From 3044809d02f3f718db4731727177463836159c63 Mon Sep 17 00:00:00 2001 From: Ajay Kumar Date: Tue, 29 Sep 2026 16:02:10 +0530 Subject: [PATCH 1/5] feat(nonstop_cli): add new members to the enclosing pub workspace `nonstop create --template package|app|plugin` run inside a mono-repo now lists the new member under the root `workspace:` and sets `resolution: workspace` in its pubspec, so `dart pub get` accepts it without manual edits. The mono template never registers itself. Co-Authored-By: Claude Opus 5.5 --- .../lib/commands/create/templates.dart | 12 ++++ packages/nonstop_cli/lib/utils/workspace.dart | 61 ++++++++++++++++ packages/nonstop_cli/pubspec.yaml | 2 +- .../test/src/utils/workspace_test.dart | 69 +++++++++++++++++++ 4 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 packages/nonstop_cli/lib/utils/workspace.dart create mode 100644 packages/nonstop_cli/test/src/utils/workspace_test.dart diff --git a/packages/nonstop_cli/lib/commands/create/templates.dart b/packages/nonstop_cli/lib/commands/create/templates.dart index 415fd3e..d3fda6b 100644 --- a/packages/nonstop_cli/lib/commands/create/templates.dart +++ b/packages/nonstop_cli/lib/commands/create/templates.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:mason/mason.dart'; import 'package:nonstop_cli/template.dart'; import 'package:nonstop_cli/utils/utils.dart'; +import 'package:nonstop_cli/utils/workspace.dart'; import 'flutter_app_for_mono_repo_bundle.dart'; import 'flutter_package_for_mono_repo_bundle.dart'; @@ -36,6 +37,7 @@ class FlutterPackageForMonoRepoTemplate extends Template { @override Future onGenerateComplete(Logger logger, Directory outputDir) async { + _joinWorkspace(logger, outputDir); logger.logSummary( outputDir: outputDir, message: 'Created a Flutter package for a Melos-managed mono-repo 🚀', @@ -53,6 +55,7 @@ class FlutterAppForMonoRepoTemplate extends Template { @override Future onGenerateComplete(Logger logger, Directory outputDir) async { + _joinWorkspace(logger, outputDir); logger.logSummary( outputDir: outputDir, message: 'Created a Flutter application for a Melos-managed mono-repo 🚀', @@ -70,9 +73,18 @@ class FlutterPluginForMonoRepoTemplate extends Template { @override Future onGenerateComplete(Logger logger, Directory outputDir) async { + _joinWorkspace(logger, outputDir); logger.logSummary( outputDir: outputDir, message: 'Created a Flutter plugin for a Melos-managed mono-repo 🚀', ); } } + +void _joinWorkspace(Logger logger, Directory member) { + final root = registerWorkspaceMember(member); + if (root != null) { + logger.info('Added ${member.path} to the workspace in ${root.path}. ' + 'Run `dart pub get` at the workspace root.'); + } +} diff --git a/packages/nonstop_cli/lib/utils/workspace.dart b/packages/nonstop_cli/lib/utils/workspace.dart new file mode 100644 index 0000000..22d77c7 --- /dev/null +++ b/packages/nonstop_cli/lib/utils/workspace.dart @@ -0,0 +1,61 @@ +import 'package:path/path.dart' as path; +import 'package:universal_io/io.dart'; +import 'package:yaml/yaml.dart'; +import 'package:yaml_edit/yaml_edit.dart'; + +/// Joins [member] to the nearest enclosing pub workspace: lists it under the +/// root `workspace:` and marks it `resolution: workspace`. +/// +/// Without both, `dart pub get` at the root rejects or ignores the new +/// package. Returns the updated root pubspec, or `null` when [member] has no +/// pubspec or no enclosing workspace (e.g. a standalone package). +File? registerWorkspaceMember(Directory member) { + final memberPubspec = File(path.join(member.path, 'pubspec.yaml')); + if (!memberPubspec.existsSync()) return null; + + final root = _findWorkspaceRoot(member.absolute.parent); + if (root == null) return null; + + final relative = path.posix.joinAll( + path.split(path.relative(member.absolute.path, from: root.parent.path)), + ); + final rootEditor = YamlEditor(root.readAsStringSync()); + final members = (rootEditor.parseAt(['workspace']) as YamlList).toList(); + if (!members.contains(relative)) { + rootEditor.appendToList(['workspace'], relative); + root.writeAsStringSync(rootEditor.toString()); + } + + final memberEditor = YamlEditor(memberPubspec.readAsStringSync()); + final resolution = memberEditor.parseAt( + ['resolution'], + orElse: () => YamlScalar.wrap(null), + ); + if (resolution.value != 'workspace') { + memberEditor.update(['resolution'], 'workspace'); + memberPubspec.writeAsStringSync(memberEditor.toString()); + } + return root; +} + +File? _findWorkspaceRoot(Directory start) { + var directory = start; + while (true) { + final pubspec = File(path.join(directory.path, 'pubspec.yaml')); + if (pubspec.existsSync()) { + try { + if (loadYaml(pubspec.readAsStringSync()) + case { + 'workspace': YamlList _, + }) { + return pubspec; + } + } on YamlException { + // An unrelated or unfinished pubspec does not identify a workspace. + } + } + final parent = directory.parent; + if (parent.path == directory.path) return null; + directory = parent; + } +} diff --git a/packages/nonstop_cli/pubspec.yaml b/packages/nonstop_cli/pubspec.yaml index 28e62e5..6677e5b 100644 --- a/packages/nonstop_cli/pubspec.yaml +++ b/packages/nonstop_cli/pubspec.yaml @@ -30,6 +30,7 @@ dependencies: process_run: ^1.2.1+1 pub_updater: ^0.6.0 universal_io: ^2.2.2 + yaml: ^3.1.4 yaml_edit: ^2.2.1 dev_dependencies: @@ -40,7 +41,6 @@ dev_dependencies: flutter_lints: ^6.0.0 mocktail: ^1.0.4 test: ^1.25.8 - yaml: ^3.1.4 executables: nonstop: diff --git a/packages/nonstop_cli/test/src/utils/workspace_test.dart b/packages/nonstop_cli/test/src/utils/workspace_test.dart new file mode 100644 index 0000000..0d160e9 --- /dev/null +++ b/packages/nonstop_cli/test/src/utils/workspace_test.dart @@ -0,0 +1,69 @@ +import 'dart:io'; + +import 'package:nonstop_cli/utils/workspace.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + late Directory root; + + setUp(() => root = Directory.systemTemp.createTempSync('workspace_test_')); + tearDown(() => root.deleteSync(recursive: true)); + + File write(String relative, String contents) => + File(p.join(root.path, relative)) + ..createSync(recursive: true) + ..writeAsStringSync(contents); + + test('lists the member and marks it resolution: workspace', () { + final rootPubspec = write( + 'pubspec.yaml', + 'name: w\nworkspace:\n - packages/core\n', + ); + final member = write('features/orders/pubspec.yaml', 'name: orders\n'); + + expect( + registerWorkspaceMember(member.parent)?.path, + rootPubspec.path, + ); + expect( + rootPubspec.readAsStringSync(), + 'name: w\nworkspace:\n - packages/core\n - features/orders\n', + ); + expect(member.readAsStringSync(), contains('resolution: workspace')); + }); + + test('is idempotent', () { + final rootPubspec = write( + 'pubspec.yaml', + 'name: w\nworkspace:\n - packages/core\n', + ); + final member = write( + 'packages/core/pubspec.yaml', + 'name: core\nresolution: workspace\n', + ); + + registerWorkspaceMember(member.parent); + + expect( + rootPubspec.readAsStringSync(), + 'name: w\nworkspace:\n - packages/core\n', + ); + expect(member.readAsStringSync(), 'name: core\nresolution: workspace\n'); + }); + + test('does nothing outside a workspace', () { + write('pubspec.yaml', 'name: standalone\n'); + final member = write('packages/a/pubspec.yaml', 'name: a\n'); + + expect(registerWorkspaceMember(member.parent), isNull); + expect(member.readAsStringSync(), 'name: a\n'); + }); + + test('does nothing without a member pubspec', () { + write('pubspec.yaml', 'name: w\nworkspace:\n - a\n'); + final member = Directory(p.join(root.path, 'b'))..createSync(); + + expect(registerWorkspaceMember(member), isNull); + }); +} From 5313aab5002a9911bc481a1aeb8b42e60e80b56f Mon Sep 17 00:00:00 2001 From: Ajay Kumar Date: Tue, 29 Sep 2026 16:02:22 +0530 Subject: [PATCH 2/5] feat(nonstop_cli): generate a Claude Code setup and harden the app template Generated mono-repos now ship a Claude Code boundary for the project: - a root CLAUDE.md (setup, run, commands, strict SOLID and Flutter rules, definition of done, communication rules) and one CLAUDE.md per area and per member, titled with the project name and gated per selected module - .claude/settings.json with command allowlist, a guard that blocks edits to generated files, and a hook that formats edited Dart files - skills: melos-workspace, new-feature, flutter-best-practices, design-system, troubleshooting - package, app and plugin bricks add a starter CLAUDE.md for new members Template fixes found while documenting it: - dashboard no longer imports auth; the app injects the guard and sign-out - sign-out unregisters the device push token when notifications are enabled - an offline Remote Config fetch no longer fails startup - no user ids, emails or names in logs or crash reports - strings via localization and colors via the theme everywhere - dependencies injected through constructors instead of di.get in build - contracts are abstract interface classes; unused dependencies removed - crashlytics, analytics, network, feature_flags and notifications READMEs rewritten from the code; leftover health-specific helpers removed - create-command syntax fixed in the area READMEs - unused material import with dashboard on and auth off Every module combination still renders; all six verify profiles pass lint, 100% line coverage and a web build. Co-Authored-By: Claude Opus 5.5 --- .../{{ name.snakeCase() }}/CLAUDE.md | 39 ++ .../{{ name.snakeCase() }}/CLAUDE.md | 46 ++ .../__brick__/{{name.snakeCase()}}/CLAUDE.md | 44 ++ .../.claude/hooks/format_dart.sh | 9 + .../.claude/hooks/guard_generated.sh | 16 + .../.claude/settings.json | 46 ++ .../.claude/skills/design-system/SKILL.md | 84 +++ .../skills/flutter-best-practices/SKILL.md | 106 ++++ .../.claude/skills/melos-workspace/SKILL.md | 93 ++++ .../.claude/skills/new-feature/SKILL.md | 132 +++++ .../.claude/skills/troubleshooting/SKILL.md | 90 ++++ .../{{ name.snakeCase() }}/.gitignore | 3 + .../{{ name.snakeCase() }}/CLAUDE.md | 270 ++++++++++ .../{{ name.snakeCase() }}/apps/CLAUDE.md | 45 ++ .../{{ name.snakeCase() }}/apps/README.md | 2 +- .../apps/{{ name.snakeCase() }}/CLAUDE.md | 95 ++++ .../lib/router/router.dart | 39 +- .../lib/ui/splash_screen.dart | 10 +- .../{{ name.snakeCase() }}/test/app_test.dart | 72 ++- .../test/entrypoint_test.dart | 5 +- .../test/startup_test.dart | 5 +- .../test/{{firebase_bootstrap_test_file}} | 12 +- .../{{ name.snakeCase() }}/features/CLAUDE.md | 66 +++ .../{{ name.snakeCase() }}/features/README.md | 2 +- .../features/{{auth_dir}}/CLAUDE.md | 90 ++++ .../{{auth_dir}}/lib/analytics/analytics.dart | 33 +- .../{{auth_dir}}/lib/config/config.dart | 2 +- .../{{auth_dir}}/lib/config/config_imp.dart | 2 +- .../{{auth_dir}}/lib/constants/routes.dart | 1 - .../lib/data/services/auth_service.dart | 2 +- .../{{auth_dir}}/lib/data/services/index.dart | 1 - .../{{auth_dir}}/lib/router/router.dart | 54 +- .../lib/ui/components/footer_builder.dart | 9 +- .../{{auth_dir}}/lib/ui/screens/index.dart | 1 - .../lib/ui/screens/register_screen.dart | 57 +- .../lib/ui/screens/sign_in_screen.dart | 47 +- .../features/{{auth_dir}}/pubspec.yaml | 5 +- .../{{auth_dir}}/test/presentation_test.dart | 55 +- .../features/{{dashboard_dir}}/CLAUDE.md | 84 +++ .../lib/router/dashboard_router.dart | 50 +- .../ui/screens/dashboard_shell_screen.dart | 8 +- .../lib/ui/screens/explore_tab_screen.dart | 9 +- .../lib/ui/screens/profile_tab_screen.dart | 56 +- .../features/{{dashboard_dir}}/pubspec.yaml | 12 +- .../test/dashboard_test.dart | 65 ++- .../{{ name.snakeCase() }}/packages/CLAUDE.md | 71 +++ .../{{ name.snakeCase() }}/packages/README.md | 2 +- .../packages/core/CLAUDE.md | 76 +++ .../packages/core/lib/bloc/global_event.dart | 7 - .../lib/bloc/global_event_channel_bloc.dart | 7 +- .../core/lib/bloc/global_event_extension.dart | 12 + .../packages/core/lib/bloc/index.dart | 16 +- .../lib/converters/datetime_converter.dart | 4 +- .../packages/core/lib/converters/index.dart | 1 - .../packages/core/lib/core.dart | 2 + .../packages/core/lib/errors/index.dart | 1 - .../packages/core/lib/logger/index.dart | 1 - .../packages/core/lib/logger/logger.dart | 2 +- .../lib/observer/core_route_observer.dart | 49 +- .../packages/core/lib/observer/index.dart | 1 - .../packages/core/lib/router/core_router.dart | 2 +- .../packages/core/pubspec.yaml | 3 +- .../packages/core/test/core_test.dart | 61 ++- .../packages/design_system/CLAUDE.md | 90 ++++ ...{asset_image.dart => app_asset_image.dart} | 4 +- .../design_system/lib/components/header.dart | 8 +- .../design_system/lib/components/index.dart | 3 +- .../design_system/lib/design_system.dart | 3 +- .../lib/dialogs/file_info_dialog.dart | 9 +- .../lib/utils/extensions/index.dart | 1 - .../design_system/lib/utils/index.dart | 1 - .../design_system/test/components_test.dart | 2 +- .../design_system/test/integration_test.dart | 9 +- .../packages/di/CLAUDE.md | 60 +++ .../di/lib/src/dependency_injection.dart | 4 +- .../di/lib/src/dependency_injection_imp.dart | 45 +- .../packages/di/test/di_test.dart | 38 +- .../packages/di/test/lifecycle_test.dart | 19 + .../packages/localization/CLAUDE.md | 54 ++ .../packages/localization/README.md | 22 +- .../packages/localization/build.yaml | 3 - .../localization/lib/messages.i69n.dart | 47 +- .../localization/lib/messages.i69n.yaml | 13 +- .../lib/src/localization_provider.dart | 29 +- .../localization/lib/src/strings.dart | 2 +- .../localization/test/localization_test.dart | 4 +- .../packages/utils/CLAUDE.md | 53 ++ .../utils/lib/src/date_time_formatter.dart | 37 ++ .../utils/lib/src/number_formatter.dart | 55 +- .../packages/utils/lib/utils.dart | 1 + ...rmatter_test.dart => formatters_test.dart} | 34 +- .../packages/{{analytics_dir}}/CLAUDE.md | 67 +++ .../packages/{{analytics_dir}}/README.md | 271 ++-------- .../{{analytics_dir}}/lib/analytics.dart | 4 +- .../lib/src/client/analytics_client.dart | 2 +- .../src/client/firebase_analytics_client.dart | 49 +- .../lib/src/config/analytics_config.dart | 2 +- .../lib/src/utils/analytics_helper.dart | 22 +- .../{{analytics_dir}}/test/client_test.dart | 43 ++ .../packages/{{crashlytics_dir}}/CLAUDE.md | 60 +++ .../packages/{{crashlytics_dir}}/README.md | 292 ++-------- .../{{crashlytics_dir}}/lib/crashlytics.dart | 10 +- .../lib/src/client/crashlytics_client.dart | 8 +- .../client/firebase_crashlytics_client.dart | 66 +-- .../lib/src/config/crashlytics_config.dart | 25 +- .../lib/src/models/crash_report.dart | 73 --- .../lib/src/models/index.dart | 1 - .../lib/src/models/user_metadata.dart | 29 +- .../packages/{{crashlytics_dir}}/pubspec.yaml | 1 - .../{{crashlytics_dir}}/test/client_test.dart | 40 +- .../test/crashlytics_test.dart | 71 +-- .../{{crashlytics_dir}}/test/models_test.dart | 44 +- .../packages/{{developer_dir}}/CLAUDE.md | 58 ++ .../lib/src/routes/developer_routes.dart | 14 +- .../lib/src/screens/developer_screen.dart | 15 +- .../src/widgets/open_dev_tools_wrapper.dart | 4 +- .../packages/{{developer_dir}}/pubspec.yaml | 4 +- .../test/developer_test.dart | 4 +- .../test/navigation_test.dart | 9 +- .../packages/{{feature_flags_dir}}/CLAUDE.md | 61 +++ .../packages/{{feature_flags_dir}}/README.md | 81 ++- .../lib/feature_flags.dart | 25 +- .../lib/src/client/feature_flag.dart | 33 ++ .../lib/src/client/feature_flag_service.dart | 79 +++ .../lib/src/client/index.dart | 2 + .../lib/src/config/feature_flags_config.dart | 16 + .../lib/src/config/index.dart | 1 + .../feature_flags_di.dart} | 14 +- .../lib/src/di/index.dart | 1 + .../lib/src/feature_flag_service.dart | 95 ---- .../{{feature_flags_dir}}/lib/src/index.dart | 5 - .../feature_flag_provider.dart | 4 +- .../firebase_remote_config_provider.dart | 49 +- .../lib/src/providers/index.dart | 2 + .../{ => widgets}/feature_flag_wrapper.dart | 33 +- .../lib/src/widgets/index.dart | 1 + .../{{feature_flags_dir}}/pubspec.yaml | 1 - .../test/feature_flags_test.dart | 56 +- .../packages/{{network_dir}}/CLAUDE.md | 73 +++ .../packages/{{network_dir}}/README.md | 74 ++- .../packages/{{network_dir}}/lib/network.dart | 66 +-- .../{{network_dir}}/lib/src/api/index.dart | 1 - .../lib/src/auth/auth_token_provider.dart | 3 +- .../lib/src/client/dio_network_client.dart | 37 +- .../lib/src/client/network_client.dart | 2 +- .../lib/src/config/network_config.dart | 2 +- .../src/exceptions/network_exceptions.dart | 2 +- .../packages/{{network_dir}}/pubspec.yaml | 2 - .../test/dio_network_client_test.dart | 62 ++- .../{{network_dir}}/test/models_test.dart | 8 + .../packages/{{notifications_dir}}/CLAUDE.md | 72 +++ .../packages/{{notifications_dir}}/README.md | 69 +++ .../lib/notifications.dart | 4 +- .../client/firebase_notification_client.dart | 28 +- .../lib/src/client/notification_client.dart | 15 +- .../lib/src/device_info/device_info.dart | 4 +- .../lib/src/di/notification_di.dart | 37 +- .../lib/src/models/device_token_models.dart | 12 - .../lib/src/models/device_token_models.g.dart | 8 - .../notification_permission_manager.dart | 11 +- .../services/notification_token_manager.dart | 19 +- .../{{notifications_dir}}/pubspec.yaml | 1 - .../test/client_test.dart | 23 + .../test/services_test.dart | 2 - .../{{ name.snakeCase() }}/plugins/CLAUDE.md | 26 + .../{{ name.snakeCase() }}/plugins/README.md | 2 +- .../flutter_app_for_mono_repo_bundle.dart | 6 + .../flutter_package_for_mono_repo_bundle.dart | 6 + .../flutter_plugin_for_mono_repo_bundle.dart | 6 + ...flutter_project_with_mono_repo_bundle.dart | 499 +++++++++++++----- 170 files changed, 4164 insertions(+), 1807 deletions(-) create mode 100644 packages/nonstop_cli/bricks/flutter_app_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_package_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_plugin_for_mono_repo/__brick__/{{name.snakeCase()}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/format_dart.sh create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/guard_generated.sh create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/settings.json create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/design-system/SKILL.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/flutter-best-practices/SKILL.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/melos-workspace/SKILL.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/new-feature/SKILL.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/troubleshooting/SKILL.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/apps/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/apps/{{ name.snakeCase() }}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/features/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/features/{{auth_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/features/{{dashboard_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/lib/bloc/global_event_extension.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/design_system/CLAUDE.md rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/design_system/lib/components/{asset_image.dart => app_asset_image.dart} (94%) create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/di/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/localization/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/utils/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/utils/lib/src/date_time_formatter.dart rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/utils/test/{number_formatter_test.dart => formatters_test.dart} (53%) create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{analytics_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{crashlytics_dir}}/CLAUDE.md delete mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{crashlytics_dir}}/lib/src/models/crash_report.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{developer_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/client/feature_flag.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/client/feature_flag_service.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/client/index.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/config/feature_flags_config.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/config/index.dart rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/{register.dart => di/feature_flags_di.dart} (71%) create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/di/index.dart delete mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/feature_flag_service.dart delete mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/index.dart rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/{ => providers}/feature_flag_provider.dart (83%) rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/{ => providers}/firebase_remote_config_provider.dart (74%) create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/providers/index.dart rename packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/{ => widgets}/feature_flag_wrapper.dart (63%) create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{feature_flags_dir}}/lib/src/widgets/index.dart create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{network_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{notifications_dir}}/CLAUDE.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/{{notifications_dir}}/README.md create mode 100644 packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/plugins/CLAUDE.md diff --git a/packages/nonstop_cli/bricks/flutter_app_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md b/packages/nonstop_cli/bricks/flutter_app_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md new file mode 100644 index 0000000..75d18c5 --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_app_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md @@ -0,0 +1,39 @@ +# {{ name.titleCase() }} + +{{ description }} + +The contract for agents working in this app. Read the repository root +`CLAUDE.md` and the area `CLAUDE.md` above this directory (`apps/`) +first, and do not repeat their rules here. Update this file in the same change as the code it +describes. + +## Composition + +| Path | Responsibility | +|---|---| +| `lib/main.dart` | Entry point: bootstrap, build the router, mount the app | +| `lib/` | Wiring only: bootstrap order, router, app-only screens | +| `test/` | Startup, routing and lifecycle tests | + +## Rules + +- This app is a composition root: it wires features and packages and owns no + business logic. Move anything reusable into `features/` or `packages/`. +- `di.get` is allowed here; this is the composition edge. +- Environment values are `--dart-define`s declared in + `packages/core/lib/constants/environment.dart`. +- App-only UI follows the `design-system` skill. + +## Common changes + +_Add two to four recipes for the changes people make here, naming the files to +touch and the test to add._ + +## Tests + +Run `dart run melos exec --scope={{ name.snakeCase() }} -- flutter test`. Keep +`dart run melos run coverage` at 100%: the gate fails a member without tests. + +## Gotchas + +_None yet. Record real ones as you find them._ diff --git a/packages/nonstop_cli/bricks/flutter_package_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md b/packages/nonstop_cli/bricks/flutter_package_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md new file mode 100644 index 0000000..1b29080 --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_package_for_mono_repo/__brick__/{{ name.snakeCase() }}/CLAUDE.md @@ -0,0 +1,46 @@ +# {{ name.titleCase() }} + +{{ description }} + +The contract for agents working in this package. Read the repository root +`CLAUDE.md` and the area `CLAUDE.md` above this directory (`packages/` or `features/`) +first, and do not repeat their rules here. Update this file in the same change as the code it +describes. + +## Public API + +| Symbol | Kind | Use | +|---|---|---| +| _Each exported class, function and `init()`_ | | | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/{{ name.snakeCase() }}.dart` | Public barrel: the only import other members use | +| `lib/src/` | Implementation, grouped by role (`client/`, `config/`, `models/`, ...) | +| `test/` | Tests for every public behavior | + +## Rules + +- Depend only on lower layers (see `packages/CLAUDE.md`); never on an app or + another feature. +- Contracts are `abstract interface class`; implementations take their + dependencies through the constructor. +- User-facing text comes from `localization`; visuals come from + `design_system` (load the `design-system` skill before UI work). +- Register implementations with `di` only from this package's `init()`. + +## Common changes + +_Add two to four recipes for the changes people make here, naming the files to +touch and the test to add._ + +## Tests + +Run `dart run melos exec --scope={{ name.snakeCase() }} -- flutter test`. Keep +`dart run melos run coverage` at 100%: the gate fails a member without tests. + +## Gotchas + +_None yet. Record real ones as you find them._ diff --git a/packages/nonstop_cli/bricks/flutter_plugin_for_mono_repo/__brick__/{{name.snakeCase()}}/CLAUDE.md b/packages/nonstop_cli/bricks/flutter_plugin_for_mono_repo/__brick__/{{name.snakeCase()}}/CLAUDE.md new file mode 100644 index 0000000..5bf0f6e --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_plugin_for_mono_repo/__brick__/{{name.snakeCase()}}/CLAUDE.md @@ -0,0 +1,44 @@ +# {{ name.titleCase() }} + +{{ description }} + +The contract for agents working in this plugin. Read the repository root +`CLAUDE.md` and the area `CLAUDE.md` above this directory (`plugins/`) +first, and do not repeat their rules here. Update this file in the same change as the code it +describes. + +## Public API + +| Symbol | Kind | Use | +|---|---|---| +| _The Dart contract other members use_ | | | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/` | Dart contract; channel names and argument maps stay private | +| `android/`, `ios/`, ... | Native implementations for each declared platform | +| `test/` | Channel tests with `TestDefaultBinaryMessengerBinding` | + +## Rules + +- A plugin depends on nothing in `apps/`, `features/` or `packages/`. +- Convert `PlatformException` into typed exceptions at the boundary. +- Every platform declared in `pubspec.yaml` is implemented or throws + `UnimplementedError` with a clear message. +- Never block the platform main thread in native code. + +## Common changes + +_Add two to four recipes for the changes people make here, naming the files to +touch and the test to add._ + +## Tests + +Run `dart run melos exec --scope={{ name.snakeCase() }} -- flutter test`. Keep +`dart run melos run coverage` at 100%: the gate fails a member without tests. + +## Gotchas + +_None yet. Record real ones as you find them._ diff --git a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/format_dart.sh b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/format_dart.sh new file mode 100644 index 0000000..96d046d --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/format_dart.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# PostToolUse(Edit|Write|MultiEdit): format the Dart file that was just written, +# so the lint gate never fails on formatting. Always exits 0. +path=$(sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1) +case "$path" in + *.g.dart|*.freezed.dart|*.i69n.dart) ;; + *.dart) [ -f "$path" ] && dart format "$path" >/dev/null 2>&1 ;; +esac +exit 0 diff --git a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/guard_generated.sh b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/guard_generated.sh new file mode 100644 index 0000000..3cbb2f3 --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/hooks/guard_generated.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# PreToolUse(Edit|Write|MultiEdit): refuse hand edits to generated files. +# Fails open: anything unexpected exits 0 so a broken hook never blocks work. +path=$(sed -n 's/.*"file_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1) +case "$path" in + *.g.dart|*.freezed.dart|*.i69n.dart) + echo "Blocked: $path is generated. Edit its source, then run 'dart run melos run generate' (or 'generate:i69n' for localization)." >&2 + exit 2 ;; + */design_system/lib/generated/*) + echo "Blocked: $path comes from Material Theme Builder. Replace the file wholesale with a new export." >&2 + exit 2 ;; + *pubspec.lock) + echo "Blocked: pubspec.lock is written by 'dart pub get'. Change pubspec.yaml instead." >&2 + exit 2 ;; +esac +exit 0 diff --git a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/settings.json b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/settings.json new file mode 100644 index 0000000..f361b18 --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/settings.json @@ -0,0 +1,46 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "permissions": { + "allow": [ + "Bash(dart pub get)", + "Bash(dart run melos bootstrap)", + "Bash(dart run melos list:*)", + "Bash(dart run melos run lint)", + "Bash(dart run melos run test)", + "Bash(dart run melos run coverage)", + "Bash(dart run melos run generate)", + "Bash(dart run melos run generate:i69n)", + "Bash(dart run tool/check.dart)", + "Bash(dart run tool/coverage.dart:*)", + "Bash(dart format:*)", + "Bash(dart analyze:*)", + "Bash(flutter test:*)", + "Bash(flutter --version)", + "Bash(flutter doctor:*)" + ], + "deny": [ + "Read(**/.env)", + "Read(**/*.keystore)", + "Read(**/*.jks)", + "Read(**/key.properties)" + ] + }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard_generated.sh\"", "timeout": 5 } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/format_dart.sh\"", "timeout": 30 } + ] + } + ] + } +} diff --git a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/design-system/SKILL.md b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/design-system/SKILL.md new file mode 100644 index 0000000..4079620 --- /dev/null +++ b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/.claude/skills/design-system/SKILL.md @@ -0,0 +1,84 @@ +--- +name: design-system +description: Visual design rules for every screen and widget in this repo - where colors, typography, shapes, icons, feedback (toasts, loaders, errors) and images come from, when a widget belongs in packages/design_system, how to add or change a shared component, theming both brightnesses, and the UI review checklist. Load before building or reviewing any UI in apps, features, packages or plugins. +--- + +# Design system + +`packages/design_system` is the single source of visual truth. Features +compose it; they do not restyle it. Package details and gotchas are in +`packages/design_system/CLAUDE.md`. + +## Where every visual value comes from + +| Need | Use | Never | +|---|---|---| +| Color | `Theme.of(context).colorScheme.` (`primary`, `onPrimary`, `surface`, `onSurfaceVariant`, `error`, `outlineVariant`, ...) | `Color(0x...)`, `Colors.*`, opacity hacks for meaning | +| Text | `Theme.of(context).textTheme. + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/main/res/values/styles.xml b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/profile/AndroidManifest.xml b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/build.gradle.kts b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle.properties b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle/wrapper/gradle-wrapper.properties b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a20f2c4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/settings.gradle.kts b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/settings.gradle.kts new file mode 100644 index 0000000..b28021a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/.gitignore b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/AppFrameworkInfo.plist b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Debug.xcconfig b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Release.xcconfig b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Podfile b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Podfile new file mode 100644 index 0000000..9d7ef08 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '15.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.pbxproj b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..d0691a1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,647 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = io.nonstop.nonstopExample; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c3fedb2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/contents.xcworkspacedata b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/AppDelegate.swift b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..dc9ada4725e9b0ddb1deab583e5b5102493aa332 GIT binary patch literal 10932 zcmeHN2~<R zh`|8`A_PQ1nSu(UMFx?8j8PC!!VDphaL#`F42fd#7Vlc`zIE4n%Y~eiz4y1j|NDpi z?<@|pSJ-HM`qifhf@m%MamgwK83`XpBA<+azdF#2QsT{X@z0A9Bq>~TVErigKH1~P zRX-!h-f0NJ4Mh++{D}J+K>~~rq}d%o%+4dogzXp7RxX4C>Km5XEI|PAFDmo;DFm6G zzjVoB`@qW98Yl0Kvc-9w09^Prs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jR1ZN09$YO%_iBqh5ftzSpMQQtxKFU=FYmP zeY^jph+g<4>YO;U^O>-NFLn~-RqlHvnZl2yd2A{Yc1G@Ga$d+Q&(f^tnPf+Z7serIU};17+2DU_f4Z z@GaPFut27d?!YiD+QP@)T=77cR9~MK@bd~pY%X(h%L={{OIb8IQmf-!xmZkm8A0Ga zQSWONI17_ru5wpHg3jI@i9D+_Y|pCqVuHJNdHUauTD=R$JcD2K_liQisqG$(sm=k9;L* z!L?*4B~ql7uioSX$zWJ?;q-SWXRFhz2Jt4%fOHA=Bwf|RzhwqdXGr78y$J)LR7&3T zE1WWz*>GPWKZ0%|@%6=fyx)5rzUpI;bCj>3RKzNG_1w$fIFCZ&UR0(7S?g}`&Pg$M zf`SLsz8wK82Vyj7;RyKmY{a8G{2BHG%w!^T|Njr!h9TO2LaP^_f22Q1=l$QiU84ao zHe_#{S6;qrC6w~7{y(hs-?-j?lbOfgH^E=XcSgnwW*eEz{_Z<_xN#0001NP)t-s|Ns9~ z#rXRE|M&d=0au&!`~QyF`q}dRnBDt}*!qXo`c{v z{Djr|@Adh0(D_%#_&mM$D6{kE_x{oE{l@J5@%H*?%=t~i_`ufYOPkAEn!pfkr2$fs z652Tz0001XNklqeeKN4RM4i{jKqmiC$?+xN>3Apn^ z0QfuZLym_5b<*QdmkHjHlj811{If)dl(Z2K0A+ekGtrFJb?g|wt#k#pV-#A~bK=OT ts8>{%cPtyC${m|1#B1A6#u!Q;umknL1chzTM$P~L002ovPDHLkV1lTfnu!1a literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..797d452e458972bab9d994556c8305db4c827017 GIT binary patch literal 406 zcmV;H0crk;P))>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed2d933e1120817fe9182483a228007b18ab6ae GIT binary patch literal 450 zcmV;z0X_bSP)iGWQ_5NJQ_~rNh*z)}eT%KUb z`7gNk0#AwF^#0T0?hIa^`~Ck;!}#m+_uT050aTR(J!bU#|IzRL%^UsMS#KsYnTF*!YeDOytlP4VhV?b} z%rz_<=#CPc)tU1MZTq~*2=8~iZ!lSa<{9b@2Jl;?IEV8)=fG217*|@)CCYgFze-x? zIFODUIA>nWKpE+bn~n7;-89sa>#DR>TSlqWk*!2hSN6D~Qb#VqbP~4Fk&m`@1$JGr zXPIdeRE&b2Thd#{MtDK$px*d3-Wx``>!oimf%|A-&-q*6KAH)e$3|6JV%HX{Hig)k suLT-RhftRq8b9;(V=235Wa|I=027H2wCDra;{X5v07*qoM6N<$f;9x^2LJ#7 literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd7b0099ca80c806f8fe495613e8d6c69460d76 GIT binary patch literal 282 zcmV+#0p(^bcu7P-R4C8Q z&e;xxFbF_Vrezo%_kH*OKhshZ6BFpG-Y1e10`QXJKbND7AMQ&cMj60B5TNObaZxYybcN07*qoM6N<$g3m;S%K!iX literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..fe730945a01f64a61e2235dbe3f45b08f7729182 GIT binary patch literal 462 zcmV;<0WtoGP)-}iV`2<;=$?g5M=KQbZ{F&YRNy7Nn@%_*5{gvDM0aKI4?ESmw z{NnZg)A0R`+4?NF_RZexyVB&^^ZvN!{I28tr{Vje;QNTz`dG&Jz0~Ek&f2;*Z7>B|cg}xYpxEFY+0YrKLF;^Q+-HreN0P{&i zK~zY`?b7ECf-n?@;d<&orQ*Q7KoR%4|C>{W^h6@&01>0SKS`dn{Q}GT%Qj_{PLZ_& zs`MFI#j-(>?bvdZ!8^xTwlY{qA)T4QLbY@j(!YJ7aXJervHy6HaG_2SB`6CC{He}f zHVw(fJWApwPq!6VY7r1w-Fs)@ox~N+q|w~e;JI~C4Vf^@d>Wvj=fl`^u9x9wd9 zR%3*Q+)t%S!MU_`id^@&Y{y7-r98lZX0?YrHlfmwb?#}^1b{8g&KzmkE(L>Z&)179 zp<)v6Y}pRl100G2FL_t(o!|l{-Q-VMg#&MKg7c{O0 z2wJImOS3Gy*Z2Qifdv~JYOp;v+U)a|nLoc7hNH;I$;lzDt$}rkaFw1mYK5_0Q(Sut zvbEloxON7$+HSOgC9Z8ltuC&0OSF!-mXv5caV>#bc3@hBPX@I$58-z}(ZZE!t-aOG zpjNkbau@>yEzH(5Yj4kZiMH32XI!4~gVXNnjAvRx;Sdg^`>2DpUEwoMhTs_st8pKG z(%SHyHdU&v%f36~uERh!bd`!T2dw;z6PrOTQ7Vt*#9F2uHlUVnb#ev_o^fh}Dzmq} zWtlk35}k=?xj28uO|5>>$yXadTUE@@IPpgH`gJ~Ro4>jd1IF|(+IX>8M4Ps{PNvmI zNj4D+XgN83gPt_Gm}`Ybv{;+&yu-C(Grdiahmo~BjG-l&mWM+{e5M1sm&=xduwgM9 z`8OEh`=F3r`^E{n_;%9weN{cf2%7=VzC@cYj+lg>+3|D|_1C@{hcU(DyQG_BvBWe? zvTv``=%b1zrol#=R`JB)>cdjpWt&rLJgVp-t?DREyuq1A%0Z4)6_WsQ7{nzjN zo!X zGXV)2i3kcZIL~_j>uIKPK_zib+3T+Nt3Mb&Br)s)UIaA}@p{wDda>7=Q|mGRp7pqY zkJ!7E{MNz$9nOwoVqpFb)}$IP24Wn2JJ=Cw(!`OXJBr45rP>>AQr$6c7slJWvbpNW z@KTwna6d?PP>hvXCcp=4F;=GR@R4E7{4VU^0p4F>v^#A|>07*qoM6N<$f*5nx ACIA2c literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..502f463a9bc882b461c96aadf492d1729e49e725 GIT binary patch literal 586 zcmV-Q0=4~#P)+}#`wDE{8-2Mebf5<{{PqV{TgVcv*r8?UZ3{-|G?_}T*&y;@cqf{ z{Q*~+qr%%p!1pS*_Uicl#q9lc(D`!D`LN62sNwq{oYw(Wmhk)k<@f$!$@ng~_5)Ru z0Z)trIA5^j{DIW^c+vT2%lW+2<(RtE2wR;4O@)Tm`Xr*?A(qYoM}7i5Yxw>D(&6ou zxz!_Xr~yNF+waPe00049Nkl*;a!v6h%{rlvIH#gW3s8p;bFr=l}mRqpW2h zw=OA%hdyL~z+UHOzl0eKhEr$YYOL-c-%Y<)=j?(bzDweB7{b+%_ypvm_cG{SvM=DK zhv{K@m>#Bw>2W$eUI#iU)Wdgs8Y3U+A$Gd&{+j)d)BmGKx+43U_!tik_YlN)>$7G! zhkE!s;%oku3;IwG3U^2kw?z+HM)jB{@zFhK8P#KMSytSthr+4!c(5c%+^UBn`0X*2 zy3(k600_CSZj?O$Qu%&$;|TGUJrptR(HzyIx>5E(2r{eA(<6t3e3I0B)7d6s7?Z5J zZ!rtKvA{MiEBm&KFtoifx>5P^Z=vl)95XJn()aS5%ad(s?4-=Tkis9IGu{`Fy8r+H07*qoM6N<$f20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0ec303439225b78712f49115768196d8d76f6790 GIT binary patch literal 862 zcmV-k1EKthP)20Z)wqMt%V?S?~D#06};F zA3KcL`Wb+>5ObvgQIG&ig8(;V04hz?@cqy3{mSh8o!|U|)cI!1_+!fWH@o*8vh^CU z^ws0;(c$gI+2~q^tO#GDHf@=;DncUw00J^eL_t(&-tE|HQ`%4vfZ;WsBqu-$0nu1R zq^Vj;p$clf^?twn|KHO+IGt^q#a3X?w9dXC@*yxhv&l}F322(8Y1&=P&I}~G@#h6; z1CV9ecD9ZEe87{{NtI*)_aJ<`kJa z?5=RBtFF50s;jQLFil-`)m2wrb=6h(&brpj%nG_U&ut~$?8Rokzxi8zJoWr#2dto5 zOX_URcc<1`Iky+jc;A%Vzx}1QU{2$|cKPom2Vf1{8m`vja4{F>HS?^Nc^rp}xo+Nh zxd}eOm`fm3@MQC1< zIk&aCjb~Yh%5+Yq0`)D;q{#-Uqlv*o+Oor zE!I71Z@ASH3grl8&P^L0WpavHoP|UX4e?!igT`4?AZk$hu*@%6WJ;zDOGlw7kj@ zY5!B-0ft0f?Lgb>C;$Ke07*qoM6N<$f~t1N9smFU literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..e9f5fea27c705180eb716271f41b582e76dcbd90 GIT binary patch literal 1674 zcmV;526g#~P){YQnis^a@{&-nmRmq)<&%Mztj67_#M}W?l>kYSliK<%xAp;0j{!}J0!o7b zE>q9${Lb$D&h7k=+4=!ek^n+`0zq>LL1O?lVyea53S5x`Nqqo2YyeuIrQrJj9XjOp z{;T5qbj3}&1vg1VK~#9!?b~^C5-}JC@Pyrv-6dSEqJq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N_IrA;5xm~3?3!StX}pUv0vkxMaqm+zxrg7X7(I&*N~&dEd0kD z-FRV|g=|QuUsuh>-xCI}vD2imzYIOIdcCVV=$Bz@*u0+Bs<|L^)32nN*=wu3n%Ynw z@1|eLG>!8ruU1pFXUfb`j>(=Gy~?Rn4QJ-c3%3T|(Frd!bI`9u&zAnyFYTqlG#&J7 zAkD(jpw|oZLNiA>;>hgp1KX7-wxC~31II47gc zHcehD6Uxlf%+M^^uN5Wc*G%^;>D5qT{>=uxUhX%WJu^Z*(_Wq9y}npFO{Hhb>s6<9 zNi0pHXWFaVZnb)1+RS&F)xOv6&aeILcI)`k#0YE+?e)5&#r7J#c`3Z7x!LpTc01dx zrdC3{Z;joZ^KN&))zB_i)I9fWedoN>Zl-6_Iz+^G&*ak2jpF07*qoM6N<$f;w%0(f|Me literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..0467bf12aa4d28f374bb26596605a46dcbb3e7c8 GIT binary patch literal 1418 zcmV;51$Fv~P)q zKfU)WzW*n(@|xWGCA9ScMt*e9`2kdxPQ&&>|-UCa7_51w+ zLUsW@ZzZSW0y$)Hp~e9%PvP|a03ks1`~K?q{u;6NC8*{AOqIUq{CL&;p56Lf$oQGq z^={4hPQv)y=I|4n+?>7Fim=dxt1 z2H+Dm+1+fh+IF>G0SjJMkQQre1x4|G*Z==(Ot&kCnUrL4I(rf(ucITwmuHf^hXiJT zkdTm&kdTm&kdTm&kdP`esgWG0BcWCVkVZ&2dUwN`cgM8QJb`Z7Z~e<&Yj2(}>Tmf` zm1{eLgw!b{bXkjWbF%dTkTZEJWyWOb##Lfw4EK2}<0d6%>AGS{po>WCOy&f$Tay_> z?NBlkpo@s-O;0V%Y_Xa-G#_O08q5LR*~F%&)}{}r&L%Sbs8AS4t7Y0NEx*{soY=0MZExqA5XHQkqi#4gW3 zqODM^iyZl;dvf)-bOXtOru(s)Uc7~BFx{w-FK;2{`VA?(g&@3z&bfLFyctOH!cVsF z7IL=fo-qBndRUm;kAdXR4e6>k-z|21AaN%ubeVrHl*<|s&Ax@W-t?LR(P-24A5=>a z*R9#QvjzF8n%@1Nw@?CG@6(%>+-0ASK~jEmCV|&a*7-GKT72W<(TbSjf)&Eme6nGE z>Gkj4Sq&2e+-G%|+NM8OOm5zVl9{Z8Dd8A5z3y8mZ=4Bv4%>as_{9cN#bm~;h>62( zdqY93Zy}v&c4n($Vv!UybR8ocs7#zbfX1IY-*w~)p}XyZ-SFC~4w>BvMVr`dFbelV{lLL0bx7@*ZZdebr3`sP;? zVImji)kG)(6Juv0lz@q`F!k1FE;CQ(D0iG$wchPbKZQELlsZ#~rt8#90Y_Xh&3U-< z{s<&cCV_1`^TD^ia9!*mQDq& zn2{r`j};V|uV%_wsP!zB?m%;FeaRe+X47K0e+KE!8C{gAWF8)lCd1u1%~|M!XNRvw zvtqy3iz0WSpWdhn6$hP8PaRBmp)q`#PCA`Vd#Tc$@f1tAcM>f_I@bC)hkI9|o(Iqv zo}Piadq!j76}004RBio<`)70k^`K1NK)q>w?p^C6J2ZC!+UppiK6&y3Kmbv&O!oYF z34$0Z;QO!JOY#!`qyGH<3Pd}Pt@q*A0V=3SVtWKRR8d8Z&@)3qLPA19LPA19LPEUC YUoZo%k(ykuW&i*H07*qoM6N<$f+CH{y8r+H literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9da19eacad3b03bb08bbddbbf4ac48dd78b3d838 GIT binary patch literal 68 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx0wlM}@Gt=>Zci7-kcv6Uzs@r-FtIZ-&5|)J Q1PU{Fy85}Sb4q9e0B4a5jsO4v literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/Main.storyboard b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Info.plist b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Info.plist new file mode 100644 index 0000000..42aef6d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Nonstop Example + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + nonstop_example + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Runner-Bridging-Header.h b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/SceneDelegate.swift b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/RunnerTests/RunnerTests.swift b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/app.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/app.dart new file mode 100644 index 0000000..12b9946 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/app.dart @@ -0,0 +1,26 @@ +import 'package:core/core.dart'; +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +/// The application view. Its owner creates and disposes the router. +class App extends StatelessWidget { + const App({required this.router, super.key}); + + final GoRouter router; + + @override + Widget build(BuildContext context) { + return GlobalEventChannelProvider( + child: DesignSystemWrapper( + builder: (context, theme) => MaterialApp.router( + debugShowCheckedModeBanner: false, + title: strings.app.name, + theme: theme, + routerConfig: router, + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/bootstrap.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/bootstrap.dart new file mode 100644 index 0000000..33836f0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/bootstrap.dart @@ -0,0 +1,100 @@ +import 'package:analytics/analytics.dart' as analytics; + +import 'package:auth/auth.dart' as auth; + +import 'package:bloc/bloc.dart'; +import 'package:core/core.dart' as core; +import 'package:core/developer/emulators.dart' as emulators; + +import 'package:core/logger/logger.dart'; +import 'package:crashlytics/crashlytics.dart' as crashlytics; + +import 'package:di/di.dart'; +import 'package:design_system/toast/toasts.dart'; + +import 'package:feature_flags/feature_flags.dart' as feature_flags; + +import 'package:firebase_core/firebase_core.dart'; + +import 'package:flutter/widgets.dart'; +import 'package:network/network.dart' as network; + +import 'package:notifications/notifications.dart' as notifications; + +import 'package:nonstop_example/firebase_options.dart'; + +/// Brings every module up, in dependency order, before the first frame. +/// +/// Order matters: the logger is registered first so everything after it can +/// report failures, and Firebase must be live before any Firebase-backed +/// module initialises. If `flutterfire configure` has not been run yet, those +/// modules are skipped so the rest of the app still boots. +Future init({ + void Function(String route)? onOpenRoute, + FirebaseOptions? firebaseOptions, + bool useEmulators = core.Environment.useEmulators, +}) async { + WidgetsFlutterBinding.ensureInitialized(); + final stopwatch = Stopwatch()..start(); + + await core.init(); + final logger = di.get(); + logger.i('Core ready in ${stopwatch.elapsedMilliseconds} ms'); + + Bloc.observer = core.CoreBlocObserver(); + + var firebaseReady = false; + FirebaseOptions? resolvedOptions; + try { + resolvedOptions = firebaseOptions ?? DefaultFirebaseOptions.currentPlatform; + await Firebase.initializeApp(options: resolvedOptions); + firebaseReady = true; + if (useEmulators) { + await emulators.init(); + } + } on UnsupportedError catch (error) { + logger.w('$error'); + } + logger.i( + firebaseReady + ? 'Firebase ready' + : 'Firebase not configured yet; skipping Firebase modules', + ); + + if (firebaseReady) await crashlytics.init(); + + if (firebaseReady) await analytics.init(); + + if (firebaseReady) await feature_flags.init(); + + if (firebaseReady) { + final clientId = + resolvedOptions!.iosClientId ?? resolvedOptions.androidClientId ?? ''; + await auth.init(auth.DefaultAuthConfig(clientId: clientId)); + } + + await network.init( + config: network.DefaultNetworkConfig(baseUrl: core.Environment.baseUrl), + ); + + if (firebaseReady) { + await notifications.init( + config: notifications.NotificationConfig( + onForeground: (title, body) => + Toast.notification(title: title, body: body), + onOpenRoute: onOpenRoute, + ), + ); + } + + // TODO: initialise your own feature modules here. + + stopwatch.stop(); + logger.i('Bootstrap completed in ${stopwatch.elapsedMilliseconds} ms'); + + if (firebaseReady) { + await analytics.AnalyticsHelper.logAppOpen( + parameters: {'bootstrap_duration': stopwatch.elapsedMilliseconds}, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/firebase_options.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/firebase_options.dart new file mode 100644 index 0000000..04ff172 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/firebase_options.dart @@ -0,0 +1,17 @@ +// This file is a placeholder. Generate the real one with: +// +// cd apps/nonstop_example && flutterfire configure +// +// FlutterFire overwrites this file with your project's options and also drops +// google-services.json / GoogleService-Info.plist into the native folders. +// Until then, bootstrap catches the throw and skips Firebase-backed modules +// so the rest of the app still runs. +import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; + +abstract final class DefaultFirebaseOptions { + static FirebaseOptions get currentPlatform => throw UnsupportedError( + 'Firebase has not been configured for Nonstop Example.\n' + 'Run `flutterfire configure` inside apps/nonstop_example ' + 'to replace lib/firebase_options.dart.', + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/main.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/main.dart new file mode 100644 index 0000000..ebea9a8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/main.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:core/core.dart'; + +import 'package:di/di.dart'; +import 'package:go_router/go_router.dart'; +import 'package:notifications/notifications.dart'; + +import 'package:nonstop_example/app.dart'; +import 'package:nonstop_example/bootstrap.dart' as bootstrap; +import 'package:nonstop_example/notification_lifecycle.dart'; + +import 'package:nonstop_example/router/router.dart'; + +Future main() => startApp(); + +/// Composition root. Queue cold-start notification routes until routing exists. +Future startApp({ + Future Function(void Function(String) onOpenRoute)? initialize, + void Function(Widget) mount = runApp, +}) async { + GoRouter? activeRouter; + String? pendingRoute; + void onOpenRoute(String route) { + if (activeRouter == null) { + pendingRoute = route; + } else { + activeRouter.go(route); + } + } + + if (initialize == null) { + await bootstrap.init(onOpenRoute: onOpenRoute); + } else { + await initialize(onOpenRoute); + } + final router = AppRouter.createRouter(initialLocation: pendingRoute); + activeRouter = router; + di.register(router, dispose: (router) => router.dispose()); + mount( + NotificationLifecycle( + logger: di.get(), + client: di.has() + ? di.get() + : null, + child: App(router: router), + ), + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/notification_lifecycle.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/notification_lifecycle.dart new file mode 100644 index 0000000..481ab7c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/notification_lifecycle.dart @@ -0,0 +1,59 @@ +import 'package:core/core.dart'; +import 'package:flutter/widgets.dart'; +import 'package:notifications/notifications.dart'; + +/// Owns foreground notification work independently of the application view. +class NotificationLifecycle extends StatefulWidget { + const NotificationLifecycle({ + required this.child, + required this.logger, + this.client, + super.key, + }); + + final Widget child; + final Logger logger; + final NotificationClient? client; + + @override + State createState() => _NotificationLifecycleState(); +} + +class _NotificationLifecycleState extends State { + late final AppLifecycleListener _listener; + + @override + void initState() { + super.initState(); + _listener = AppLifecycleListener(onResume: _clearBadge); + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + try { + await widget.client?.init(); + } catch (error, stackTrace) { + widget.logger.e( + 'Notification initialization failed', + error, + stackTrace, + ); + } + }); + } + + Future _clearBadge() async { + try { + await widget.client?.clearBadge(); + } catch (error, stackTrace) { + widget.logger.e('Notification badge clearing failed', error, stackTrace); + } + } + + @override + void dispose() { + _listener.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/router/router.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/router/router.dart new file mode 100644 index 0000000..babc10d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/router/router.dart @@ -0,0 +1,106 @@ +import 'package:analytics/analytics.dart'; +import 'package:auth/auth.dart' as auth; +import 'package:core/core.dart' as core; +import 'package:dashboard/dashboard.dart'; +import 'package:design_system/design_system.dart'; +import 'package:developer/developer.dart' as developer; +import 'package:di/di.dart'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; +import 'package:notifications/notifications.dart'; +import 'package:nonstop_example/ui/splash_screen.dart'; + +/// The app's single [GoRouter]. +/// +/// Feature packages expose their own `routes` list and are spliced in here, so +/// adding a feature is one import plus one spread - no route table to merge. +abstract final class AppRouter { + static GoRouter createRouter({String? initialLocation}) { + final router = GoRouter( + debugLogDiagnostics: kDebugMode, + initialLocation: initialLocation ?? core.CoreRoutes.root, + observers: [ + core.CoreRouteObserver(), + if (di.has()) + AnalyticsRouteObserver( + client: di.get(), + logger: di.get(), + ), + ], + errorBuilder: (context, state) => ErrorScreen( + title: strings.errors.page_not_found, + message: strings.errors.page_not_found_description, + onGoHome: () => context.go(core.CoreRoutes.root), + error: state.uri.toString(), + ), + routes: [ + GoRoute( + path: core.CoreRoutes.root, + builder: (context, state) => const SplashScreen(), + ), + GoRoute( + path: core.CoreRoutes.home, + redirect: (context, state) => DashboardRouter.home, + ), + DashboardRouter.createShellRoute( + // Demo tabs open before Firebase is configured; configured apps + // require sign-in. Never allow unconfigured access to real data. + redirect: auth.authRedirect(allowUnconfigured: true), + onSignOut: signOut, + ), + ...auth.AuthRouter( + onSignedIn: _onAuthenticated, + onSignedUp: _onAuthenticated, + ).routes, + ...developer.DeveloperRouter().routes, + GoRoute( + path: core.CoreRoutes.error, + builder: (context, state) => ErrorScreen( + title: + state.uri.queryParameters[core.Keys.title] ?? + strings.generic.error, + message: + state.uri.queryParameters[core.Keys.message] ?? + strings.errors.unexpected_error, + error: state.uri.queryParameters[core.Keys.error], + onGoHome: () => context.go(core.CoreRoutes.root), + ), + ), + ], + ); + + return router; + } + + /// Signs out after removing this device's push token, so a signed-out + /// device stops receiving the previous user's notifications. A backend + /// failure is logged and never blocks sign-out. + @visibleForTesting + static Future signOut(BuildContext context) async { + if (di.has()) { + try { + await di.get().unregisterDevice(); + } catch (error, stackTrace) { + di.get().e( + 'Could not unregister the device token', + error, + stackTrace, + ); + } + } + if (context.mounted) await auth.signOut(context); + } + + /// Where a user lands once sign-in or sign-up succeeds. + /// + /// Load the profile / entitlements you need here before routing on. + static Future _onAuthenticated(BuildContext context) async { + await AnalyticsHelper.logEvent(AnalyticsEvents.user.authenticatedRedirect); + if (context.mounted) { + context.go(DashboardRouter.home); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/ui/splash_screen.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/ui/splash_screen.dart new file mode 100644 index 0000000..c1bd733 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/lib/ui/splash_screen.dart @@ -0,0 +1,61 @@ +import 'package:auth/auth.dart' as auth; +import 'package:dashboard/dashboard.dart'; +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +/// First frame the user sees. +/// +/// It exists to give async startup work (session restore, profile fetch) a +/// place to happen before the app commits to a destination. +class SplashScreen extends StatefulWidget { + const SplashScreen({super.key}); + + @override + State createState() => _SplashScreenState(); +} + +class _SplashScreenState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _redirect()); + } + + Future _redirect() async { + if (!mounted) return; + + // Same rule as the dashboard guard, so the two can never disagree. + final signIn = auth.authRedirectLocation(allowUnconfigured: true); + if (signIn != null) { + context.go(signIn); + return; + } + + // TODO: load whatever the first screen needs before navigating. + context.go(DashboardRouter.home); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + strings.app.name, + style: theme.textTheme.headlineMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 32), + const DefaultLoader(), + ], + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/pubspec.yaml new file mode 100644 index 0000000..a382ce6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/pubspec.yaml @@ -0,0 +1,68 @@ +name: nonstop_example +description: "Reference project generated by nonstop_cli." +publish_to: 'none' +version: 0.1.0+1 + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + cupertino_icons: ^1.0.8 + go_router: ^18.0.1 + bloc: ^9.0.0 + core: + path: ../../packages/core + design_system: + path: ../../packages/design_system + di: + path: ../../packages/di + localization: + path: ../../packages/localization + utils: + path: ../../packages/utils + firebase_core: ^4.15.0 + network: + path: ../../packages/network + analytics: + path: ../../packages/analytics + crashlytics: + path: ../../packages/crashlytics + feature_flags: + path: ../../packages/feature_flags + notifications: + path: ../../packages/notifications + developer: + path: ../../packages/developer + auth: + path: ../../features/auth + dashboard: + path: ../../features/dashboard + +dev_dependencies: + mocktail: ^1.0.4 + plugin_platform_interface: ^2.1.8 + firebase_core_platform_interface: ^8.1.1 + firebase_auth_platform_interface: ^9.1.0 + firebase_analytics_platform_interface: ^6.0.7 + firebase_crashlytics_platform_interface: ^3.8.10 + firebase_remote_config_platform_interface: ^3.0.7 + firebase_messaging_platform_interface: ^4.6.10 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + + +flutter: + uses-material-design: true + fonts: + # firebase_ui_auth ships this font but never registers it, so the Google + # and Apple buttons render as tofu unless the app declares it here. + - family: SocialIcons + fonts: + - asset: packages/firebase_ui_auth/fonts/SocialIcons.ttf + + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/app_test.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/app_test.dart new file mode 100644 index 0000000..bae934e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/app_test.dart @@ -0,0 +1,105 @@ +import 'package:auth/auth.dart' as auth; +import 'package:core/core.dart' as core; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; +import 'package:notifications/notifications.dart'; +import 'package:nonstop_example/app.dart'; +import 'package:nonstop_example/router/router.dart'; + +class _Notifications implements NotificationClient { + _Notifications({required this.fails}); + final bool fails; + int unregistered = 0; + + @override + Future unregisterDevice() async { + unregistered++; + if (fails) throw Exception('backend down'); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _Auth implements auth.AuthService { + int signOuts = 0; + + @override + Future signOut() async => signOuts++; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + setUp(core.init); + tearDown(di.reset); + + testWidgets('renders an injected router without platform initialization', ( + tester, + ) async { + final router = GoRouter( + routes: [ + GoRoute(path: '/', builder: (_, _) => const Text('Test destination')), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(App(router: router)); + await tester.pumpAndSettle(); + expect(find.text('Test destination'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('real routes boot without configured Firebase and switch tabs', ( + tester, + ) async { + final router = AppRouter.createRouter(); + addTearDown(router.dispose); + await tester.pumpWidget(App(router: router)); + await tester.pumpAndSettle(); + expect(find.text(strings.nav.explore), findsWidgets); + await tester.tap(find.text(strings.nav.explore).first); + await tester.pumpAndSettle(); + router.go('/error'); + await tester.pumpAndSettle(); + expect(find.text(strings.generic.error), findsWidgets); + expect(find.text(strings.errors.unexpected_error), findsWidgets); + expect(tester.takeException(), isNull); + }); + + for (final fails in [false, true]) { + testWidgets('sign-out unregisters the device first (failure: $fails)', ( + tester, + ) async { + final notifications = _Notifications(fails: fails); + final service = _Auth(); + di.register(notifications); + di.register(service); + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, _) => TextButton( + onPressed: () => AppRouter.signOut(context), + child: const Text('out'), + ), + ), + GoRoute( + path: auth.AuthRoutes.signIn, + builder: (_, _) => const Text('login'), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.tap(find.text('out')); + await tester.pumpAndSettle(); + expect(notifications.unregistered, 1); + expect(service.signOuts, 1); + expect(find.text('login'), findsOneWidget); + }); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/entrypoint_test.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/entrypoint_test.dart new file mode 100644 index 0000000..7545f92 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/entrypoint_test.dart @@ -0,0 +1,37 @@ +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; +import 'package:network/network.dart'; + +import 'package:nonstop_example/main.dart' as entrypoint; + +void main() { + tearDown(di.reset); + testWidgets('real entrypoint starts offline without Firebase credentials', ( + tester, + ) async { + await entrypoint.main(); + await tester.pump(); + await tester.pumpAndSettle(); + expect(di.has(), isTrue); + + expect(di.has(), isTrue); + expect(find.text(strings.nav.explore), findsWidgets); + + final router = di.get(); + router.go('/unknown'); + await tester.pumpAndSettle(); + expect(find.byType(OutlinedButton), findsOneWidget); + await tester.tap(find.byType(OutlinedButton)); + await tester.pumpAndSettle(); + router.go('/error?title=Test&message=Try%20later&error=Details'); + await tester.pumpAndSettle(); + expect(find.text('Try later'), findsOneWidget); + await tester.tap(find.byType(OutlinedButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/firebase_bootstrap_test.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/firebase_bootstrap_test.dart new file mode 100644 index 0000000..67de726 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/firebase_bootstrap_test.dart @@ -0,0 +1,248 @@ +// Protected delegate methods are the FlutterFire platform mocking seam. +// ignore_for_file: invalid_use_of_protected_member +import 'package:analytics/analytics.dart'; + +import 'package:auth/auth.dart' as auth; + +import 'package:core/developer/emulators.dart' as emulators; + +import 'package:crashlytics/crashlytics.dart'; + +import 'package:di/di.dart'; +import 'package:feature_flags/feature_flags.dart'; + +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/test.dart'; +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; + +import 'package:firebase_analytics_platform_interface/firebase_analytics_platform_interface.dart'; + +import 'package:firebase_crashlytics_platform_interface/firebase_crashlytics_platform_interface.dart'; + +import 'package:firebase_remote_config_platform_interface/firebase_remote_config_platform_interface.dart'; + +import 'package:firebase_messaging_platform_interface/firebase_messaging_platform_interface.dart'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:localization/localization.dart'; +import 'package:notifications/notifications.dart'; + +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import 'package:nonstop_example/bootstrap.dart' as bootstrap; +import 'package:nonstop_example/main.dart' as entrypoint; +import 'package:nonstop_example/app.dart'; +import 'package:nonstop_example/router/router.dart'; + +class _Core extends MockFirebaseApp { + @override + Future> initializeCore() async { + final apps = await super.initializeCore(); + apps.first.pluginConstants['plugins.flutter.io/firebase_crashlytics'] = { + 'isCrashlyticsCollectionEnabled': false, + }; + return apps; + } +} + +class _Auth extends Mock + with MockPlatformInterfaceMixin + implements FirebaseAuthPlatform {} + +class _Analytics extends Mock + with MockPlatformInterfaceMixin + implements FirebaseAnalyticsPlatform {} + +class _Crash extends Mock + with MockPlatformInterfaceMixin + implements FirebaseCrashlyticsPlatform {} + +class _Flags extends Mock + with MockPlatformInterfaceMixin + implements FirebaseRemoteConfigPlatform {} + +class _Messaging extends Mock + with MockPlatformInterfaceMixin + implements FirebaseMessagingPlatform {} + +class _User extends Mock + with MockPlatformInterfaceMixin + implements UserPlatform {} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'configured bootstrap composes all modules against offline platform doubles', + (tester) async { + TestFirebaseCoreHostApi.setUp(_Core()); + final app = await Firebase.initializeApp(); + registerFallbackValue(app); + registerFallbackValue( + RemoteConfigSettings( + fetchTimeout: const Duration(seconds: 1), + minimumFetchInterval: Duration.zero, + ), + ); + final identity = _Auth(); + + final analytics = _Analytics(); + + final crash = _Crash(); + + final flags = _Flags(); + + final messaging = _Messaging(); + + FirebaseAuthPlatform.instance = identity; + + FirebaseAnalyticsPlatform.instance = analytics; + + FirebaseCrashlyticsPlatform.instance = crash; + + FirebaseRemoteConfigPlatform.instance = flags; + + FirebaseMessagingPlatform.instance = messaging; + + when( + () => identity.delegateFor(app: any(named: 'app')), + ).thenReturn(identity); + when( + () => identity.setInitialValues( + currentUser: any(named: 'currentUser'), + languageCode: any(named: 'languageCode'), + ), + ).thenReturn(identity); + when( + identity.idTokenChanges, + ).thenAnswer((_) => const Stream.empty()); + when( + identity.authStateChanges, + ).thenAnswer((_) => const Stream.empty()); + when( + identity.userChanges, + ).thenAnswer((_) => const Stream.empty()); + when( + () => identity.useAuthEmulator(any(), any()), + ).thenAnswer((_) async {}); + when( + () => analytics.delegateFor( + app: any(named: 'app'), + webOptions: any(named: 'webOptions'), + ), + ).thenReturn(analytics); + when( + () => analytics.setAnalyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + when( + () => analytics.logEvent( + name: any(named: 'name'), + parameters: any(named: 'parameters'), + ), + ).thenAnswer((_) async {}); + when( + () => crash.setInitialValues( + isCrashlyticsCollectionEnabled: any( + named: 'isCrashlyticsCollectionEnabled', + ), + ), + ).thenReturn(crash); + when( + () => crash.setCrashlyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + when(crash.checkForUnsentReports).thenAnswer((_) async => false); + when(() => flags.delegateFor(app: any(named: 'app'))).thenReturn(flags); + when( + () => flags.setInitialValues( + remoteConfigValues: any(named: 'remoteConfigValues'), + ), + ).thenReturn(flags); + when(() => flags.setConfigSettings(any())).thenAnswer((_) async {}); + when(() => flags.setDefaults(any())).thenAnswer((_) async {}); + when(flags.fetchAndActivate).thenAnswer((_) async => false); + when(() => flags.lastFetchTime).thenReturn(DateTime(2026)); + when( + () => flags.lastFetchStatus, + ).thenReturn(RemoteConfigFetchStatus.success); + when( + () => messaging.delegateFor(app: any(named: 'app')), + ).thenReturn(messaging); + when( + () => messaging.setInitialValues( + isAutoInitEnabled: any(named: 'isAutoInitEnabled'), + ), + ).thenReturn(messaging); + addTearDown(di.reset); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await bootstrap.init(firebaseOptions: app.options, useEmulators: true); + debugDefaultTargetPlatformOverride = null; + expect(di.has(), isTrue); + + expect(di.has(), isTrue); + + expect(di.has(), isTrue); + + expect(di.has(), isTrue); + + expect(di.has(), isTrue); + + expect(di.get(), isA()); + + expect( + di.get(), + isA(), + ); + + verify( + () => analytics.logEvent( + name: 'app_open', + parameters: any(named: 'parameters'), + ), + ).called(1); + when( + () => identity.useAuthEmulator(any(), any()), + ).thenThrow(StateError('offline')); + await expectLater(emulators.init(), throwsStateError); + late Widget composed; + await entrypoint.startApp( + initialize: (_) async {}, + mount: (app) => composed = app, + ); + expect(composed, isA()); + final router = AppRouter.createRouter(initialLocation: '/error'); + addTearDown(router.dispose); + await tester.pumpWidget(App(router: router)); + await tester.pumpAndSettle(); + final context = tester.element(find.byType(OutlinedButton)); + final route = router.configuration.routes.whereType().firstWhere( + (r) => r.path == auth.AuthRoutes.signIn, + ); + final screen = + route.builder!(context, GoRouterState.of(context)) + as auth.SignInScreen; + when(() => identity.currentUser).thenReturn(_User()); + await screen.onSignedIn(context); + await tester.pumpAndSettle(); + expect(find.text(strings.nav.explore), findsWidgets); + + await di.get().onForeground!('Notice', 'Details'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.text('Notice'), findsOneWidget); + await tester.pump(const Duration(seconds: 4)); + await tester.pumpAndSettle(); + when(() => identity.currentUser).thenReturn(null); + router.go('/'); + await tester.pumpAndSettle(); + expect(find.byType(auth.SignInScreen), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/notification_lifecycle_test.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/notification_lifecycle_test.dart new file mode 100644 index 0000000..0e018c6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/notification_lifecycle_test.dart @@ -0,0 +1,98 @@ +import 'package:core/core.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:notifications/notifications.dart'; +import 'package:nonstop_example/notification_lifecycle.dart'; + +class _Logger implements Logger { + final errors = []; + @override + Object get logger => this; + @override + void d(String message) {} + @override + void i(String message) {} + @override + void w(String message) {} + @override + void e(String message, [Object? error, StackTrace? stackTrace]) => + errors.add(error); +} + +class _Client implements NotificationClient { + int starts = 0; + int clears = 0; + bool fail = false; + @override + Future init() async { + starts++; + if (fail) throw StateError('init failed'); + } + + @override + Future clearBadge() async { + clears++; + if (fail) throw StateError('badge failed'); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + testWidgets('initializes after the first frame and clears badge on resume', ( + tester, + ) async { + final client = _Client(); + final logger = _Logger(); + await tester.pumpWidget( + NotificationLifecycle( + logger: logger, + client: client, + child: const SizedBox(), + ), + ); + expect(client.starts, 1); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(client.clears, 1); + expect(logger.errors, isEmpty); + await tester.pumpWidget(const SizedBox()); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(client.clears, 1); + }); + + testWidgets('catches asynchronous initialization and badge failures', ( + tester, + ) async { + final client = _Client()..fail = true; + final logger = _Logger(); + await tester.pumpWidget( + NotificationLifecycle( + logger: logger, + client: client, + child: const SizedBox(), + ), + ); + await tester.pump(); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(logger.errors, hasLength(2)); + expect(tester.takeException(), isNull); + }); + + testWidgets('works when notifications are not configured', (tester) async { + final logger = _Logger(); + await tester.pumpWidget( + NotificationLifecycle(logger: logger, child: const SizedBox()), + ); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + expect(logger.errors, isEmpty); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/startup_test.dart b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/startup_test.dart new file mode 100644 index 0000000..60b4646 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/test/startup_test.dart @@ -0,0 +1,33 @@ +import 'package:di/di.dart'; +import 'package:core/core.dart' as core; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:localization/localization.dart'; +import 'package:nonstop_example/main.dart' as entrypoint; + +void main() { + tearDown(di.reset); + testWidgets( + 'cold-start notification routes wait for the router; later routes navigate directly', + (tester) async { + late void Function(String) openRoute; + late Widget app; + await entrypoint.startApp( + initialize: (callback) async { + await core.init(); + openRoute = callback; + callback('/error?title=From%20notification'); + }, + mount: (widget) => app = widget, + ); + await tester.pumpWidget(app); + await tester.pumpAndSettle(); + expect(find.text('From notification'), findsOneWidget); + openRoute('/home'); + await tester.pumpAndSettle(); + expect(find.text(strings.nav.explore), findsWidgets); + + await tester.pumpWidget(const SizedBox()); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/favicon.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8aaa46ac1ae21512746f852a42ba87e4165dfdd1 GIT binary patch literal 917 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|I14-?iy0X7 zltGxWVyS%@P(fs7NJL45ua8x7ey(0(N`6wRUPW#JP&EUCO@$SZnVVXYs8ErclUHn2 zVXFjIVFhG^g!Ppaz)DK8ZIvQ?0~DO|i&7O#^-S~(l1AfjnEK zjFOT9D}DX)@^Za$W4-*MbbUihOG|wNBYh(yU7!lx;>x^|#0uTKVr7USFmqf|i<65o z3raHc^AtelCMM;Vme?vOfh>Xph&xL%(-1c06+^uR^q@XSM&D4+Kp$>4P^%3{)XKjo zGZknv$b36P8?Z_gF{nK@`XI}Z90TzwSQO}0J1!f2c(B=V`5aP@1P1a|PZ!4!3&Gl8 zTYqUsf!gYFyJnXpu0!n&N*SYAX-%d(5gVjrHJWqXQshj@!Zm{!01WsQrH~9=kTxW#6SvuapgMqt>$=j#%eyGrQzr zP{L-3gsMA^$I1&gsBAEL+vxi1*Igl=8#8`5?A-T5=z-sk46WA1IUT)AIZHx1rdUrf zVJrJn<74DDw`j)Ki#gt}mIT-Q`XRa2-jQXQoI%w`nb|XblvzK${ZzlV)m-XcwC(od z71_OEC5Bt9GEXosOXaPTYOia#R4ID2TiU~`zVMl08TV_C%DnU4^+HE>9(CE4D6?Fz oujB08i7adh9xk7*FX66dWH6F5TM;?E2b5PlUHx3vIVCg!0Dx9vYXATM literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-192.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..b749bfef07473333cf1dd31e9eed89862a5d52aa GIT binary patch literal 5292 zcmZ`-2T+sGz6~)*FVZ`aW+(v>MIm&M-g^@e2u-B-DoB?qO+b1Tq<5uCCv>ESfRum& zp%X;f!~1{tzL__3=gjVJ=j=J>+nMj%ncXj1Q(b|Ckbw{Y0FWpt%4y%$uD=Z*c-x~o zE;IoE;xa#7Ll5nj-e4CuXB&G*IM~D21rCP$*xLXAK8rIMCSHuSu%bL&S3)8YI~vyp@KBu9Ph7R_pvKQ@xv>NQ`dZp(u{Z8K3yOB zn7-AR+d2JkW)KiGx0hosml;+eCXp6+w%@STjFY*CJ?udJ64&{BCbuebcuH;}(($@@ znNlgBA@ZXB)mcl9nbX#F!f_5Z=W>0kh|UVWnf!At4V*LQP%*gPdCXd6P@J4Td;!Ur z<2ZLmwr(NG`u#gDEMP19UcSzRTL@HsK+PnIXbVBT@oHm53DZr?~V(0{rsalAfwgo zEh=GviaqkF;}F_5-yA!1u3!gxaR&Mj)hLuj5Q-N-@Lra{%<4ONja8pycD90&>yMB` zchhd>0CsH`^|&TstH-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mFIgx=0$(sjb>+0CHG)K@cPG{IxaJ&Ueo8)0RWgV9+gO7+Bl1(F z7!BslJ2MP*PWJ;x)QXbR$6jEr5q3 z(3}F@YO_P1NyTdEXRLU6fp?9V2-S=E+YaeLL{Y)W%6`k7$(EW8EZSA*(+;e5@jgD^I zaJQ2|oCM1n!A&-8`;#RDcZyk*+RPkn_r8?Ak@agHiSp*qFNX)&i21HE?yuZ;-C<3C zwJGd1lx5UzViP7sZJ&|LqH*mryb}y|%AOw+v)yc`qM)03qyyrqhX?ub`Cjwx2PrR! z)_z>5*!*$x1=Qa-0uE7jy0z`>|Ni#X+uV|%_81F7)b+nf%iz=`fF4g5UfHS_?PHbr zB;0$bK@=di?f`dS(j{l3-tSCfp~zUuva+=EWxJcRfp(<$@vd(GigM&~vaYZ0c#BTs z3ijkxMl=vw5AS&DcXQ%eeKt!uKvh2l3W?&3=dBHU=Gz?O!40S&&~ei2vg**c$o;i89~6DVns zG>9a*`k5)NI9|?W!@9>rzJ;9EJ=YlJTx1r1BA?H`LWijk(rTax9(OAu;q4_wTj-yj z1%W4GW&K4T=uEGb+E!>W0SD_C0RR91 literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-512.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..88cfd48dff1169879ba46840804b412fe02fefd6 GIT binary patch literal 8252 zcmd5=2T+s!lYZ%-(h(2@5fr2dC?F^$C=i-}R6$UX8af(!je;W5yC_|HmujSgN*6?W z3knF*TL1$|?oD*=zPbBVex*RUIKsL<(&Rj9%^UD2IK3W?2j>D?eWQgvS-HLymHo9%~|N2Q{~j za?*X-{b9JRowv_*Mh|;*-kPFn>PI;r<#kFaxFqbn?aq|PduQg=2Q;~Qc}#z)_T%x9 zE|0!a70`58wjREmAH38H1)#gof)U3g9FZ^ zF7&-0^Hy{4XHWLoC*hOG(dg~2g6&?-wqc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Z(n~|PSNsv+Wgl{P-TvaUQ9j?ZCtvb^37U$sFpBrkT{7Jpd?HpIvj2!}RIq zH{9~+gErN2+}J`>Jvng2hwM`=PLNkc7pkjblKW|+Fk9rc)G1R>Ww>RC=r-|!m-u7( zc(a$9NG}w#PjWNMS~)o=i~WA&4L(YIW25@AL9+H9!?3Y}sv#MOdY{bb9j>p`{?O(P zIvb`n?_(gP2w3P#&91JX*md+bBEr%xUHMVqfB;(f?OPtMnAZ#rm5q5mh;a2f_si2_ z3oXWB?{NF(JtkAn6F(O{z@b76OIqMC$&oJ_&S|YbFJ*)3qVX_uNf5b8(!vGX19hsG z(OP>RmZp29KH9Ge2kKjKigUmOe^K_!UXP`von)PR8Qz$%=EmOB9xS(ZxE_tnyzo}7 z=6~$~9k0M~v}`w={AeqF?_)9q{m8K#6M{a&(;u;O41j)I$^T?lx5(zlebpY@NT&#N zR+1bB)-1-xj}R8uwqwf=iP1GbxBjneCC%UrSdSxK1vM^i9;bUkS#iRZw2H>rS<2<$ zNT3|sDH>{tXb=zq7XZi*K?#Zsa1h1{h5!Tq_YbKFm_*=A5-<~j63he;4`77!|LBlo zR^~tR3yxcU=gDFbshyF6>o0bdp$qmHS7D}m3;^QZq9kBBU|9$N-~oU?G5;jyFR7>z hN`IR97YZXIo@y!QgFWddJ3|0`sjFx!m))><{BI=FK%f8s literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-maskable-192.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9b4d76e525556d5d89141648c724331630325d GIT binary patch literal 5594 zcmdT|`#%%j|KDb2V@0DPm$^(Lx5}lO%Yv(=e*7hl@QqKS50#~#^IQPxBmuh|i9sXnt4ch@VT0F7% zMtrs@KWIOo+QV@lSs66A>2pz6-`9Jk=0vv&u?)^F@HZ)-6HT=B7LF;rdj zskUyBfbojcX#CS>WrIWo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c6XSboURUh&k=B)MS>6kw9bY z{7vdev7;A}5fy*ZE23DS{J?8at~xwVk`pEwP5^k?XMQ7u64;KmFJ#POzdG#np~F&H ze-BUh@g54)dsS%nkBb}+GuUEKU~pHcYIg4vSo$J(J|U36bs0Use+3A&IMcR%6@jv$ z=+QI+@wW@?iu}Hpyzlvj-EYeop{f65GX0O%>w#0t|V z1-svWk`hU~m`|O$kw5?Yn5UhI%9P-<45A(v0ld1n+%Ziq&TVpBcV9n}L9Tus-TI)f zd_(g+nYCDR@+wYNQm1GwxhUN4tGMLCzDzPqY$~`l<47{+l<{FZ$L6(>J)|}!bi<)| zE35dl{a2)&leQ@LlDxLQOfUDS`;+ZQ4ozrleQwaR-K|@9T{#hB5Z^t#8 zC-d_G;B4;F#8A2EBL58s$zF-=SCr`P#z zNCTnHF&|X@q>SkAoYu>&s9v@zCpv9lLSH-UZzfhJh`EZA{X#%nqw@@aW^vPcfQrlPs(qQxmC|4tp^&sHy!H!2FH5eC{M@g;ElWNzlb-+ zxpfc0m4<}L){4|RZ>KReag2j%Ot_UKkgpJN!7Y_y3;Ssz{9 z!K3isRtaFtQII5^6}cm9RZd5nTp9psk&u1C(BY`(_tolBwzV_@0F*m%3G%Y?2utyS zY`xM0iDRT)yTyYukFeGQ&W@ReM+ADG1xu@ruq&^GK35`+2r}b^V!m1(VgH|QhIPDE X>c!)3PgKfL&lX^$Z>Cpu&6)6jvi^Z! literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-maskable-512.png b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000000000000000000000000000000000000..d69c56691fbdb0b7efa65097c7cc1edac12a6d3e GIT binary patch literal 20998 zcmeFZ_gj-)&^4Nb2tlbLMU<{!p(#yjqEe+=0IA_oih%ScH9@5#MNp&}Y#;;(h=A0@ zh7{>lT2MkSQ344eAvrhici!td|HJuyvJm#Y_w1Q9Yu3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hzb>HgF2|2Usww0nL^;x@1eaB)=+Clj+$fF@H( z-fqP??~QMT$KI-#m;QC*&6vkp&8699G3)Bq0*kFZXINw=b9OVaed(3(3kS|IZ)CM? zJdnW&%t8MveBuK21uiYj)_a{Fnw0OErMzMN?d$QoPwkhOwcP&p+t>P)4tHlYw-pPN z^oJ=uc$Sl>pv@fZH~ZqxSvdhF@F1s=oZawpr^-#l{IIOGG=T%QXjtwPhIg-F@k@uIlr?J->Ia zpEUQ*=4g|XYn4Gez&aHr*;t$u3oODPmc2Ku)2Og|xjc%w;q!Zz+zY)*3{7V8bK4;& zYV82FZ+8?v)`J|G1w4I0fWdKg|2b#iaazCv;|?(W-q}$o&Y}Q5d@BRk^jL7#{kbCK zSgkyu;=DV+or2)AxCBgq-nj5=@n^`%T#V+xBGEkW4lCqrE)LMv#f;AvD__cQ@Eg3`~x| zW+h9mofSXCq5|M)9|ez(#X?-sxB%Go8};sJ?2abp(Y!lyi>k)|{M*Z$c{e1-K4ky` MPgg&ebxsLQ025IeI{*Lx literal 0 HcmV?d00001 diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/index.html b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/index.html new file mode 100644 index 0000000..5c6cd53 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + nonstop_example + + + + + + + diff --git a/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/manifest.json b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/manifest.json new file mode 100644 index 0000000..03f8f0d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/apps/nonstop_example/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "nonstop_example", + "short_name": "nonstop_example", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "Reference project generated by nonstop_cli.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/packages/nonstop_cli/example/nonstop_example/docs/architecture.md b/packages/nonstop_cli/example/nonstop_example/docs/architecture.md new file mode 100644 index 0000000..94cf46f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/docs/architecture.md @@ -0,0 +1,61 @@ +# Architecture decisions + +The app is the composition root. Features own screens and feature behavior; +shared packages expose cohesive contracts and implementations. Keep dependencies +pointing from apps to features to packages, never back toward the app. + +## SOLID boundaries + +| Principle | Starter boundary | +| --- | --- | +| Single responsibility | `App` renders an injected router; bootstrap composes services; lifecycle handling owns foreground work. | +| Open/closed | Implement the client/provider contracts to swap a backend or add a feature without editing existing consumers. | +| Liskov substitution | Tests exercise fakes against the same contracts; core observers accept any `Logger`, not only Talker. | +| Interface segregation | Auth tokens, device identity, notification permission and notification delivery have separate contracts. | +| Dependency inversion | Clients accept their transport, SDK, logger and clock dependencies. Resolve the locator at composition boundaries. | + +The locator is a convenience at Flutter composition edges, not a requirement for +business logic. Prefer constructor injection in new services and repositories. +The container disposes dependents before dependencies and awaits async cleanup. +Only one component should own each subscription or disposable service. + +## Adding a feature + +1. Put behavior behind a small contract in the owning feature or shared package. +2. Inject its dependencies. Use an optional clock callback for time-sensitive behavior. +3. Write tests for success, invalid input, platform failure and lifecycle cleanup. +4. Expose feature routes and compose them in the app router. +5. Register implementations in bootstrap; keep registration separate from widget rendering. +6. Run `dart run melos run lint` and `dart run melos run coverage` before committing. + +```dart +abstract interface class GreetingRepository { + Future loadGreeting(); +} + +class LoadGreeting { + const LoadGreeting(this.repository); + final GreetingRepository repository; + + Future call() => repository.loadGreeting(); +} +``` + +Test `LoadGreeting` using a small fake repository. Test a real repository's adapter +with an injected transport rather than making live requests in unit tests. + +## Failure and privacy policy + +- HTTP failures stay typed; application-level error envelopes never masquerade as success. +- Automatic bearer headers stay on the configured API origin. One retry follows a shared token refresh; consumed streams are not replayed. +- SDK initialization is awaited. An unavailable optional Firebase configuration permits the starter demo to boot; emulator setup failures are surfaced. +- Analytics failures do not interrupt UI behavior. SDK state is not cached across DI resets. +- Network logs omit headers, query values and bodies. Auth success logs omit email addresses; add your own redaction rules for domain errors. +- Platform crash handlers are restored when their owning client is disposed. + +## What the tests do not replace + +100% line coverage measures execution, not every branch or possible input. Add +security rules tests, device tests, accessibility checks and backend integration +tests for your product. Configure provider credentials, privacy consent and native +permissions deliberately; a starter cannot choose these product policies for you. diff --git a/packages/nonstop_cli/example/nonstop_example/features/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/features/CLAUDE.md new file mode 100644 index 0000000..b80af9c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/CLAUDE.md @@ -0,0 +1,60 @@ +# Nonstop Example: `features/` + +A feature is a vertical slice of the product: UI, state and data access for one +capability. Read the root `CLAUDE.md` first. To add one end to end, load the +`new-feature` skill. + +## Shape of a feature + +``` +features// + lib/ + .dart public API: init(), exports. Nothing else is imported from outside + config/ feature config contract + default implementation + constants/routes.dart route paths + data/ `abstract interface class` contracts (`*_service.dart`) and implementations (`*_imp.dart`) + router/router.dart `Router` exposing `List routes` + ui/screens/ one screen per file, `index.dart` barrel + ui/components/ feature-private widgets + analytics/ feature event names (if analytics is used) + test/ + pubspec.yaml `resolution: workspace` + CLAUDE.md this feature's contract (required) +``` + +`features/auth` is the reference implementation. Match its layout. (A small +feature may keep route paths as constants on its router class, as +`dashboard/lib/router/dashboard_router.dart` does. Pick one style per feature.) + +## Rules + +- **Public surface is the barrel file.** Other code imports + `package:/.dart` only, never `package:/src/...` or deep paths. +- **No feature-to-feature imports.** A feature that needs another feature's + behavior takes it as a parameter, and the app passes it in. Example: + `DashboardRouter.createShellRoute(redirect: auth.authRedirect(...), + onSignOut: AppRouter.signOut)` in the app router, so `dashboard` never + imports `auth`. If several features share a contract, move it into `packages/`. +- **Layers inside a feature:** `ui` -> state (Cubit/Bloc or a small controller) + -> `data` contracts. Widgets never call SDKs, HTTP or Firebase directly. +- `init()` registers services with `di` and is the only place a feature calls + `di.register`. Services and screens take dependencies (including `Logger`) + through their constructor so tests can pass fakes; the router resolves them + once and passes them down. +- Routes are exposed, not registered: the app spreads `Router().routes`. + Guard protected routes with `GoAuthRoute`, or, when the feature must not + depend on `auth`, accept a `GoRouterRedirect` and let the app pass + `auth.authRedirect()` (as `dashboard` does). Client guards are navigation + helpers; the backend enforces authorization. +- All strings via `strings.*` from `localization`; all styling via the theme and + `design_system` components (load the `design-system` skill). +- Emit analytics through the `analytics` package contract, with event names + defined in the feature's `analytics/` file. + +## Tests + +Each feature needs tests for: service success and typed failure, the widget +states a screen can show (loading, data, empty, error), navigation of its +routes, and disposal of subscriptions. Use `setUp(core.init)` and +`tearDown(di.reset)` so the locator is clean per test (see +`features/dashboard/test/dashboard_test.dart`). diff --git a/packages/nonstop_cli/example/nonstop_example/features/README.md b/packages/nonstop_cli/example/nonstop_example/features/README.md new file mode 100644 index 0000000..4811ae8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/README.md @@ -0,0 +1,15 @@ +# Features + +Vertical slices of the product. A feature owns its UI, state and data access, +and exposes two things to the app: + +- an `init()` that registers its services with the locator +- a `Router` exposing the routes the app splices into its route table + +Features may depend on `packages/`, and should avoid depending on each other. + +Add one with: + +```sh +nonstop create my_feature --template package -o features +``` diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/features/auth/CLAUDE.md new file mode 100644 index 0000000..88c144c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/CLAUDE.md @@ -0,0 +1,90 @@ +# Nonstop Example: `features/auth` + +Firebase Authentication (email, Google, Apple on iOS) built on `firebase_ui_auth`: +sign-in, register and forgot-password screens, the `AuthService` identity +contract, the bearer-token adapter for `network`, route guards and a sign-out +helper for other features. It must not decide where the user lands after auth +(the app passes `onSignedIn` / `onSignedUp`) and must not import other features. + +Read the root `CLAUDE.md` and `features/CLAUDE.md` first. +Load the `design-system` skill before changing UI. + +## Public API (`package:auth/auth.dart`) + +| Symbol | Kind | Notes | +|---|---|---| +| `init(AuthConfig, {firebaseAuth, configureProviders})` | function | Configures FirebaseUI providers, registers `AuthService` and `AuthTokenProvider` | +| `AuthConfig` / `DefaultAuthConfig` | interface / impl | `clientId` for `GoogleProvider` | +| `AuthService` / `AuthServiceImp` | interface / impl | `uid`, `isSignedIn`, `signOut()` | +| `FirebaseAuthTokenProvider` | impl of `network`'s `AuthTokenProvider` | owns the `idTokenChanges` subscription | +| `AuthRouter({onSignedIn, onSignedUp})` | implements `core.CoreRouter` | `routes`: sign-in, sign-up, forgot-password; callbacks are `FutureOr Function(BuildContext)`; resolves `Logger` once and passes it to the screens | +| `authRedirectLocation({allowUnconfigured})` | function | null when signed in, else `AuthRoutes.signIn`; used by the app's `SplashScreen` | +| `authRedirect({allowUnconfigured})` | `GoRouterRedirect` | route-guard wrapper around `authRedirectLocation` | +| `signOut(BuildContext)` | function | no-op without `AuthService`; signs out, then `go(signIn)` if mounted | +| `GoAuthRoute` | `GoRoute` | `redirect` preset to `authRedirect` | +| `AuthRoutes` | constants | `/auth/sign-in`, `/auth/sign-up`, `/auth/forgot-password` | +| `AuthAnalytics` | static helpers | all auth analytics events | +| `SignInScreen({onSignedIn, logger})`, `RegisterScreen({onSignedUp, logger})`, `ForgotPasswordScreen({email})` | widgets | wrap the `firebase_ui_auth` screens | + +## Layout + +``` +lib/ + auth.dart barrel + init() + analytics/analytics.dart AuthAnalytics: event names and params via AnalyticsHelper + config/ AuthConfig contract, DefaultAuthConfig + constants/routes.dart AuthRoutes + data/services/ AuthService contract, AuthServiceImp (FirebaseAuth + Logger injected) + data/token/firebase_auth_token_provider.dart token cache, expiry, refresh, stale-response guard + router/router.dart AuthRouter, authRedirectLocation, authRedirect, signOut, GoAuthRoute + ui/screens/ SignIn / Register / ForgotPassword adapters (index.dart barrel) + ui/components/ headerBuilder (theme-drawn), footerBuilder(context, action, type, logger) + FooterType (not exported) +``` + +## Rules + +- `init()` needs `Logger` in `di` and Firebase initialised; call it before + `network.init()` (which picks up `AuthTokenProvider`) and before the router. +- The token provider is registered with `dispose: (_) => tokens.dispose()`; it + owns its subscription and broadcast controller. Nothing else may cancel them. +- `FirebaseAuthTokenProvider` bumps `_revision` on every token event, sign-out + and dispose; `_readToken` drops a result whose revision or `currentUser.uid` + changed. Keep that guard on any new read path. +- A token counts as expired 5 minutes before `expirationTime`; the clock is + injectable (`now:`). +- `AuthServiceImp.signOut` logs and reports failures, then **rethrows**. +- `allowUnconfigured` exists only for the demo dashboard before Firebase is set up. +- Screens and `footerBuilder` take `Logger` as a parameter; only `AuthRouter` and `init()` use `di`. + +## Common changes + +- **Add an auth provider:** add it to the list in `init()` in `lib/auth.dart` + (platform-guard like `AppleProvider`), add its package to `pubspec.yaml`, and + map its `providerId` in `AuthAnalytics.getAuthMethod`. Extend the provider + loop in `test/presentation_test.dart`. +- **Add an auth screen/route:** constant in `constants/routes.dart`, screen in + `ui/screens/` + `index.dart`, `GoRoute` in `AuthRouter.routes`; assert the + builder type in the `auth screen adapters` test. +- **Add an `AuthService` member:** contract, `AuthServiceImp`, and a case in + `test/auth_service_test.dart` (success and SDK failure). +- **New auth analytics event:** static method on `AuthAnalytics`; call it in `presentation_test.dart`. +## Tests + +| File | Covers | +|---|---| +| `auth_service_test.dart` | `AuthServiceImp` identity + sign-out, sign-out error rethrown, `init()` registers types and `di.reset` disposes the token provider | +| `token_provider_test.dart` | expiry-driven reuse vs refresh, signed-out null, stream publish/clear, read and stream errors, late refresh after sign-out or account change, idempotent dispose, null token | +| `presentation_test.dart` | `getAuthMethod`, every analytics call, route builders, SDK state actions invoke callbacks, forgot-password push with email, header/footer builders, `GoAuthRoute` for no service / signed out / signed in, `signOut` with and without service, footer navigation | + +Pattern: `mocktail` mocks of `FirebaseAuth`, `User`, `IdTokenResult`, `AuthService`; +`setUp(core.init)` / `tearDown(di.reset)` in widget tests. + +`dart run melos exec --scope=auth -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- Screen actions fire `AuthAnalytics.*` with `unawaited`, then `await` the callback. +- `SignInScreen` also handles `UserCreated`, `RegisterScreen` also `SignedIn`; both log a sign-up. +- Both screens log and show `Toast.error` on `AuthFailed`. +- Success analytics carry only method, `success`, `timestamp`: no user data. +- `ui/components/` is not exported; tests import `footer_builder.dart` directly. diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/README.md b/packages/nonstop_cli/example/nonstop_example/features/auth/README.md new file mode 100644 index 0000000..de195f3 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/README.md @@ -0,0 +1,18 @@ +# Auth + +A Melos-managed project for mono-repo, created using NonStop CLI. + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) + +## Installation 💻 + +**❗ In order to start using Auth you must have the [Flutter SDK][flutter_install_link] installed on your machine.** + +Install via `dart pub add`: + +```sh +dart pub add auth +``` + +[flutter_install_link]: https://docs.flutter.dev/get-started/install \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/analytics/analytics.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/analytics/analytics.dart new file mode 100644 index 0000000..702669e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/analytics/analytics.dart @@ -0,0 +1,75 @@ +import 'package:analytics/analytics.dart'; +import 'package:firebase_auth/firebase_auth.dart'; + +/// Every auth-related analytics event in one place. +/// +/// Screens call these instead of `AnalyticsHelper` directly so the event names +/// and parameter shapes stay consistent across sign-in, sign-up and recovery. +abstract final class AuthAnalytics { + /// 'google', 'apple' or 'email', derived from the signed-in provider. + static String getAuthMethod(List? providerData) { + if (providerData?.isNotEmpty ?? false) { + final providerId = providerData!.first.providerId; + if (providerId.contains('google')) return 'google'; + if (providerId.contains('apple')) return 'apple'; + } + return 'email'; + } + + static Future logSignInSuccess({required String method}) async { + await AnalyticsHelper.logSignIn( + method: method, + parameters: _successParams(), + ); + } + + static Future logSignUpSuccess({required String method}) async { + await AnalyticsHelper.logSignUp( + method: method, + parameters: _successParams(), + ); + } + + static Future logSignOutSuccess() async { + await AnalyticsHelper.logEvent( + AnalyticsEvents.auth.signOut, + parameters: _successParams(), + ); + } + + /// [flowType] is one of 'sign_in', 'sign_up', 'forgot_password'. + static Future logAuthError({ + required String errorType, + required String flowType, + String? errorMessage, + String? method, + }) async { + await AnalyticsHelper.logEvent( + AnalyticsEvents.auth.failed, + parameters: { + 'error_type': errorType, + 'flow_type': flowType, + 'auth_method': method, + 'error_message': errorMessage, + 'timestamp': DateTime.now().toIso8601String(), + }, + ); + } + + static Future logSignOutError({required String errorMessage}) async { + await AnalyticsHelper.logEvent( + AnalyticsEvents.error.appError, + parameters: { + 'error_type': 'sign_out_failed', + 'error_message': errorMessage, + 'feature': 'auth', + 'timestamp': DateTime.now().toIso8601String(), + }, + ); + } + + static Map _successParams() => { + 'success': 'true', + 'timestamp': DateTime.now().toIso8601String(), + }; +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/auth.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/auth.dart new file mode 100644 index 0000000..dad89e7 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/auth.dart @@ -0,0 +1,47 @@ +import 'package:flutter/foundation.dart'; +import 'package:firebase_auth/firebase_auth.dart' show FirebaseAuth; + +import 'package:auth/config/config.dart'; +import 'package:auth/data/index.dart'; +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart'; +import 'package:firebase_ui_oauth_apple/firebase_ui_oauth_apple.dart'; +import 'package:firebase_ui_oauth_google/firebase_ui_oauth_google.dart'; +import 'package:network/network.dart'; + +export 'analytics/analytics.dart'; +export 'config/index.dart'; +export 'constants/index.dart'; +export 'data/index.dart'; +export 'router/router.dart'; +export 'ui/screens/index.dart'; + +/// Registers the auth providers and services. +/// +/// Call this after `Firebase.initializeApp` and before the router is built - +/// route guards resolve [AuthService] from the locator on the first frame. +Future init( + AuthConfig config, { + FirebaseAuth? firebaseAuth, + void Function(List)? configureProviders, +}) async { + final logger = di.get(); + logger.i('Initializing Auth...'); + + (configureProviders ?? FirebaseUIAuth.configureProviders)([ + EmailAuthProvider(), + GoogleProvider(clientId: config.clientId, iOSPreferPlist: true), + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.iOS) AppleProvider(), + ]); + + final sdk = firebaseAuth ?? FirebaseAuth.instance; + di.register(AuthServiceImp(firebaseAuth: sdk, logger: logger)); + + // The network layer reads bearer tokens through this provider, so auth has + // to own it - registering it anywhere else risks a stale token on refresh. + final tokens = FirebaseAuthTokenProvider(firebaseAuth: sdk, logger: logger); + di.register(tokens, dispose: (_) => tokens.dispose()); + + logger.i('Auth initialized'); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config.dart new file mode 100644 index 0000000..107ece2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config.dart @@ -0,0 +1,3 @@ +abstract interface class AuthConfig { + String get clientId; +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config_imp.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config_imp.dart new file mode 100644 index 0000000..6bcd13a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/config_imp.dart @@ -0,0 +1,8 @@ +import 'package:auth/config/config.dart'; + +class DefaultAuthConfig implements AuthConfig { + @override + final String clientId; + + DefaultAuthConfig({required this.clientId}); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/index.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/index.dart new file mode 100644 index 0000000..5a25c0b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/config/index.dart @@ -0,0 +1,2 @@ +export 'config.dart'; +export 'config_imp.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/index.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/index.dart new file mode 100644 index 0000000..a935bb9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/index.dart @@ -0,0 +1 @@ +export 'routes.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/routes.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/routes.dart new file mode 100644 index 0000000..290aed5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/constants/routes.dart @@ -0,0 +1,7 @@ +abstract final class AuthRoutes { + static const String auth = '/auth'; + + static const String signIn = '$auth/sign-in'; + static const String signUp = '$auth/sign-up'; + static const String forgotPassword = '$auth/forgot-password'; +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/index.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/index.dart new file mode 100644 index 0000000..b275afc --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/index.dart @@ -0,0 +1,2 @@ +export './services/index.dart'; +export './token/firebase_auth_token_provider.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service.dart new file mode 100644 index 0000000..17b0c92 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service.dart @@ -0,0 +1,7 @@ +abstract interface class AuthService { + String get uid; + + bool get isSignedIn; + + Future signOut(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service_imp.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service_imp.dart new file mode 100644 index 0000000..bdd477f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/auth_service_imp.dart @@ -0,0 +1,38 @@ +import 'package:auth/analytics/analytics.dart'; +import 'package:auth/data/services/auth_service.dart'; +import 'package:core/core.dart'; +import 'package:firebase_auth/firebase_auth.dart'; + +class AuthServiceImp implements AuthService { + AuthServiceImp({required FirebaseAuth firebaseAuth, required Logger logger}) + : _firebaseAuth = firebaseAuth, + _logger = logger; + + final Logger _logger; + final FirebaseAuth _firebaseAuth; + + @override + String get uid => _firebaseAuth.currentUser?.uid ?? ''; + + @override + bool get isSignedIn => _firebaseAuth.currentUser != null; + + @override + Future signOut() async { + try { + _logger.d('Attempting to sign out user'); + await _firebaseAuth.signOut(); + _logger.d('User signed out successfully'); + + // Log successful sign out + await AuthAnalytics.logSignOutSuccess(); + } catch (e, s) { + _logger.e('Error signing out user: $e', e, s); + + // Log sign out error + await AuthAnalytics.logSignOutError(errorMessage: e.toString()); + + rethrow; + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/index.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/index.dart new file mode 100644 index 0000000..b41c8a1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/services/index.dart @@ -0,0 +1,2 @@ +export 'auth_service.dart'; +export 'auth_service_imp.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/token/firebase_auth_token_provider.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/token/firebase_auth_token_provider.dart new file mode 100644 index 0000000..e37c49c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/data/token/firebase_auth_token_provider.dart @@ -0,0 +1,113 @@ +import 'dart:async'; + +import 'package:core/core.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:network/network.dart'; + +/// Adapts Firebase tokens to the network contract and owns its subscription. +class FirebaseAuthTokenProvider implements AuthTokenProvider { + FirebaseAuthTokenProvider({ + required FirebaseAuth firebaseAuth, + required Logger logger, + DateTime Function()? now, + }) : _auth = firebaseAuth, + _logger = logger, + _now = now ?? DateTime.now { + _subscription = _auth.idTokenChanges().listen( + (user) { + _revision++; + _publish(null); + if (user != null) unawaited(_readToken(user, force: false)); + }, + onError: (Object error, StackTrace stackTrace) { + _revision++; + _publish(null); + _logger.e('Auth token stream failed', error, stackTrace); + }, + ); + } + + final FirebaseAuth _auth; + final Logger _logger; + final DateTime Function() _now; + final _controller = StreamController.broadcast(); + late final StreamSubscription _subscription; + String? _token; + DateTime? _expiry; + int _revision = 0; + bool _disposed = false; + + void _publish(String? token, [DateTime? expiry]) { + if (_disposed) return; + _token = token; + _expiry = expiry; + _controller.add(token); + } + + Future _readToken(User user, {required bool force}) async { + final revision = _revision; + try { + final result = await user.getIdTokenResult(force); + // A late refresh from an old session must never restore its token. + if (_disposed || + revision != _revision || + _auth.currentUser?.uid != user.uid) { + return null; + } + _publish(result.token, result.expirationTime); + return result.token; + } catch (error, stackTrace) { + if (!_disposed && revision == _revision) { + _publish(null); + _logger.e('Unable to read authentication token', error, stackTrace); + } + return null; + } + } + + @override + Future getValidToken() async { + final user = _auth.currentUser; + if (_disposed || user == null) return null; + if (_token != null && !isTokenExpired) return _token; + return _readToken(user, force: false); + } + + @override + Future refreshToken() async { + final user = _auth.currentUser; + if (_disposed || user == null) return null; + return _readToken(user, force: true); + } + + @override + String? getCurrentToken() => _token; + + @override + Stream get tokenStream => _controller.stream; + + @override + bool get isAuthenticated => !_disposed && _auth.currentUser != null; + + @override + bool get isTokenExpired => + _expiry == null || + !_now().isBefore(_expiry!.subtract(const Duration(minutes: 5))); + + @override + Future signOut() async { + _revision++; + _publish(null); + await _auth.signOut(); + } + + Future dispose() async { + if (_disposed) return; + _disposed = true; + _revision++; + _token = null; + _expiry = null; + await _subscription.cancel(); + await _controller.close(); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/router/router.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/router/router.dart new file mode 100644 index 0000000..86cab61 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/router/router.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:auth/constants/index.dart'; +import 'package:auth/data/services/auth_service.dart'; +import 'package:auth/ui/screens/index.dart'; +import 'package:core/core.dart' as core; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +class AuthRouter implements core.CoreRouter { + final FutureOr Function(BuildContext context) onSignedIn; + final FutureOr Function(BuildContext context) onSignedUp; + + AuthRouter({required this.onSignedIn, required this.onSignedUp}); + + final core.Logger _logger = di.get(); + + @override + List get routes => [ + GoRoute( + path: AuthRoutes.signIn, + builder: (context, state) => + SignInScreen(onSignedIn: onSignedIn, logger: _logger), + ), + GoRoute( + path: AuthRoutes.signUp, + builder: (context, state) => + RegisterScreen(onSignedUp: onSignedUp, logger: _logger), + ), + GoRoute( + path: AuthRoutes.forgotPassword, + builder: (context, state) { + final email = state.uri.queryParameters[core.Keys.email]; + return ForgotPasswordScreen(email: email); + }, + ), + ]; +} + +/// Where a user must go before continuing: sign-in, or null when signed in. +/// +/// [allowUnconfigured] lets the user through while auth is not set up yet (the +/// demo before `flutterfire configure`). Never use it for protected data. +String? authRedirectLocation({bool allowUnconfigured = false}) { + if (!di.has()) { + return allowUnconfigured ? null : AuthRoutes.signIn; + } + return di.get().isSignedIn ? null : AuthRoutes.signIn; +} + +/// Route guard form of [authRedirectLocation]. +GoRouterRedirect authRedirect({bool allowUnconfigured = false}) => + (context, state) => + authRedirectLocation(allowUnconfigured: allowUnconfigured); + +/// Signs the user out and returns to sign-in. Hand this to features that +/// offer sign-out so they never depend on this package. +Future signOut(BuildContext context) async { + if (!di.has()) return; + await di.get().signOut(); + if (context.mounted) context.go(AuthRoutes.signIn); +} + +final class GoAuthRoute extends GoRoute { + /// Create a secure route that requires authentication + GoAuthRoute({ + required super.path, + required super.builder, + List super.routes = const [], + super.pageBuilder, + bool allowUnconfigured = false, + }) : super(redirect: authRedirect(allowUnconfigured: allowUnconfigured)); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/footer_builder.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/footer_builder.dart new file mode 100644 index 0000000..f99639a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/footer_builder.dart @@ -0,0 +1,73 @@ +import 'package:auth/constants/index.dart'; +import 'package:core/logger/logger.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +enum FooterType { signIn, register } + +Widget footerBuilder( + BuildContext context, + AuthAction action, + FooterType type, + Logger logger, +) { + switch (type) { + case FooterType.signIn: + return _AuthFooter( + title: strings.auth.dont_have_account, + linkText: strings.auth.register, + onTap: () { + logger.d('Navigating to register screen'); + + context.go(AuthRoutes.signUp); + }, + ); + case FooterType.register: + return _AuthFooter( + title: strings.auth.already_have_account, + linkText: strings.auth.sign_in, + onTap: () { + logger.d('Navigating to sign in screen'); + + context.go(AuthRoutes.signIn); + }, + ); + } +} + +class _AuthFooter extends StatelessWidget { + final String title; + final String linkText; + final VoidCallback onTap; + + const _AuthFooter({ + required this.title, + required this.linkText, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(title), + GestureDetector( + onTap: onTap, + child: Text( + linkText, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + ], + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/header_builder.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/header_builder.dart new file mode 100644 index 0000000..c6f728b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/components/header_builder.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +/// Banner shown above the sign-in and register forms. +/// +/// Deliberately drawn from the theme rather than an image, so a fresh project +/// has no asset to ship and nothing to fetch. Swap it for your own artwork: +/// add the file under the app's `assets:` and use `design_system`'s `Header` +/// with `HeaderType.asset`. +Widget headerBuilder(BuildContext context) { + final theme = Theme.of(context); + + return Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + height: 72, + width: 72, + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(20), + ), + child: Icon( + Icons.bolt_outlined, + size: 40, + color: theme.colorScheme.onPrimaryContainer, + ), + ), + const SizedBox(height: 16), + Text( + strings.app.name, + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/forgot_password_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/forgot_password_screen.dart new file mode 100644 index 0000000..265c87f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/forgot_password_screen.dart @@ -0,0 +1,19 @@ +import 'package:auth/ui/components/header_builder.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart' as ui_auth; +import 'package:flutter/material.dart'; + +class ForgotPasswordScreen extends StatelessWidget { + final String? email; + + const ForgotPasswordScreen({super.key, this.email}); + + @override + Widget build(BuildContext context) { + return ui_auth.ForgotPasswordScreen( + email: email, + headerBuilder: (context, constraints, shrinkOffset) { + return headerBuilder(context); + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/index.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/index.dart new file mode 100644 index 0000000..2ceb68a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/index.dart @@ -0,0 +1,3 @@ +export 'forgot_password_screen.dart'; +export 'register_screen.dart'; +export 'sign_in_screen.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/register_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/register_screen.dart new file mode 100644 index 0000000..43eb7cf --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/register_screen.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:auth/analytics/analytics.dart'; +import 'package:auth/ui/components/footer_builder.dart'; +import 'package:auth/ui/components/header_builder.dart'; +import 'package:core/logger/logger.dart'; +import 'package:design_system/toast/toasts.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart' as ui_auth; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +class RegisterScreen extends StatelessWidget { + const RegisterScreen({ + super.key, + required this.onSignedUp, + required this.logger, + }); + + final FutureOr Function(BuildContext context) onSignedUp; + final Logger logger; + + @override + Widget build(BuildContext context) { + return ui_auth.RegisterScreen( + showAuthActionSwitch: false, + actions: [ + ui_auth.AuthStateChangeAction((context, state) async { + logger.d('User registered successfully'); + + final method = AuthAnalytics.getAuthMethod(state.user?.providerData); + unawaited(AuthAnalytics.logSignUpSuccess(method: method)); + + await onSignedUp(context); + }), + ui_auth.AuthStateChangeAction(( + context, + state, + ) async { + logger.d('User created successfully'); + + final method = AuthAnalytics.getAuthMethod( + state.credential.user?.providerData, + ); + unawaited(AuthAnalytics.logSignUpSuccess(method: method)); + + await onSignedUp(context); + }), + ui_auth.AuthStateChangeAction(( + context, + state, + ) async { + logger.e('Registration failed: ${state.exception}'); + + unawaited( + AuthAnalytics.logAuthError( + errorType: state.exception.runtimeType.toString(), + flowType: 'sign_up', + errorMessage: state.exception.toString(), + method: 'email', + ), + ); + + Toast.error(context, message: strings.errors.default_error_message); + }), + ], + footerBuilder: (context, action) { + return footerBuilder(context, action, FooterType.register, logger); + }, + headerBuilder: (context, constraints, shrinkOffset) { + return headerBuilder(context); + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/sign_in_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/sign_in_screen.dart new file mode 100644 index 0000000..556d67b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/lib/ui/screens/sign_in_screen.dart @@ -0,0 +1,87 @@ +import 'dart:async'; + +import 'package:auth/analytics/analytics.dart'; +import 'package:auth/constants/index.dart'; +import 'package:auth/ui/components/footer_builder.dart'; +import 'package:auth/ui/components/header_builder.dart'; +import 'package:core/core.dart' as core; +import 'package:core/logger/logger.dart'; +import 'package:design_system/toast/toasts.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart' as ui_auth; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +class SignInScreen extends StatelessWidget { + const SignInScreen({ + super.key, + required this.onSignedIn, + required this.logger, + }); + + final FutureOr Function(BuildContext context) onSignedIn; + final Logger logger; + + @override + Widget build(BuildContext context) { + return ui_auth.SignInScreen( + showAuthActionSwitch: false, + oauthButtonVariant: ui_auth.OAuthButtonVariant.icon_and_text, + actions: [ + ui_auth.ForgotPasswordAction((context, email) { + logger.d('Navigating to forgot password screen'); + + final uri = Uri( + path: AuthRoutes.forgotPassword, + queryParameters: {core.Keys.email: email}, + ); + context.push(uri.toString()); + }), + ui_auth.AuthStateChangeAction((context, state) async { + logger.d('User signed in successfully'); + + final method = AuthAnalytics.getAuthMethod(state.user?.providerData); + unawaited(AuthAnalytics.logSignInSuccess(method: method)); + + await onSignedIn(context); + }), + ui_auth.AuthStateChangeAction(( + context, + state, + ) async { + logger.d('User created from the sign-in screen'); + + final method = AuthAnalytics.getAuthMethod( + state.credential.user?.providerData, + ); + unawaited(AuthAnalytics.logSignUpSuccess(method: method)); + + await onSignedIn(context); + }), + ui_auth.AuthStateChangeAction(( + context, + state, + ) async { + logger.e('Sign-in failed: ${state.exception}'); + + unawaited( + AuthAnalytics.logAuthError( + errorType: state.exception.runtimeType.toString(), + flowType: 'sign_in', + errorMessage: state.exception.toString(), + ), + ); + + Toast.error(context, message: strings.errors.default_error_message); + }), + //TODO: Handle other AuthState + ], + footerBuilder: (context, action) { + return footerBuilder(context, action, FooterType.signIn, logger); + }, + headerBuilder: (context, constraints, shrinkOffset) { + return headerBuilder(context); + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/features/auth/pubspec.yaml new file mode 100644 index 0000000..b06b5de --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/pubspec.yaml @@ -0,0 +1,40 @@ +name: auth +description: "Firebase Authentication (email, Google, Apple) with go_router integration for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + firebase_auth: ^6.7.0 + firebase_core: ^4.15.0 + firebase_ui_auth: ^3.1.1 + firebase_ui_oauth_apple: ^2.1.1 + firebase_ui_oauth_google: ^2.1.1 + go_router: ^18.0.1 + core: + path: ../../packages/core + design_system: + path: ../../packages/design_system + di: + path: ../../packages/di + localization: + path: ../../packages/localization + network: + path: ../../packages/network + analytics: + path: ../../packages/analytics + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/test/auth_service_test.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/test/auth_service_test.dart new file mode 100644 index 0000000..d996f85 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/test/auth_service_test.dart @@ -0,0 +1,62 @@ +import 'package:auth/auth.dart' as module; +import 'package:auth/data/services/auth_service_imp.dart'; +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:network/network.dart'; + +class _Auth extends Mock implements FirebaseAuth {} + +class _User extends Mock implements User {} + +class _Logger extends Mock implements Logger {} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + tearDown(di.reset); + test('service reads injected identity and awaits sign-out', () async { + final auth = _Auth(); + final user = _User(); + final service = AuthServiceImp(firebaseAuth: auth, logger: _Logger()); + when(() => auth.currentUser).thenReturn(user); + when(() => user.uid).thenReturn('test-user'); + when(auth.signOut).thenAnswer((_) async { + when(() => auth.currentUser).thenReturn(null); + }); + expect(service.uid, 'test-user'); + expect(service.isSignedIn, isTrue); + await service.signOut(); + expect(service.uid, isEmpty); + expect(service.isSignedIn, isFalse); + verify(auth.signOut).called(1); + }); + + test('SDK sign-out errors remain visible to the caller', () async { + final auth = _Auth(); + final error = FirebaseAuthException(code: 'network-request-failed'); + when(auth.signOut).thenThrow(error); + final service = AuthServiceImp(firebaseAuth: auth, logger: _Logger()); + await expectLater(service.signOut(), throwsA(same(error))); + }); + + test( + 'module composes injected SDK and disposes owned token provider', + () async { + di.register(_Logger()); + final auth = _Auth(); + when(auth.idTokenChanges).thenAnswer((_) => const Stream.empty()); + await module.init( + module.DefaultAuthConfig(clientId: 'client-id'), + firebaseAuth: auth, + configureProviders: (providers) => + expect(providers.length, greaterThanOrEqualTo(2)), + ); + expect(di.get(), isA()); + final tokens = di.get(); + await di.reset(); + expect(tokens.isAuthenticated, isFalse); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/test/presentation_test.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/test/presentation_test.dart new file mode 100644 index 0000000..6b56757 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/test/presentation_test.dart @@ -0,0 +1,258 @@ +import 'package:auth/auth.dart'; +import 'package:auth/ui/components/footer_builder.dart'; +import 'package:core/core.dart' as core; +import 'package:di/di.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:firebase_ui_auth/firebase_ui_auth.dart' as ui; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:mocktail/mocktail.dart'; + +class _User extends Mock implements User {} + +class _UserInfo extends Mock implements UserInfo {} + +class _Credential extends Mock implements UserCredential {} + +class _AuthService extends Mock implements AuthService {} + +void main() { + setUp(core.init); + tearDown(di.reset); + + test( + 'provider analytics handles every supported method and empty identities', + () async { + expect(AuthAnalytics.getAuthMethod(null), 'email'); + expect(AuthAnalytics.getAuthMethod([]), 'email'); + for (final provider in ['google.com', 'apple.com', 'password']) { + final info = _UserInfo(); + when(() => info.providerId).thenReturn(provider); + expect( + AuthAnalytics.getAuthMethod([info]), + provider == 'password' ? 'email' : provider.split('.').first, + ); + } + await AuthAnalytics.logSignInSuccess(method: 'email'); + await AuthAnalytics.logSignUpSuccess(method: 'email'); + await AuthAnalytics.logAuthError(errorType: 'test', flowType: 'sign_in'); + await AuthAnalytics.logSignOutError(errorMessage: 'test'); + await AuthAnalytics.logSignOutSuccess(); + }, + ); + + testWidgets( + 'auth screen adapters wire headers, footers and SDK state actions', + (tester) async { + late BuildContext context; + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (ctx, _) { + context = ctx; + return const SizedBox(); + }, + ), + GoRoute( + path: AuthRoutes.forgotPassword, + builder: (_, state) => + Text(state.uri.queryParameters['email'] ?? ''), + ), + GoRoute( + path: AuthRoutes.signIn, + builder: (_, _) => const Text('sign-in route'), + ), + GoRoute( + path: AuthRoutes.signUp, + builder: (_, _) => const Text('sign-up route'), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + var signedIn = 0; + var signedUp = 0; + final routes = AuthRouter( + onSignedIn: (_) {}, + onSignedUp: (_) {}, + ).routes.whereType().toList(); + final state = GoRouterState.of(context); + expect(routes[0].builder!(context, state), isA()); + expect(routes[1].builder!(context, state), isA()); + expect( + (routes[2].builder!(context, state) as ForgotPasswordScreen).email, + isNull, + ); + final logger = di.get(); + final signIn = + SignInScreen( + onSignedIn: (_) => signedIn++, + logger: logger, + ).build(context) + as ui.SignInScreen; + final register = + RegisterScreen( + onSignedUp: (_) => signedUp++, + logger: logger, + ).build(context) + as ui.RegisterScreen; + final recovery = + const ForgotPasswordScreen( + email: 'person@example.test', + ).build(context) + as ui.ForgotPasswordScreen; + expect(recovery.email, 'person@example.test'); + final user = _User(); + final credential = _Credential(); + when(() => user.providerData).thenReturn([]); + when(() => user.email).thenReturn('person@example.test'); + when(() => credential.user).thenReturn(user); + for (final actions in [signIn.actions, register.actions!]) { + actions + .whereType>() + .single + .invoke(context, ui.SignedIn(user)); + actions + .whereType>() + .single + .invoke(context, ui.UserCreated(credential)); + actions + .whereType>() + .single + .invoke(context, ui.AuthFailed(Exception('test'))); + } + await tester.pump(); + expect(signedIn, 2); + expect(signedUp, 2); + signIn.actions.whereType().single.callback( + context, + 'person@example.test', + ); + await tester.pumpAndSettle(); + expect(find.text('person@example.test'), findsOneWidget); + router.pop(); + await tester.pumpAndSettle(); + // Validate our builders independently of Firebase UI's platform implementation. + final widgets = [ + signIn.headerBuilder!(context, const BoxConstraints(), 0), + register.headerBuilder!(context, const BoxConstraints(), 0), + recovery.headerBuilder!(context, const BoxConstraints(), 0), + signIn.footerBuilder!(context, ui.AuthAction.signIn), + register.footerBuilder!(context, ui.AuthAction.signUp), + ]; + for (final widget in widgets) { + await tester.pumpWidget(MaterialApp(home: Scaffold(body: widget))); + expect(tester.takeException(), isNull); + } + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(seconds: 5)); + }, + ); + + for (final signedIn in [null, false, true]) { + testWidgets('route guard handles registered identity $signedIn', ( + tester, + ) async { + if (signedIn != null) { + final service = _AuthService(); + when(() => service.isSignedIn).thenReturn(signedIn); + di.register(service); + } + final router = GoRouter( + initialLocation: '/private', + routes: [ + GoAuthRoute( + path: '/private', + builder: (_, _) => const Text('private'), + ), + GoRoute( + path: AuthRoutes.signIn, + builder: (_, _) => const Text('login'), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text(signedIn == true ? 'private' : 'login'), findsOneWidget); + }); + } + + for (final registered in [false, true]) { + testWidgets('signOut with registered service $registered', (tester) async { + final service = _AuthService(); + when(service.signOut).thenAnswer((_) async {}); + if (registered) di.register(service); + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, _) => TextButton( + onPressed: () => signOut(context), + child: const Text('out'), + ), + ), + GoRoute( + path: AuthRoutes.signIn, + builder: (_, _) => const Text('login'), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.tap(find.text('out')); + await tester.pumpAndSettle(); + expect(find.text('login'), registered ? findsOneWidget : findsNothing); + registered + ? verify(service.signOut).called(1) + : verifyNever(service.signOut); + }); + } + + testWidgets('footers navigate to the opposite authentication route', ( + tester, + ) async { + for (final type in FooterType.values) { + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (context, _) => Scaffold( + body: footerBuilder( + context, + ui.AuthAction.signIn, + type, + di.get(), + ), + ), + ), + GoRoute( + path: AuthRoutes.signIn, + builder: (_, _) => const Text('login destination'), + ), + GoRoute( + path: AuthRoutes.signUp, + builder: (_, _) => const Text('register destination'), + ), + ], + ); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(GestureDetector).last); + await tester.pumpAndSettle(); + expect( + find.text( + type == FooterType.signIn + ? 'register destination' + : 'login destination', + ), + findsOneWidget, + ); + await tester.pumpWidget(const SizedBox()); + router.dispose(); + } + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/auth/test/token_provider_test.dart b/packages/nonstop_cli/example/nonstop_example/features/auth/test/token_provider_test.dart new file mode 100644 index 0000000..fd7c3b2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/auth/test/token_provider_test.dart @@ -0,0 +1,146 @@ +import 'dart:async'; + +import 'package:auth/data/token/firebase_auth_token_provider.dart'; +import 'package:core/core.dart'; +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Auth extends Mock implements FirebaseAuth {} + +class _User extends Mock implements User {} + +class _Token extends Mock implements IdTokenResult {} + +class _Logger extends Mock implements Logger {} + +void main() { + late _Auth auth; + late _User user; + late _Logger logger; + late _Token token; + late StreamController events; + late FirebaseAuthTokenProvider provider; + late DateTime now; + + setUp(() { + auth = _Auth(); + user = _User(); + token = _Token(); + logger = _Logger(); + now = DateTime(2026); + events = StreamController(); + when(auth.idTokenChanges).thenAnswer((_) => events.stream); + when(() => auth.currentUser).thenReturn(user); + when(() => user.uid).thenReturn('user-1'); + when(() => token.token).thenReturn('test-token'); + when( + () => token.expirationTime, + ).thenReturn(now.add(const Duration(hours: 1))); + when(() => user.getIdTokenResult(any())).thenAnswer((_) async => token); + when(auth.signOut).thenAnswer((_) async {}); + provider = FirebaseAuthTokenProvider( + firebaseAuth: auth, + logger: logger, + now: () => now, + ); + }); + tearDown(() async { + await provider.dispose(); + await events.close(); + }); + + test('Firebase expiration controls cached-token reuse and refresh', () async { + expect(provider.isTokenExpired, isTrue); + expect(provider.isAuthenticated, isTrue); + expect(await provider.getValidToken(), 'test-token'); + expect(provider.getCurrentToken(), 'test-token'); + expect(provider.isTokenExpired, isFalse); + expect(await provider.getValidToken(), 'test-token'); + verify(() => user.getIdTokenResult(false)).called(1); + now = now.add(const Duration(minutes: 55)); + expect(provider.isTokenExpired, isTrue); + await provider.getValidToken(); + verify(() => user.getIdTokenResult(false)).called(1); + await provider.refreshToken(); + verify(() => user.getIdTokenResult(true)).called(1); + }); + + test('signed-out users have no token', () async { + when(() => auth.currentUser).thenReturn(null); + expect(provider.isAuthenticated, isFalse); + expect(await provider.getValidToken(), isNull); + expect(await provider.refreshToken(), isNull); + }); + + test('token events publish refreshed tokens and clear on sign-out', () async { + final values = []; + final subscription = provider.tokenStream.listen(values.add); + events.add(user); + await pumpEventQueue(); + expect(values, [null, 'test-token']); + when(() => auth.currentUser).thenReturn(null); + events.add(null); + await pumpEventQueue(); + expect(provider.getCurrentToken(), isNull); + expect(values.last, isNull); + await subscription.cancel(); + }); + + test('read and stream errors clear cached credentials', () async { + await provider.getValidToken(); + when( + () => user.getIdTokenResult(any()), + ).thenThrow(StateError('unavailable')); + expect(await provider.refreshToken(), isNull); + expect(provider.getCurrentToken(), isNull); + events.addError(StateError('stream failure'), StackTrace.current); + await pumpEventQueue(); + expect(provider.isTokenExpired, isTrue); + }); + + test( + 'sign-out clears credentials and late refreshes cannot restore them', + () async { + final pending = Completer(); + when( + () => user.getIdTokenResult(any()), + ).thenAnswer((_) => pending.future); + final refresh = provider.refreshToken(); + await provider.signOut(); + pending.complete(token); + expect(await refresh, isNull); + expect(provider.getCurrentToken(), isNull); + verify(auth.signOut).called(1); + }, + ); + + test('an account change invalidates an in-flight response', () async { + final pending = Completer(); + when(() => user.getIdTokenResult(any())).thenAnswer((_) => pending.future); + final refresh = provider.refreshToken(); + when(() => auth.currentUser).thenReturn(null); + pending.complete(token); + expect(await refresh, isNull); + }); + + test('disposing during refresh closes safely and is idempotent', () async { + final pending = Completer(); + when(() => user.getIdTokenResult(any())).thenAnswer((_) => pending.future); + final refresh = provider.refreshToken(); + await provider.dispose(); + pending.completeError(StateError('late error')); + expect(await refresh, isNull); + expect(provider.isAuthenticated, isFalse); + expect(await provider.getValidToken(), isNull); + expect(await provider.refreshToken(), isNull); + await provider.dispose(); + }); + + test('null token results do not throw', () async { + when(() => token.token).thenReturn(null); + when(() => token.expirationTime).thenReturn(null); + expect(await provider.getValidToken(), isNull); + expect(provider.isTokenExpired, isTrue); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/features/dashboard/CLAUDE.md new file mode 100644 index 0000000..1797a5a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/CLAUDE.md @@ -0,0 +1,82 @@ +# Nonstop Example: `features/dashboard` + +The bottom-navigation shell for the signed-in area and its starter tabs (Home, +Explore, Profile). It owns tab layout and tab screens only. It does not know +about auth: the route guard and the sign-out action are injected by the app. It +has no `init()`, no services and no `di` registrations. + +Read the root `CLAUDE.md` and `features/CLAUDE.md` first. +Load the `design-system` skill before changing UI. + +## Public API (`package:dashboard/dashboard.dart`) + +| Symbol | Kind | Notes | +|---|---|---| +| `DashboardRouter.createShellRoute({redirect, onOpenSettings, onSignOut})` | `StatefulShellRoute` | `redirect` applied to every tab; `onOpenSettings` and `onSignOut` forwarded to `ProfileTabScreen` | +| `DashboardRouter.home` / `explore` / `profile` | route constants | `/home/dashboard`, `/home/explore`, `/home/profile` | +| `DashboardShellScreen({navigationShell})` | widget | `NavigationBar` over the shell | +| `HomeTabScreen`, `ExploreTabScreen` | widgets | placeholder tabs | +| `ProfileTabScreen({onOpenSettings, onSignOut})` | widget | avatar (dev-tools entry), optional settings tile, optional sign-out | +| `PlaceholderTab({icon, title, subtitle, action})` | widget | "nothing here yet" body | + +The app wires it as +`DashboardRouter.createShellRoute(redirect: auth.authRedirect(allowUnconfigured: true), onSignOut: AppRouter.signOut)` +(no `onOpenSettings` yet, so the settings tile is hidden). + +## Layout + +``` +lib/ + dashboard.dart barrel + router/dashboard_router.dart DashboardRouter: paths + indexed-stack shell, one branch per tab + ui/screens/dashboard_shell_screen.dart NavigationBar; destinations are positional with branches + ui/screens/home_tab_screen.dart Home placeholder + ui/screens/explore_tab_screen.dart Explore placeholder + ui/screens/profile_tab_screen.dart profile, optional settings tile, sign-out with confirm dialog + ui/widgets/placeholder_tab.dart PlaceholderTab +``` + +## Rules + +- Never import `auth` (or any feature). New cross-feature behavior is a new + optional parameter on `createShellRoute`, supplied by `apps/nonstop_example/lib/router/router.dart`. +- Branch order in `createShellRoute` must match destination order in + `DashboardShellScreen`; `goBranch` uses the index. +- Every tab goes through the local `tab(path, screen)` helper so it gets `redirect`. +- Sign-out runs only after the dialog returns `true` and `context.mounted`. + Each profile tile is hidden when its callback (`onOpenSettings`, `onSignOut`) is null. +- Tapping the current tab again calls `goBranch(..., initialLocation: true)` + (pops to the tab root). +- The avatar is wrapped in `developer`'s `OpenDevToolsWrapper` (5 taps). + +## Common changes + +- **Add a tab:** path constant and `StatefulShellBranch` via `tab(...)` in + `router/dashboard_router.dart`; screen in `ui/screens/` + `index.dart`; + `NavigationDestination` at the same index in `dashboard_shell_screen.dart` + (icon from `NavigationIcons`, label from `strings.nav.*`, add the key in `localization`). Extend the + navigation test in `test/dashboard_test.dart` to tap it and assert its path + was redirected through. +- **Replace a placeholder tab:** swap `PlaceholderTab` in the tab screen for real + content; real data and state belong in their own feature, passed in the same + way as `onSignOut`. +- **Inject another app callback:** add an optional parameter to + `createShellRoute`, forward it to the screen, wire it in the app router, and + test both the set and null cases like `onOpenSettings` / `onSignOut`. + +## Tests + +`test/dashboard_test.dart`: tab navigation hits `home`/`explore`/`profile` and +runs the injected `redirect` for each; the settings tile calls `onOpenSettings`; +sign-out cancel does nothing, confirm calls `onSignOut` once; +`ProfileTabScreen()` hides settings and sign-out; `PlaceholderTab` action fires. Pattern: real `GoRouter` with a recording `redirect` and counter +callbacks, `setUp(core.init)` / `tearDown(di.reset)`. + +`dart run melos exec --scope=dashboard -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- All copy comes from `strings.*`, including the placeholder subtitles; tests + find the tab by `strings.nav.explore`. +- `core` and `di` are dev dependencies, used only by the test. +- Route paths live on `DashboardRouter`, not in a `constants/routes.dart`. diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/README.md b/packages/nonstop_cli/example/nonstop_example/features/dashboard/README.md new file mode 100644 index 0000000..4f80f3e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/README.md @@ -0,0 +1,18 @@ +# Dashboard + +Dashboard feature with bottom navigation + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) + +## Installation 💻 + +**❗ In order to start using Dashboard you must have the [Flutter SDK][flutter_install_link] installed on your machine.** + +Install via `dart pub add`: + +```sh +dart pub add dashboard +``` + +[flutter_install_link]: https://docs.flutter.dev/get-started/install \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/dashboard.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/dashboard.dart new file mode 100644 index 0000000..ffb156e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/dashboard.dart @@ -0,0 +1,5 @@ +library; + +export 'router/dashboard_router.dart'; +export 'ui/screens/index.dart'; +export 'ui/widgets/index.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/router/dashboard_router.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/router/dashboard_router.dart new file mode 100644 index 0000000..87036e4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/router/dashboard_router.dart @@ -0,0 +1,44 @@ +import 'package:dashboard/ui/screens/index.dart'; +import 'package:flutter/widgets.dart'; +import 'package:go_router/go_router.dart'; + +/// Bottom-navigation shell for the signed-in part of the app. +/// +/// Add a tab by adding a [StatefulShellBranch] here and a destination in +/// [DashboardShellScreen]. +abstract final class DashboardRouter { + static const String home = '/home/dashboard'; + static const String explore = '/home/explore'; + static const String profile = '/home/profile'; + + /// [redirect] guards every tab (the app passes its auth guard); + /// [onOpenSettings] and [onSignOut] show the settings and sign-out actions + /// on the profile tab when given. All are injected so the dashboard never depends on another feature. + static StatefulShellRoute createShellRoute({ + GoRouterRedirect? redirect, + void Function(BuildContext context)? onOpenSettings, + Future Function(BuildContext context)? onSignOut, + }) { + GoRoute tab(String path, Widget screen) => + GoRoute(path: path, redirect: redirect, builder: (_, _) => screen); + return StatefulShellRoute.indexedStack( + builder: (context, state, navigationShell) => + DashboardShellScreen(navigationShell: navigationShell), + branches: [ + StatefulShellBranch(routes: [tab(home, const HomeTabScreen())]), + StatefulShellBranch(routes: [tab(explore, const ExploreTabScreen())]), + StatefulShellBranch( + routes: [ + tab( + profile, + ProfileTabScreen( + onOpenSettings: onOpenSettings, + onSignOut: onSignOut, + ), + ), + ], + ), + ], + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/dashboard_shell_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/dashboard_shell_screen.dart new file mode 100644 index 0000000..2f8727d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/dashboard_shell_screen.dart @@ -0,0 +1,54 @@ +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +/// Hosts the bottom navigation bar and keeps each tab's navigation stack alive. +/// +/// Add a tab by adding a [StatefulShellBranch] in `DashboardRouter` and a +/// matching destination here - the two lists are positional. +class DashboardShellScreen extends StatefulWidget { + const DashboardShellScreen({super.key, required this.navigationShell}); + + final StatefulNavigationShell navigationShell; + + @override + State createState() => _DashboardShellScreenState(); +} + +class _DashboardShellScreenState extends State { + void _onDestinationSelected(int index) { + widget.navigationShell.goBranch( + index, + initialLocation: index == widget.navigationShell.currentIndex, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: widget.navigationShell, + bottomNavigationBar: NavigationBar( + selectedIndex: widget.navigationShell.currentIndex, + onDestinationSelected: _onDestinationSelected, + destinations: [ + NavigationDestination( + icon: const Icon(NavigationIcons.home), + selectedIcon: const Icon(NavigationIcons.homeSelected), + label: strings.nav.home, + ), + NavigationDestination( + icon: const Icon(NavigationIcons.explore), + selectedIcon: const Icon(NavigationIcons.exploreSelected), + label: strings.nav.explore, + ), + NavigationDestination( + icon: const Icon(NavigationIcons.profile), + selectedIcon: const Icon(NavigationIcons.profileSelected), + label: strings.nav.profile, + ), + ], + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/explore_tab_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/explore_tab_screen.dart new file mode 100644 index 0000000..f12408c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/explore_tab_screen.dart @@ -0,0 +1,22 @@ +import 'package:dashboard/ui/widgets/index.dart'; +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +class ExploreTabScreen extends StatelessWidget { + const ExploreTabScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text(strings.nav.explore)), + body: SafeArea( + child: PlaceholderTab( + icon: NavigationIcons.exploreSelected, + title: strings.nav.explore, + subtitle: strings.nav.explore_placeholder, + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/home_tab_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/home_tab_screen.dart new file mode 100644 index 0000000..340cac9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/home_tab_screen.dart @@ -0,0 +1,22 @@ +import 'package:dashboard/ui/widgets/index.dart'; +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +class HomeTabScreen extends StatelessWidget { + const HomeTabScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text(strings.nav.dashboard)), + body: SafeArea( + child: PlaceholderTab( + icon: NavigationIcons.homeSelected, + title: strings.app.welcome_to_app, + subtitle: strings.app.description, + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/index.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/index.dart new file mode 100644 index 0000000..8bebb72 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/index.dart @@ -0,0 +1,4 @@ +export 'dashboard_shell_screen.dart'; +export 'explore_tab_screen.dart'; +export 'home_tab_screen.dart'; +export 'profile_tab_screen.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/profile_tab_screen.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/profile_tab_screen.dart new file mode 100644 index 0000000..2ab8f39 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/screens/profile_tab_screen.dart @@ -0,0 +1,92 @@ +import 'package:design_system/design_system.dart'; +import 'package:developer/developer.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +/// Account tab: identity, settings entry points, sign out. +/// +/// This is deliberately thin - hang your real profile feature off it. +class ProfileTabScreen extends StatelessWidget { + const ProfileTabScreen({super.key, this.onOpenSettings, this.onSignOut}); + + /// Shows the settings entry when set; runs when it is tapped. + final void Function(BuildContext context)? onOpenSettings; + + /// Shows the sign-out action when set; runs after the user confirms. + final Future Function(BuildContext context)? onSignOut; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text(strings.profile.profile)), + body: SafeArea( + child: ListView( + children: [ + const SizedBox(height: 16), + // Tap the avatar 5x to open developer tools. + OpenDevToolsWrapper(child: const _ProfileAvatar()), + const SizedBox(height: 24), + if (onOpenSettings case final onOpenSettings?) + ListTile( + leading: const Icon(NavigationIcons.settings), + title: Text(strings.profile.settings), + trailing: const Icon(Icons.chevron_right), + onTap: () => onOpenSettings(context), + ), + if (onSignOut case final onSignOut?) + ListTile( + leading: const Icon(Icons.logout), + title: Text(strings.auth.sign_out), + onTap: () => _confirmSignOut(context, onSignOut), + ), + ], + ), + ), + ); + } + + Future _confirmSignOut( + BuildContext context, + Future Function(BuildContext context) onSignOut, + ) async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(strings.auth.sign_out), + content: Text(strings.auth.sign_out_confirmation), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(strings.generic.cancel), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: Text(strings.auth.sign_out), + ), + ], + ), + ); + + if (confirmed == true && context.mounted) await onSignOut(context); + } +} + +class _ProfileAvatar extends StatelessWidget { + const _ProfileAvatar(); + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + return Center( + child: CircleAvatar( + radius: 44, + backgroundColor: colorScheme.primaryContainer, + child: Icon( + NavigationIcons.profileSelected, + size: 44, + color: colorScheme.onPrimaryContainer, + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/index.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/index.dart new file mode 100644 index 0000000..7abc376 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/index.dart @@ -0,0 +1 @@ +export 'placeholder_tab.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/placeholder_tab.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/placeholder_tab.dart new file mode 100644 index 0000000..e367fed --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/lib/ui/widgets/placeholder_tab.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; + +/// Drop-in "nothing here yet" tab body. +/// +/// Delete this the moment a tab grows real content. +class PlaceholderTab extends StatelessWidget { + const PlaceholderTab({ + super.key, + required this.icon, + required this.title, + required this.subtitle, + this.action, + }); + + final IconData icon; + final String title; + final String subtitle; + final Widget? action; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textTheme = theme.textTheme; + + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: colorScheme.primary.withValues(alpha: 0.1), + shape: BoxShape.circle, + ), + child: Icon(icon, size: 72, color: colorScheme.primary), + ), + const SizedBox(height: 32), + Text( + title, + style: textTheme.headlineMedium?.copyWith( + color: colorScheme.onSurface, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + Text( + subtitle, + style: textTheme.bodyLarge?.copyWith( + color: colorScheme.onSurfaceVariant, + height: 1.5, + ), + textAlign: TextAlign.center, + ), + if (action != null) ...[const SizedBox(height: 32), action!], + ], + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/features/dashboard/pubspec.yaml new file mode 100644 index 0000000..f2aea4c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/pubspec.yaml @@ -0,0 +1,32 @@ +name: dashboard +description: "Bottom-navigation shell and starter tabs for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + go_router: ^18.0.1 + design_system: + path: ../../packages/design_system + localization: + path: ../../packages/localization + developer: + path: ../../packages/developer + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + core: + path: ../../packages/core + di: + path: ../../packages/di + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/features/dashboard/test/dashboard_test.dart b/packages/nonstop_cli/example/nonstop_example/features/dashboard/test/dashboard_test.dart new file mode 100644 index 0000000..3acf66b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/features/dashboard/test/dashboard_test.dart @@ -0,0 +1,111 @@ +import 'package:core/core.dart' as core; +import 'package:dashboard/dashboard.dart'; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; + +void main() { + setUp(core.init); + tearDown(di.reset); + + testWidgets('tabs navigate and profile sign-out requires confirmation', ( + tester, + ) async { + var signOuts = 0; + var settingsOpened = 0; + final redirected = []; + final router = GoRouter( + initialLocation: DashboardRouter.home, + routes: [ + DashboardRouter.createShellRoute( + redirect: (_, state) { + redirected.add(state.uri.path); + return null; + }, + onOpenSettings: (_) => settingsOpened++, + onSignOut: (context) async { + signOuts++; + context.go('/signed-out'); + }, + ), + GoRoute( + path: '/signed-out', + builder: (_, _) => const Text('Signed out'), + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect( + router.routeInformationProvider.value.uri.path, + DashboardRouter.home, + ); + await tester.tap(find.text(strings.nav.explore).last); + await tester.pumpAndSettle(); + expect( + router.routeInformationProvider.value.uri.path, + DashboardRouter.explore, + ); + await tester.tap(find.text(strings.nav.profile).last); + await tester.pumpAndSettle(); + expect( + router.routeInformationProvider.value.uri.path, + DashboardRouter.profile, + ); + expect( + redirected, + containsAll([ + DashboardRouter.home, + DashboardRouter.explore, + DashboardRouter.profile, + ]), + ); + await tester.tap(find.text(strings.profile.settings)); + expect(settingsOpened, 1); + await tester.tap(find.text(strings.auth.sign_out)); + await tester.pumpAndSettle(); + await tester.tap(find.text(strings.generic.cancel)); + await tester.pumpAndSettle(); + expect(signOuts, 0); + await tester.tap(find.text(strings.auth.sign_out)); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FilledButton, strings.auth.sign_out)); + await tester.pumpAndSettle(); + expect(signOuts, 1); + expect(find.text('Signed out'), findsOneWidget); + }); + + testWidgets('profile hides settings and sign-out without handlers', ( + tester, + ) async { + await tester.pumpWidget(const MaterialApp(home: ProfileTabScreen())); + expect(find.text(strings.profile.settings), findsNothing); + expect(find.text(strings.auth.sign_out), findsNothing); + }); + + testWidgets('placeholder supports an action', (tester) async { + var calls = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PlaceholderTab( + icon: Icons.add, + title: 'Title', + subtitle: 'Subtitle', + action: TextButton( + onPressed: () { + calls++; + }, + child: const Text('Start'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Start')); + expect(calls, 1); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/CLAUDE.md new file mode 100644 index 0000000..9a7ed63 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/CLAUDE.md @@ -0,0 +1,69 @@ +# Nonstop Example: `packages/` + +Shared capabilities used by features and apps. Read the root `CLAUDE.md` first. +A package knows nothing about the product: no feature names, no screens, no +product copy. + +## Layers + +A package may depend only on packages in a **lower** row. Adding an upward or +same-row dependency needs a reason stated in the change. + +| Layer | Packages | Depends on | +|---|---|---| +| 0 | `di`, `localization`, `utils` | nothing in the workspace | +| 1 | `core` | `di`, `localization` | +| 2 | `analytics`, `crashlytics`, `feature_flags` | `core`, `di` | +| 2 | `network` | `core`, `di`, `localization` | +| 3 | `notifications` | `core`, `di`, `network` | +| 3 | `design_system` | `core`, `di`, `localization`, `network` | +| 3 | `developer` | `core`, `di`, `localization`, `feature_flags` | + +`developer` does not depend on `design_system`; keep it that way. + +## Package conventions + +- Every package has its own `CLAUDE.md`: read it before editing the package, + and update it in the same change when its API, rules or gotchas change. +- Public API is `lib/.dart`; implementation under `lib/src/`, grouped by + role (`client/`, `config/`, `models/`, `exceptions/`), each with an + `index.dart` barrel. `core` and `design_system` are older: their role folders + sit directly under `lib/`. +- **Contract + implementation** for anything backed by an SDK or I/O: + `AnalyticsClient` / `FirebaseAnalyticsClient`, `NetworkClient` / + `DioNetworkClient`. Consumers depend on the contract; the implementation takes + its SDK, logger and clock through the constructor. +- A package exposes an `init({config})` that registers its implementation with + `di`. It never reads `Environment` itself; the app passes config in. +- Owned disposables (streams, subscriptions, timers, SDK handlers) are released + through the `dispose:` callback given to `di.register`. +- Exceptions are typed per package (`network_exceptions.dart`, ...). + +## Package-specific notes + +- **`core`**: logger (`Logger` contract, Talker implementation), environment, + `CoreRouter` contract, global event channel, route/bloc observers, base + exceptions, converters, extensions. Keep it small; a helper + used by one package belongs in that package. +- **`di`**: the only place `get_it` is imported. Everything else uses the + `DependencyInjection` interface via `di`. +- **`localization`**: edit `lib/messages.i69n.yaml`, then run + `dart run melos run generate:i69n`. Never edit `messages.i69n.dart`. Keys are + grouped by area (`generic`, `errors`, `auth`, ...); add to the right group. +- **`design_system`**: `lib/generated/theme.dart` comes from Material Theme + Builder; replace the file wholesale when the palette changes. Shared + components must be stateless where possible, accept everything they render as + parameters, and meet accessibility basics (semantics labels, 48dp targets, + contrast). +- **`network`**: bearer headers are attached only for the configured API origin; + logs omit headers, query values and bodies. Keep both properties when + changing interceptors. `network_response.g.dart` is generated: run + `dart run melos run generate`. +- **`notifications`**: owns SDK subscriptions only. Navigation and toasts are + callbacks supplied by the app. + +## Tests + +Test the implementation against a fake SDK/transport, and test consumers +against a fake of the contract. No real network, Firebase or platform channels. +Every package must keep at least one `*_test.dart` or the coverage gate fails. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/README.md b/packages/nonstop_cli/example/nonstop_example/packages/README.md new file mode 100644 index 0000000..6175a25 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/README.md @@ -0,0 +1,13 @@ +# Packages + +Horizontal capabilities shared across features: networking, design system, +logging, analytics, dependency injection. + +A package here must not depend on a `features/` package - dependencies point +inward, from features to packages. + +Add one with: + +```sh +nonstop create my_package --template package -o packages +``` diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/analytics/CLAUDE.md new file mode 100644 index 0000000..970252f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/CLAUDE.md @@ -0,0 +1,67 @@ +# Nonstop Example: `packages/analytics` + +Owns event tracking behind `AnalyticsClient`: the Firebase Analytics adapter, +the event-name catalog, screen tracking and static helpers. It does not own +consent or product policy (the app decides `enableAnalytics`), and holds no +feature logic. Layer 2: depends on `core`, `di`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | +|---|---| +| `AnalyticsClient` / `FirebaseAnalyticsClient(config, analytics:, logger:)` | `abstract interface class` / Firebase implementation: `logEvent`, `logCustomEvent`, `setUserId`, `setUserProperty`, `resetAnalyticsData`, `setAnalyticsCollectionEnabled`, `logScreenView`, `logAppOpen`, `logLogin`, `logSignUp`, `logPurchase`, `dispose`; plus `initialize()` and `@visibleForTesting static toFirebaseParameters` on the implementation | +| `init({config, analytics})`, `registerAnalyticsWithDI` | Awaits `initialize()`, registers `AnalyticsClient` (with `dispose`) and `AnalyticsConfig` | +| `AnalyticsConfig` (interface) / `DefaultAnalyticsConfig` | `enableAnalytics`, `enableDebugLogging`, `userId`, `defaultUserProperties`, `copyWith` | +| `AnalyticsEvent` | Name + parameters value object | +| `AnalyticsEvents` | Catalog: `user`, `auth`, `navigation`, `feature`, `error`, `app`, `profile` | +| `PredefinedEvents`, `PredefinedParameters` | Firebase standard names | +| `AnalyticsRouteObserver(client:, logger:)` | `NavigatorObserver` logging named `PageRoute`s | +| `AnalyticsHelper` | `abstract final class` of static fire-and-forget wrappers resolving `AnalyticsClient` from `di` per call | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/analytics.dart` | Barrel, `init`, `registerAnalyticsWithDI` | +| `lib/src/client/` | Contract and `FirebaseAnalyticsClient` | +| `lib/src/config/` | `AnalyticsConfig`, `DefaultAnalyticsConfig` | +| `lib/src/models/analytics_event.dart` | `AnalyticsEvent`, `PredefinedEvents`, `PredefinedParameters` | +| `lib/src/models/analytics_events.dart` | `AnalyticsEvents` catalog | +| `lib/src/observer/` | `AnalyticsRouteObserver` | +| `lib/src/utils/` | `AnalyticsHelper` | + +## Rules + +- **Analytics failures never break UI.** Every `FirebaseAnalyticsClient` call except `initialize()` catches and logs through `Logger.e`. `AnalyticsHelper` returns silently when no client is registered and catches client errors. `AnalyticsRouteObserver` tracks with `unawaited` and catches. +- **Startup is not swallowed.** `initialize()` rethrows SDK errors, so `init` fails and nothing is registered. +- **Collection switch.** `_enabled` starts from `config.enableAnalytics`; when false, `logEvent` returns without calling the SDK. `setAnalyticsCollectionEnabled` updates it only after the SDK call succeeds. +- **Parameters** go through `toFirebaseParameters`: nulls are dropped, `String`/`num` pass through, `bool` and other objects become `toString()`. +- **Documented locator facade.** `AnalyticsHelper` is the one allowed service-locator facade: it resolves the client via `di.has`/`di.get` on every call and is a silent no-op when none is registered. Do not add a static cache; code that needs results or testable wiring injects `AnalyticsClient` instead. +- **Privacy.** User IDs, property values and event parameters are never logged; debug logging (`enableDebugLogging`) names only the event or property. A test asserts user IDs stay out of the log. Do not add PII to event parameters. +- **Injected:** `FirebaseAnalytics` and `Logger`. The helpers' `timestamp` parameters use `DateTime.now()` (no clock). +- Screen tracking uses `RouteSettings.name`; unnamed or non-page routes are skipped. The app adds the observer in `apps/nonstop_example/lib/router/router.dart` only when `AnalyticsClient` is registered. + +## Common changes + +- **Add an event name:** add a getter to the right `_XxxEvents` class in `analytics_events.dart` (or a new group and a `static const` on `AnalyticsEvents`). Append it to both lists in `test/event_names_test.dart`; that test asserts exact strings and uniqueness. +- **Add a semantic helper:** add a static method to `AnalyticsHelper` that goes through `logEvent` or a client method with try/catch, then add it to the `operations` list in `test/helper_test.dart` (absent service, success and failure are covered in one test). +- **Add a client method:** declare it on `AnalyticsClient`, implement it with try/catch in `FirebaseAnalyticsClient`, cover success and SDK failure in `test/client_test.dart`. Any other `AnalyticsClient` implementation, including test fakes, must add it too. + +## Tests + +| File | Covers | +|---|---| +| `test/client_test.dart` | Semantic event names/params, `initialize` success and failure, null stripping, parameter coercion, user IDs never logged, collection toggle, contained SDK failures, `init` and helpers after `di.reset` | +| `test/helper_test.dart` | Every helper without/with/failing client, route observer push/pop/replace, `AnalyticsEvent` equality, config `copyWith` | +| `test/event_names_test.dart` | Stable, unique catalog strings | +| `test/analytics_test.dart` | Model and config construction | + +Doubles: mocktail `FirebaseAnalytics` (`_Sdk`), `AnalyticsClient` (`_Client`), `Logger`. + +`dart run melos exec --scope=analytics -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `init` needs `Logger` registered first and Firebase initialized; bootstrap calls it only when Firebase is ready, so code must tolerate `AnalyticsClient` being absent (`di.has`). diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/README.md b/packages/nonstop_cli/example/nonstop_example/packages/analytics/README.md new file mode 100644 index 0000000..5810c2e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/README.md @@ -0,0 +1,92 @@ +# analytics + +Event tracking for Nonstop Example behind the `AnalyticsClient` interface, +with a Firebase Analytics implementation, a route observer for screen views and +a static `AnalyticsHelper` facade for UI code. + +## Initialise + +Firebase must be initialised and a `Logger` registered. + +```dart +import 'package:analytics/analytics.dart' as analytics; + +await analytics.init( + config: const analytics.DefaultAnalyticsConfig( + enableAnalytics: !kDebugMode, + enableDebugLogging: kDebugMode, + ), +); +``` + +`init` applies the config to Firebase, then registers `AnalyticsClient` and +`AnalyticsConfig`. SDK failures during `init` propagate. + +## Configure + +| `DefaultAnalyticsConfig` field | Default | Effect | +| --- | --- | --- | +| `enableAnalytics` | `true` | collection on/off; when off, events are skipped | +| `enableDebugLogging` | `false` | logs event names (never parameters or user ids) at debug | +| `userId` | `null` | initial analytics user id | +| `defaultUserProperties` | `null` | user properties set at startup | + +`setAnalyticsCollectionEnabled` changes collection at runtime. + +## Screen tracking + +`AnalyticsRouteObserver` logs a `screen_view` for every named `PageRoute` on +push, pop (the route returned to) and replace: + +```dart +GoRouter( + observers: [ + AnalyticsRouteObserver( + client: di.get(), + logger: di.get(), + ), + ], + routes: [...], +); +``` + +## Logging events + +From UI code, use `AnalyticsHelper`. It is the one allowed locator facade: it +resolves the registered client per call, does nothing when analytics is not +registered, and logs instead of throwing. + +```dart +await AnalyticsHelper.logEvent( + AnalyticsEvents.feature.tutorialCompleted, + parameters: {'tutorial_id': 'getting_started', 'duration_seconds': 120}, +); +await AnalyticsHelper.logSignIn(method: 'google'); +await AnalyticsHelper.logFeatureUsed('export'); +await AnalyticsHelper.logButtonPressed('get_started', screenName: 'home'); +await AnalyticsHelper.logAppError('network_timeout'); +``` + +Elsewhere, inject `AnalyticsClient`, which also offers `logScreenView`, +`logAppOpen`, `logLogin`, `logSignUp`, `logPurchase`, `setUserId`, +`setUserProperty` and `resetAnalyticsData`. + +Event names live in `AnalyticsEvents` (`user`, `auth`, `navigation`, `feature`, +`error`, `app`, `profile`); add your own groups there rather than using string +literals. + +Parameter values are converted to what Firebase accepts: `String` and `num` +pass through, `bool` becomes `'true'`/`'false'`, other objects use +`toString()`, and `null` entries are dropped. + +## Errors + +After `init`, client methods catch SDK failures and log them; analytics never +crashes the app. + +## Privacy rules + +- User ids are never written to the log. +- Do not put personal data (emails, names, raw ids, free-text errors from the + backend) into event parameters or user properties. +- Call `resetAnalyticsData()` and `setUserId(null)` on sign-out. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/analytics.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/analytics.dart new file mode 100644 index 0000000..7dae563 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/analytics.dart @@ -0,0 +1,47 @@ +library; + +import 'package:analytics/src/client/index.dart'; +import 'package:analytics/src/config/index.dart'; +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:firebase_analytics/firebase_analytics.dart'; + +export 'src/client/index.dart'; +export 'src/config/index.dart'; +export 'src/models/index.dart'; +export 'src/observer/index.dart'; +export 'src/utils/index.dart'; + +Future init({ + AnalyticsConfig config = const DefaultAnalyticsConfig(), + FirebaseAnalytics? analytics, +}) async { + await registerAnalyticsWithDI(config, analytics: analytics); + final logger = di.get(); + logger.i('Analytics module initialized with Firebase Analytics'); +} + +Future registerAnalyticsWithDI( + AnalyticsConfig config, { + FirebaseAnalytics? analytics, +}) async { + final logger = di.get(); + + final analyticsClient = FirebaseAnalyticsClient( + config, + analytics: analytics ?? FirebaseAnalytics.instance, + logger: logger, + ); + await analyticsClient.initialize(); + di.register( + analyticsClient, + dispose: (client) => client.dispose(), + ); + di.register(config); + + if (config.enableAnalytics) { + logger.i('Analytics client registered with collection enabled'); + } else { + logger.i('Analytics client registered with collection disabled'); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/analytics_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/analytics_client.dart new file mode 100644 index 0000000..e2d120c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/analytics_client.dart @@ -0,0 +1,44 @@ +import 'package:analytics/src/models/analytics_event.dart'; + +abstract interface class AnalyticsClient { + Future logEvent({ + required String name, + Map? parameters, + }); + + Future logCustomEvent(AnalyticsEvent event); + + Future setUserId(String? userId); + + Future setUserProperty({required String name, required String? value}); + + Future resetAnalyticsData(); + + Future setAnalyticsCollectionEnabled(bool enabled); + + Future logScreenView({ + required String screenName, + String? screenClass, + Map? parameters, + }); + + Future logAppOpen({Map? parameters}); + + Future logLogin({ + String? loginMethod, + Map? parameters, + }); + + Future logSignUp({ + String? signUpMethod, + Map? parameters, + }); + + Future logPurchase({ + required String currency, + required double value, + Map? parameters, + }); + + void dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/firebase_analytics_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/firebase_analytics_client.dart new file mode 100644 index 0000000..faf230a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/firebase_analytics_client.dart @@ -0,0 +1,222 @@ +import 'package:analytics/src/client/analytics_client.dart'; +import 'package:analytics/src/config/analytics_config.dart'; +import 'package:analytics/src/models/analytics_event.dart'; +import 'package:core/core.dart'; +import 'package:firebase_analytics/firebase_analytics.dart'; +import 'package:flutter/foundation.dart'; + +class FirebaseAnalyticsClient implements AnalyticsClient { + FirebaseAnalyticsClient( + this._config, { + required FirebaseAnalytics analytics, + required Logger logger, + }) : _analytics = analytics, + _logger = logger, + _enabled = _config.enableAnalytics; + + final AnalyticsConfig _config; + final FirebaseAnalytics _analytics; + final Logger _logger; + bool _enabled; + + Future initialize() async { + await _analytics.setAnalyticsCollectionEnabled(_enabled); + + if (_config.userId != null) { + await _analytics.setUserId(id: _config.userId); + } + + if (_config.defaultUserProperties != null) { + for (final entry in _config.defaultUserProperties!.entries) { + await _analytics.setUserProperty(name: entry.key, value: entry.value); + } + _logger.d('Analytics default user properties set'); + } + + if (_config.enableDebugLogging) { + _logger.d('Firebase Analytics initialized with debug logging enabled'); + } else { + _logger.i('Firebase Analytics initialized'); + } + } + + @override + Future logEvent({ + required String name, + Map? parameters, + }) async { + try { + if (!_enabled) { + if (_config.enableDebugLogging) { + _logger.d('Analytics disabled, skipping event: $name'); + } + return; + } + + await _analytics.logEvent( + name: name, + parameters: parameters == null + ? null + : toFirebaseParameters(parameters), + ); + + if (_config.enableDebugLogging) { + _logger.d('Analytics event logged: $name'); + } + } catch (e, s) { + _logger.e('Failed to log analytics event: $name', e, s); + } + } + + /// Firebase accepts only `String` and `num` parameter values: `bool` + /// becomes `'true'`/`'false'`, other objects use `toString()`, nulls are + /// dropped. + @visibleForTesting + static Map toFirebaseParameters( + Map parameters, + ) => { + for (final MapEntry(:key, :value) in parameters.entries) + if (value != null) + key: switch (value) { + final String text => text, + final num number => number, + _ => value.toString(), + }, + }; + + @override + Future logCustomEvent(AnalyticsEvent event) async { + await logEvent(name: event.name, parameters: event.parameters); + } + + @override + Future setUserId(String? userId) async { + try { + await _analytics.setUserId(id: userId); + + if (_config.enableDebugLogging) { + _logger.d('Analytics user ID updated'); + } + } catch (e, s) { + _logger.e('Failed to set analytics user ID', e, s); + } + } + + @override + Future setUserProperty({ + required String name, + required String? value, + }) async { + try { + await _analytics.setUserProperty(name: name, value: value); + + if (_config.enableDebugLogging) { + _logger.d('Analytics user property set: $name'); + } + } catch (e, s) { + _logger.e('Failed to set analytics user property: $name', e, s); + } + } + + @override + Future resetAnalyticsData() async { + try { + await _analytics.resetAnalyticsData(); + + if (_config.enableDebugLogging) { + _logger.d('Analytics data reset'); + } + } catch (e, s) { + _logger.e('Failed to reset analytics data', e, s); + } + } + + @override + Future setAnalyticsCollectionEnabled(bool enabled) async { + try { + await _analytics.setAnalyticsCollectionEnabled(enabled); + _enabled = enabled; + + if (_config.enableDebugLogging) { + _logger.d('Analytics collection ${enabled ? 'enabled' : 'disabled'}'); + } + } catch (e, s) { + _logger.e('Failed to set analytics collection enabled: $enabled', e, s); + } + } + + @override + Future logScreenView({ + required String screenName, + String? screenClass, + Map? parameters, + }) async { + final eventParameters = { + PredefinedParameters.screenName: screenName, + PredefinedParameters.screenClass: ?screenClass, + ...?parameters, + }; + + await logEvent( + name: PredefinedEvents.screenView, + parameters: eventParameters, + ); + } + + @override + Future logAppOpen({Map? parameters}) async { + await logEvent(name: PredefinedEvents.appOpen, parameters: parameters); + } + + @override + Future logLogin({ + String? loginMethod, + Map? parameters, + }) async { + final eventParameters = { + PredefinedParameters.method: ?loginMethod, + ...?parameters, + }; + + await logEvent(name: PredefinedEvents.login, parameters: eventParameters); + } + + @override + Future logSignUp({ + String? signUpMethod, + Map? parameters, + }) async { + final eventParameters = { + PredefinedParameters.method: ?signUpMethod, + ...?parameters, + }; + + await logEvent(name: PredefinedEvents.signUp, parameters: eventParameters); + } + + @override + Future logPurchase({ + required String currency, + required double value, + Map? parameters, + }) async { + final eventParameters = { + PredefinedParameters.currency: currency, + PredefinedParameters.value: value, + ...?parameters, + }; + + await logEvent( + name: PredefinedEvents.purchase, + parameters: eventParameters, + ); + } + + @override + void dispose() { + // Firebase Analytics doesn't need explicit disposal + if (_config.enableDebugLogging) { + _logger.d('Firebase Analytics client disposed'); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/index.dart new file mode 100644 index 0000000..959ed69 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/client/index.dart @@ -0,0 +1,2 @@ +export 'analytics_client.dart'; +export 'firebase_analytics_client.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/analytics_config.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/analytics_config.dart new file mode 100644 index 0000000..499eab0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/analytics_config.dart @@ -0,0 +1,42 @@ +abstract interface class AnalyticsConfig { + bool get enableAnalytics; + bool get enableDebugLogging; + String? get userId; + Map? get defaultUserProperties; +} + +class DefaultAnalyticsConfig implements AnalyticsConfig { + const DefaultAnalyticsConfig({ + this.enableAnalytics = true, + this.enableDebugLogging = false, + this.userId, + this.defaultUserProperties, + }); + + @override + final bool enableAnalytics; + + @override + final bool enableDebugLogging; + + @override + final String? userId; + + @override + final Map? defaultUserProperties; + + DefaultAnalyticsConfig copyWith({ + bool? enableAnalytics, + bool? enableDebugLogging, + String? userId, + Map? defaultUserProperties, + }) { + return DefaultAnalyticsConfig( + enableAnalytics: enableAnalytics ?? this.enableAnalytics, + enableDebugLogging: enableDebugLogging ?? this.enableDebugLogging, + userId: userId ?? this.userId, + defaultUserProperties: + defaultUserProperties ?? this.defaultUserProperties, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/index.dart new file mode 100644 index 0000000..cfd2ef0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/config/index.dart @@ -0,0 +1 @@ +export 'analytics_config.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_event.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_event.dart new file mode 100644 index 0000000..81a47ea --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_event.dart @@ -0,0 +1,70 @@ +class AnalyticsEvent { + const AnalyticsEvent({required this.name, this.parameters}); + + final String name; + final Map? parameters; + + Map toMap() { + return {'name': name, if (parameters != null) 'parameters': parameters}; + } + + @override + String toString() => 'AnalyticsEvent(name: $name, parameters: $parameters)'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is AnalyticsEvent && + other.name == name && + _mapEquals(other.parameters, parameters); + } + + @override + int get hashCode => Object.hash( + name, + parameters == null + ? null + : Object.hashAllUnordered( + parameters!.entries.map((e) => Object.hash(e.key, e.value)), + ), + ); + + bool _mapEquals(Map? a, Map? b) { + if (a == null) return b == null; + if (b == null || a.length != b.length) return false; + for (final key in a.keys) { + if (!b.containsKey(key) || a[key] != b[key]) return false; + } + return true; + } +} + +class PredefinedEvents { + static const String appOpen = 'app_open'; + static const String login = 'login'; + static const String signUp = 'sign_up'; + static const String screenView = 'screen_view'; + static const String purchase = 'purchase'; + static const String selectContent = 'select_content'; + static const String share = 'share'; + static const String search = 'search'; + static const String beginCheckout = 'begin_checkout'; + static const String addToCart = 'add_to_cart'; + static const String removeFromCart = 'remove_from_cart'; + static const String viewItem = 'view_item'; + static const String viewItemList = 'view_item_list'; +} + +class PredefinedParameters { + static const String screenName = 'screen_name'; + static const String screenClass = 'screen_class'; + static const String method = 'method'; + static const String currency = 'currency'; + static const String value = 'value'; + static const String itemId = 'item_id'; + static const String itemName = 'item_name'; + static const String itemCategory = 'item_category'; + static const String contentType = 'content_type'; + static const String searchTerm = 'search_term'; + static const String userId = 'user_id'; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_events.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_events.dart new file mode 100644 index 0000000..b4ec336 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/analytics_events.dart @@ -0,0 +1,163 @@ +/// Structured analytics event names organized by category. +/// +/// Usage: `AnalyticsEvents.user.authenticatedRedirect`. Naming events here +/// instead of inline keeps them discoverable and typo-free, and gives you one +/// place to add the groups your own product needs. +abstract final class AnalyticsEvents { + /// User-related events + static const user = _UserEvents(); + + /// Authentication-related events + static const auth = _AuthEvents(); + + /// Navigation-related events + static const navigation = _NavigationEvents(); + + /// Feature usage events + static const feature = _FeatureEvents(); + + /// Error and debugging events + static const error = _ErrorEvents(); + + /// App lifecycle events + static const app = _AppEvents(); + + /// Profile-related events + static const profile = _ProfileEvents(); +} + +class _UserEvents { + const _UserEvents(); + + /// User successfully authenticated and redirected + String get authenticatedRedirect => 'user_authenticated_redirect'; + + /// User profile updated + String get profileUpdated => 'user_profile_updated'; + + /// User preferences changed + String get preferencesChanged => 'user_preferences_changed'; + + /// User completed onboarding + String get onboardingCompleted => 'user_onboarding_completed'; + + /// User account deleted + String get accountDeleted => 'user_account_deleted'; +} + +class _AuthEvents { + const _AuthEvents(); + + /// User signed in + String get signIn => 'auth_sign_in'; + + /// User signed up + String get signUp => 'auth_sign_up'; + + /// User signed out + String get signOut => 'auth_sign_out'; + + /// Password reset requested + String get passwordReset => 'auth_password_reset'; + + /// Authentication failed + String get failed => 'auth_failed'; + + /// Social authentication (Google, Apple, etc.) + String get socialLogin => 'auth_social_login'; +} + +class _NavigationEvents { + const _NavigationEvents(); + + /// Screen viewed (automatically tracked) + String get screenView => 'screen_view'; + + /// Tab switched in bottom navigation + String get tabSwitched => 'navigation_tab_switched'; + + /// Back button pressed + String get backPressed => 'navigation_back_pressed'; + + /// Deep link opened + String get deepLinkOpened => 'navigation_deep_link_opened'; +} + +class _FeatureEvents { + const _FeatureEvents(); + + /// Feature was used/accessed + String get used => 'feature_used'; + + /// Feature tutorial started + String get tutorialStarted => 'feature_tutorial_started'; + + /// Feature tutorial completed + String get tutorialCompleted => 'feature_tutorial_completed'; + + /// Feature feedback given + String get feedbackGiven => 'feature_feedback_given'; + + /// Button pressed + String get buttonPressed => 'button_pressed'; +} + +class _ErrorEvents { + const _ErrorEvents(); + + /// General app error occurred + String get appError => 'app_error'; + + /// Network error occurred + String get networkError => 'network_error'; + + /// Crash occurred + String get crash => 'app_crash'; + + /// API error occurred + String get apiError => 'api_error'; + + /// Validation error + String get validationError => 'validation_error'; +} + +class _AppEvents { + const _AppEvents(); + + /// App opened/launched + String get open => 'app_open'; + + /// App went to background + String get background => 'app_background'; + + /// App came to foreground + String get foreground => 'app_foreground'; + + /// App updated to new version + String get updated => 'app_updated'; + + /// App installed for first time + String get installed => 'app_installed'; + + /// App uninstalled + String get uninstalled => 'app_uninstalled'; +} + +class _ProfileEvents { + const _ProfileEvents(); + + /// Profile viewed + String get viewed => 'profile_viewed'; + + /// Profile edited + String get edited => 'profile_edited'; + + /// Profile photo updated + String get photoUpdated => 'profile_photo_updated'; + + /// Profile settings changed + String get settingsChanged => 'profile_settings_changed'; + + /// Profile privacy settings updated + String get privacyUpdated => 'profile_privacy_updated'; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/index.dart new file mode 100644 index 0000000..17f5809 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/models/index.dart @@ -0,0 +1,2 @@ +export 'analytics_event.dart'; +export 'analytics_events.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/analytics_route_observer.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/analytics_route_observer.dart new file mode 100644 index 0000000..9a4b60b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/analytics_route_observer.dart @@ -0,0 +1,43 @@ +import 'dart:async'; +import 'package:analytics/src/client/analytics_client.dart'; +import 'package:core/core.dart'; +import 'package:flutter/material.dart'; + +/// Tracks named pages through the analytics abstraction, including async errors. +class AnalyticsRouteObserver extends NavigatorObserver { + AnalyticsRouteObserver({ + required AnalyticsClient client, + required Logger logger, + }) : _client = client, + _logger = logger; + + final AnalyticsClient _client; + final Logger _logger; + + Future _track(Route? route) async { + if (route is! PageRoute || route.settings.name == null) return; + try { + await _client.logScreenView(screenName: route.settings.name!); + } catch (error, stack) { + _logger.e('Failed to track screen navigation', error, stack); + } + } + + @override + void didPush(Route route, Route? previousRoute) { + super.didPush(route, previousRoute); + unawaited(_track(route)); + } + + @override + void didPop(Route route, Route? previousRoute) { + super.didPop(route, previousRoute); + unawaited(_track(previousRoute)); + } + + @override + void didReplace({Route? newRoute, Route? oldRoute}) { + super.didReplace(newRoute: newRoute, oldRoute: oldRoute); + unawaited(_track(newRoute)); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/index.dart new file mode 100644 index 0000000..e4f9659 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/observer/index.dart @@ -0,0 +1 @@ +export 'analytics_route_observer.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/analytics_helper.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/analytics_helper.dart new file mode 100644 index 0000000..72e5f20 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/analytics_helper.dart @@ -0,0 +1,163 @@ +import 'package:analytics/src/client/analytics_client.dart'; +import 'package:analytics/src/models/analytics_event.dart'; +import 'package:analytics/src/models/analytics_events.dart'; +import 'package:core/core.dart'; +import 'package:di/di.dart'; + +/// Fire-and-forget analytics facade for UI code. +/// +/// This is the one allowed service-locator facade in the app: widgets and +/// feature helpers call these statics instead of threading an +/// [AnalyticsClient] through every constructor. Each call resolves the +/// registered client at call time and is a silent no-op when analytics is not +/// configured; client failures are logged, never thrown. Code that needs a +/// result or testable wiring should inject [AnalyticsClient] instead. +abstract final class AnalyticsHelper { + static AnalyticsClient? get _analyticsClient => + di.has() ? di.get() : null; + + static Logger? get _log => di.has() ? di.get() : null; + + /// Log a custom event with optional parameters + static Future logEvent( + String name, { + Map? parameters, + }) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.logEvent(name: name, parameters: parameters); + } catch (e, s) { + _log?.e('Failed to log analytics event: $name', e, s); + } + } + + /// Log user sign in + static Future logSignIn({ + String? method, + Map? parameters, + }) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.logLogin(loginMethod: method, parameters: parameters); + } catch (e, s) { + _log?.e('Failed to log sign in event', e, s); + } + } + + /// Log user sign up + static Future logSignUp({ + String? method, + Map? parameters, + }) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.logSignUp(signUpMethod: method, parameters: parameters); + } catch (e, s) { + _log?.e('Failed to log sign up event', e, s); + } + } + + /// Set user ID for analytics + static Future setUserId(String? userId) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.setUserId(userId); + } catch (e, s) { + _log?.e('Failed to set analytics user ID', e, s); + } + } + + /// Set user property + static Future setUserProperty({ + required String name, + required String? value, + }) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.setUserProperty(name: name, value: value); + } catch (e, s) { + _log?.e('Failed to set analytics user property: $name', e, s); + } + } + + /// Log app open event + static Future logAppOpen({Map? parameters}) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.logAppOpen(parameters: parameters); + } catch (e, s) { + _log?.e('Failed to log app open event', e, s); + } + } + + /// Log custom analytics event + static Future logCustomEvent(AnalyticsEvent event) async { + final client = _analyticsClient; + if (client == null) return; + + try { + await client.logCustomEvent(event); + } catch (e, s) { + _log?.e('Failed to log custom analytics event: ${event.name}', e, s); + } + } + + /// Common business events + static Future logFeatureUsed( + String featureName, { + Map? parameters, + }) async { + await logEvent( + AnalyticsEvents.feature.used, + parameters: { + 'feature_name': featureName, + 'timestamp': DateTime.now().toIso8601String(), + ...?parameters, + }, + ); + } + + static Future logButtonPressed( + String buttonName, { + String? screenName, + Map? parameters, + }) async { + await logEvent( + AnalyticsEvents.feature.buttonPressed, + parameters: { + 'button_name': buttonName, + 'screen_name': ?screenName, + 'timestamp': DateTime.now().toIso8601String(), + ...?parameters, + }, + ); + } + + static Future logAppError( + String errorType, { + String? errorMessage, + Map? parameters, + }) async { + await logEvent( + AnalyticsEvents.error.appError, + parameters: { + 'error_type': errorType, + 'error_message': ?errorMessage, + 'timestamp': DateTime.now().toIso8601String(), + ...?parameters, + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/index.dart new file mode 100644 index 0000000..7195697 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/lib/src/utils/index.dart @@ -0,0 +1 @@ +export 'analytics_helper.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/analytics/pubspec.yaml new file mode 100644 index 0000000..e9fe335 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/pubspec.yaml @@ -0,0 +1,27 @@ +name: analytics +description: "Event tracking for Nonstop Example behind a swappable client interface." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + firebase_analytics: ^12.6.0 + core: + path: ../core + di: + path: ../di + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/analytics_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/analytics_test.dart new file mode 100644 index 0000000..4414841 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/analytics_test.dart @@ -0,0 +1,26 @@ +import 'package:analytics/analytics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Analytics Package', () { + test('should create AnalyticsEvent correctly', () { + const event = AnalyticsEvent( + name: 'test_event', + parameters: {'key': 'value'}, + ); + + expect(event.name, 'test_event'); + expect(event.parameters, {'key': 'value'}); + }); + + test('should create DefaultAnalyticsConfig correctly', () { + const config = DefaultAnalyticsConfig( + enableAnalytics: true, + enableDebugLogging: false, + ); + + expect(config.enableAnalytics, isTrue); + expect(config.enableDebugLogging, isFalse); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/client_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/client_test.dart new file mode 100644 index 0000000..ff2d932 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/client_test.dart @@ -0,0 +1,216 @@ +import 'package:analytics/analytics.dart'; +import 'package:analytics/analytics.dart' as analytics; +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:firebase_analytics/firebase_analytics.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Sdk extends Mock implements FirebaseAnalytics {} + +class _Logger extends Mock implements Logger {} + +void main() { + late _Sdk sdk; + late _Logger logger; + late FirebaseAnalyticsClient client; + setUp(() { + sdk = _Sdk(); + logger = _Logger(); + when( + () => sdk.setAnalyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + when(() => sdk.setUserId(id: any(named: 'id'))).thenAnswer((_) async {}); + when( + () => sdk.setUserProperty( + name: any(named: 'name'), + value: any(named: 'value'), + ), + ).thenAnswer((_) async {}); + when( + () => sdk.logEvent( + name: any(named: 'name'), + parameters: any(named: 'parameters'), + ), + ).thenAnswer((_) async {}); + when(sdk.resetAnalyticsData).thenAnswer((_) async {}); + client = FirebaseAnalyticsClient( + const DefaultAnalyticsConfig( + enableDebugLogging: true, + userId: 'user', + defaultUserProperties: {'role': 'tester'}, + ), + analytics: sdk, + logger: logger, + ); + }); + tearDown(di.reset); + + test('semantic events forward additional parameters', () async { + await client.logScreenView( + screenName: 'home', + parameters: {'source': 'link'}, + ); + await client.logLogin(parameters: {'source': 'link'}); + await client.logSignUp(parameters: {'source': 'link'}); + await client.logPurchase( + currency: 'USD', + value: 2, + parameters: {'source': 'link'}, + ); + verify( + () => sdk.logEvent(name: 'login', parameters: {'source': 'link'}), + ).called(1); + verify( + () => sdk.logEvent(name: 'sign_up', parameters: {'source': 'link'}), + ).called(1); + }); + + test( + 'initialization awaits SDK setup and propagates startup failures', + () async { + await client.initialize(); + verify(() => sdk.setUserId(id: 'user')).called(1); + verify( + () => sdk.setUserProperty(name: 'role', value: 'tester'), + ).called(1); + when( + () => sdk.setAnalyticsCollectionEnabled(any()), + ).thenThrow(StateError('setup')); + await expectLater(client.initialize(), throwsStateError); + }, + ); + + test('null event parameters are removed before SDK submission', () async { + await client.logEvent( + name: 'event', + parameters: {'valid': 1, 'optional': null}, + ); + verify( + () => sdk.logEvent(name: 'event', parameters: {'valid': 1}), + ).called(1); + }); + + test('parameter values are coerced to types Firebase accepts', () async { + await client.logEvent( + name: 'typed', + parameters: { + 'text': 'a', + 'count': 2, + 'ratio': 0.5, + 'flag': true, + 'when': DateTime.utc(2026), + 'list': [1, 2], + 'none': null, + }, + ); + verify( + () => sdk.logEvent( + name: 'typed', + parameters: { + 'text': 'a', + 'count': 2, + 'ratio': 0.5, + 'flag': 'true', + 'when': DateTime.utc(2026).toString(), + 'list': '[1, 2]', + }, + ), + ).called(1); + }); + + test('user identifiers are never written to the log', () async { + await client.initialize(); + await client.setUserId('secret-user'); + when( + () => sdk.setUserId(id: any(named: 'id')), + ).thenThrow(StateError('user')); + await client.setUserId('secret-user'); + final messages = [ + ...verify(() => logger.d(captureAny())).captured, + ...verify(() => logger.e(captureAny(), any(), any())).captured, + ]; + expect(messages.where((m) => '$m'.contains('user')), isNot(isEmpty)); + expect(messages.where((m) => '$m'.contains('secret-user')), isEmpty); + }); + + test('collection changes affect future logging', () async { + await client.setAnalyticsCollectionEnabled(false); + await client.logEvent(name: 'disabled'); + verifyNever(() => sdk.logEvent(name: 'disabled')); + await client.setAnalyticsCollectionEnabled(true); + await client.logEvent(name: 'enabled'); + verify(() => sdk.logEvent(name: 'enabled')).called(1); + }); + + test( + 'semantic events preserve their expected names and parameters', + () async { + await client.logCustomEvent(const AnalyticsEvent(name: 'custom')); + await client.logAppOpen(); + await client.logScreenView(screenName: 'home', screenClass: 'Home'); + await client.logLogin(loginMethod: 'email'); + await client.logSignUp(signUpMethod: 'google'); + await client.logPurchase(currency: 'USD', value: 3.5); + verify( + () => sdk.logEvent(name: 'login', parameters: {'method': 'email'}), + ).called(1); + verify( + () => sdk.logEvent( + name: 'purchase', + parameters: {'currency': 'USD', 'value': 3.5}, + ), + ).called(1); + await client.setUserId(null); + await client.setUserProperty(name: 'role', value: null); + await client.resetAnalyticsData(); + client.dispose(); + }, + ); + + test('SDK event and property failures are contained', () async { + when( + () => sdk.logEvent( + name: any(named: 'name'), + parameters: any(named: 'parameters'), + ), + ).thenThrow(StateError('event')); + when( + () => sdk.setUserId(id: any(named: 'id')), + ).thenThrow(StateError('user')); + when( + () => sdk.setUserProperty( + name: any(named: 'name'), + value: any(named: 'value'), + ), + ).thenThrow(StateError('property')); + when(sdk.resetAnalyticsData).thenThrow(StateError('reset')); + when( + () => sdk.setAnalyticsCollectionEnabled(any()), + ).thenThrow(StateError('collection')); + await client.logEvent(name: 'event'); + await client.setUserId('user'); + await client.setUserProperty(name: 'role', value: 'value'); + await client.resetAnalyticsData(); + await client.setAnalyticsCollectionEnabled(false); + verify(() => logger.e(any(), any(), any())).called(5); + }); + + test( + 'module startup is injectable and helpers resolve fresh clients after reset', + () async { + di.register(logger); + await analytics.init(analytics: sdk); + await AnalyticsHelper.logEvent('before'); + await di.reset(); + di.register(logger); + await analytics.init( + analytics: sdk, + config: const DefaultAnalyticsConfig(enableAnalytics: false), + ); + await AnalyticsHelper.logEvent('after'); + verify(() => sdk.logEvent(name: 'before')).called(1); + verifyNever(() => sdk.logEvent(name: 'after')); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/event_names_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/event_names_test.dart new file mode 100644 index 0000000..909bd47 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/event_names_test.dart @@ -0,0 +1,84 @@ +import 'package:analytics/analytics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('event catalog keeps stable unique names', () { + final events = [ + AnalyticsEvents.user.authenticatedRedirect, + AnalyticsEvents.user.profileUpdated, + AnalyticsEvents.user.preferencesChanged, + AnalyticsEvents.user.onboardingCompleted, + AnalyticsEvents.user.accountDeleted, + AnalyticsEvents.auth.signIn, + AnalyticsEvents.auth.signUp, + AnalyticsEvents.auth.signOut, + AnalyticsEvents.auth.passwordReset, + AnalyticsEvents.auth.failed, + AnalyticsEvents.auth.socialLogin, + AnalyticsEvents.navigation.screenView, + AnalyticsEvents.navigation.tabSwitched, + AnalyticsEvents.navigation.backPressed, + AnalyticsEvents.navigation.deepLinkOpened, + AnalyticsEvents.feature.used, + AnalyticsEvents.feature.tutorialStarted, + AnalyticsEvents.feature.tutorialCompleted, + AnalyticsEvents.feature.feedbackGiven, + AnalyticsEvents.feature.buttonPressed, + AnalyticsEvents.error.appError, + AnalyticsEvents.error.networkError, + AnalyticsEvents.error.crash, + AnalyticsEvents.error.apiError, + AnalyticsEvents.error.validationError, + AnalyticsEvents.app.open, + AnalyticsEvents.app.background, + AnalyticsEvents.app.foreground, + AnalyticsEvents.app.updated, + AnalyticsEvents.app.installed, + AnalyticsEvents.app.uninstalled, + AnalyticsEvents.profile.viewed, + AnalyticsEvents.profile.edited, + AnalyticsEvents.profile.photoUpdated, + AnalyticsEvents.profile.settingsChanged, + AnalyticsEvents.profile.privacyUpdated, + ]; + expect(events, [ + 'user_authenticated_redirect', + 'user_profile_updated', + 'user_preferences_changed', + 'user_onboarding_completed', + 'user_account_deleted', + 'auth_sign_in', + 'auth_sign_up', + 'auth_sign_out', + 'auth_password_reset', + 'auth_failed', + 'auth_social_login', + 'screen_view', + 'navigation_tab_switched', + 'navigation_back_pressed', + 'navigation_deep_link_opened', + 'feature_used', + 'feature_tutorial_started', + 'feature_tutorial_completed', + 'feature_feedback_given', + 'button_pressed', + 'app_error', + 'network_error', + 'app_crash', + 'api_error', + 'validation_error', + 'app_open', + 'app_background', + 'app_foreground', + 'app_updated', + 'app_installed', + 'app_uninstalled', + 'profile_viewed', + 'profile_edited', + 'profile_photo_updated', + 'profile_settings_changed', + 'profile_privacy_updated', + ]); + expect(events.toSet(), hasLength(events.length)); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/helper_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/helper_test.dart new file mode 100644 index 0000000..ed02d54 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/analytics/test/helper_test.dart @@ -0,0 +1,157 @@ +import 'package:analytics/analytics.dart'; +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Client extends Mock implements AnalyticsClient {} + +class _Logger extends Mock implements Logger {} + +void main() { + tearDown(di.reset); + setUpAll(() => registerFallbackValue(const AnalyticsEvent(name: 'fallback'))); + test( + 'all helpers tolerate absent services, forward calls and contain asynchronous failures', + () async { + final logger = _Logger(); + final client = _Client(); + final operations = Function()>[ + () => AnalyticsHelper.logEvent('custom', parameters: {'key': 1}), + () => AnalyticsHelper.logSignIn(method: 'email'), + () => AnalyticsHelper.logSignUp(method: 'email'), + () => AnalyticsHelper.setUserId('user'), + () => AnalyticsHelper.setUserProperty(name: 'role', value: 'tester'), + () => AnalyticsHelper.logAppOpen(), + () => AnalyticsHelper.logCustomEvent( + const AnalyticsEvent(name: 'custom'), + ), + () => AnalyticsHelper.logFeatureUsed( + 'search', + parameters: {'source': 'home'}, + ), + () => AnalyticsHelper.logButtonPressed( + 'submit', + screenName: 'home', + parameters: {'source': 'link'}, + ), + () => AnalyticsHelper.logAppError( + 'validation', + errorMessage: 'invalid', + parameters: {'source': 'link'}, + ), + ]; + for (final operation in operations) { + await operation(); + } + di.register(logger); + di.register(client); + final stubs = [ + () => client.logEvent( + name: any(named: 'name'), + parameters: any(named: 'parameters'), + ), + () => client.logLogin( + loginMethod: any(named: 'loginMethod'), + parameters: any(named: 'parameters'), + ), + () => client.logSignUp( + signUpMethod: any(named: 'signUpMethod'), + parameters: any(named: 'parameters'), + ), + () => client.setUserId(any()), + () => client.setUserProperty( + name: any(named: 'name'), + value: any(named: 'value'), + ), + () => client.logAppOpen(parameters: any(named: 'parameters')), + () => client.logCustomEvent(any()), + ]; + for (final stub in stubs) { + when(stub).thenAnswer((_) async {}); + } + for (final operation in operations) { + await operation(); + } + verify(() => client.logLogin(loginMethod: 'email')).called(1); + verify(() => client.setUserId('user')).called(1); + for (final stub in stubs) { + when(stub).thenAnswer((_) async => throw StateError('offline')); + } + for (final operation in operations) { + await operation(); + } + verify(() => logger.e(any(), any(), any())).called(operations.length); + }, + ); + + test( + 'route observer tracks named pages and catches asynchronous failures', + () async { + final client = _Client(); + final logger = _Logger(); + when( + () => client.logScreenView(screenName: any(named: 'screenName')), + ).thenAnswer((_) async {}); + final observer = AnalyticsRouteObserver(client: client, logger: logger); + final page = MaterialPageRoute( + settings: const RouteSettings(name: '/home'), + builder: (_) => const SizedBox(), + ); + final unnamed = MaterialPageRoute(builder: (_) => const SizedBox()); + observer.didPush(page, null); + observer.didPop(unnamed, page); + observer.didReplace(newRoute: page); + observer.didPush(unnamed, page); + observer.didPop(page, null); + await pumpEventQueue(); + verify(() => client.logScreenView(screenName: '/home')).called(3); + when( + () => client.logScreenView(screenName: any(named: 'screenName')), + ).thenAnswer((_) async => throw StateError('offline')); + observer.didPush(page, null); + await pumpEventQueue(); + verify(() => logger.e(any(), any(), any())).called(1); + page.dispose(); + unnamed.dispose(); + }, + ); + + test('event value equality agrees with hash codes and map serialization', () { + final a = AnalyticsEvent(name: 'event', parameters: {'one': 1, 'two': 2}); + final b = AnalyticsEvent(name: 'event', parameters: {'two': 2, 'one': 1}); + expect(a, b); + expect(a.hashCode, b.hashCode); + expect(a, a); + expect(a.toMap()['name'], 'event'); + expect(a.toString(), contains('event')); + expect(a, isNot(const AnalyticsEvent(name: 'event'))); + expect(const AnalyticsEvent(name: 'event'), isNot(a)); + expect( + a, + isNot(const AnalyticsEvent(name: 'event', parameters: {'one': 1})), + ); + expect( + a, + isNot( + const AnalyticsEvent(name: 'event', parameters: {'one': 1, 'two': 3}), + ), + ); + expect( + const AnalyticsEvent(name: 'empty'), + const AnalyticsEvent(name: 'empty'), + ); + final config = const DefaultAnalyticsConfig(userId: 'user') + .copyWith( + enableAnalytics: false, + enableDebugLogging: true, + defaultUserProperties: {'role': 'test'}, + ) + .copyWith(); + expect(config.enableAnalytics, isFalse); + expect(config.enableDebugLogging, isTrue); + expect(config.userId, 'user'); + expect(config.defaultUserProperties, {'role': 'test'}); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md new file mode 100644 index 0000000..399b47e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md @@ -0,0 +1,76 @@ +# Nonstop Example: `packages/core` + +Cross-cutting foundation (layer 1): the `Logger` contract and its Talker +implementation, build-time `Environment`, shared route/query-key constants, +bloc and route observers, the app-wide event channel, JSON/date converters and +the base `CoreException`. It must not own feature logic, screens, product copy +or anything only one package uses. Its only workspace deps are `di` and `localization`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +Exported from `package:core/core.dart` unless noted. + +| Symbol | Kind | Notes | +|---|---|---| +| `init()` | function | Calls `registerLoggerWithDI()`, sets `di.onDisposeError` to log through the `Logger`, logs "Core module initialized". Called first in app `bootstrap.dart` and in tests via `setUp(core.init)` | +| `Logger` | `abstract interface class` | `d`, `i`, `w`, `e(message, [error, stackTrace])`, `Object get logger` (raw backend) | +| `registerLoggerWithDI()` | function | `di.register(TalkerLoggerImpl(TalkerFlutter.init()))` | +| `TalkerLoggerImpl` | implementation | Not in the barrel; import `package:core/logger/talker_logger_impl.dart` | +| `Environment` | constants | `useEmulators` (`USE_EMULATORS`), `baseUrl` (`BASE_URL`) | +| `CoreRoutes`, `Keys`, `Defaults` | constants | Shell paths, query/extra keys, `defaultPageSize` | +| `CoreRouter` | `abstract interface class` | `List get routes`; feature/package routers `implements` it | +| `CoreBlocObserver`, `CoreRouteObserver` | observers | Optional `logger:`; fall back to `di.get()` | +| `GlobalEventChannel({required maxRecentEvents, Logger? logger})` + `GlobalEventChannelProvider/Builder/Listener/Consumer` | bloc | App-wide events; `context.fire(GlobalEventType)` extension | +| `GlobalEventType`, `FireGlobalEvent`, `GlobalEventState` | events/state | No concrete events ship; subclass `GlobalEventType` | +| `CoreException`, `UserNotFoundException` | errors | Other packages extend `CoreException` (e.g. `NotificationException`) | +| `DateTimeConverter` | formatter | `toViewFormat`, `toViewFormatWithTime`, `toViewFormatTime`; all convert to local time | +| `TimestampConverter`, `TimestampConverterNullable` | converters | Accept ISO string, Firestore `Timestamp`, `{_seconds,_nanoseconds}` | +| `BasicStringExtensions.asBool` | extension | `'true'`/`'1'` (case-insensitive) -> true | +| `emulators.init({host})` | function | `package:core/developer/emulators.dart`, not in the barrel | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/core.dart` | Barrel + `init()` | +| `lib/logger/` | `Logger` contract, `registerLoggerWithDI`, `TalkerLoggerImpl` | +| `lib/constants/` | `Environment`, `CoreRoutes`, `Keys`, `Defaults` | +| `lib/observer/` | `CoreBlocObserver`, `CoreRouteObserver` (logs `push/pop/remove/replace route named X` at debug) | +| `lib/bloc/` | Global event channel bloc, state, events, widgets; `global_event_extension.dart` holds the `fire` extension | +| `lib/errors/exceptions.dart` | `CoreException`, `UserNotFoundException` (message from `strings.errors`) | +| `lib/converters/` | Date display formats and timestamp JSON converters | +| `lib/extensions/basic.dart` | `String?` helpers | +| `lib/router/core_router.dart` | `CoreRouter` contract | +| `lib/developer/emulators.dart` | Points Auth (9099), Firestore (8080), Functions (5001) at the emulator host | + +## Rules + +- `core.init()` is the only registration this package performs (`Logger`); it also routes `di` dispose failures to that logger. Everything else here is stateless or owned by the widget tree. +- `Environment` is the single place `String/bool.fromEnvironment` is called. +- `GlobalEventChannel` is created and closed by `GlobalEventChannelProvider` (a `BlocProvider`). `context.fire` requires that provider above the caller. +- `GlobalEventChannel` falls back to `di.get()` when no `logger:` is passed (as `GlobalEventChannelProvider` does), so `core.init()` must run before it is constructed. +- Observers accept any `Logger`; do not type them against Talker. +- `emulators.init` rethrows setup failures after logging; do not swallow them. Host defaults to `10.0.2.2` on Android, `localhost` elsewhere; ports must match `firebase.json`. +- Keep global events rare (see the doc comment in `bloc/global_event.dart`). + +## Common changes + +- **Add an environment value:** add a `static const` to `Environment` in `lib/constants/environment.dart`, pass it from the app's `bootstrap.dart` into the consuming package's `init(config:)`. Document the `--dart-define` in the root `CLAUDE.md` Run section. +- **Add a global event:** subclass `GlobalEventType` in `lib/bloc/global_event.dart` (override `props` if it carries data); add a case to `test/core_test.dart` asserting `eventCounts` / `current`. +- **Add a shared query key or shell route:** add to `Keys` or `CoreRoutes`. A route used by one feature belongs in that feature's `constants/routes.dart`. +- **Swap the logger backend:** `implements Logger`, register it in place of `TalkerLoggerImpl` in `registerLoggerWithDI`; `packages/developer` falls back to a plain message when `logger` is not a `Talker`. + +## Tests + +`test/core_test.dart` covers: emulator init failing before Firebase init, event equality and `Logger` registration after `init`, DI dispose failures reported through the logger, `context.fire`, bounded history with total counts, provider/builder/listener/consumer, date and `asBool` helpers, timestamp converter shapes and invalid input, every `TalkerLoggerImpl` level, and all observer callbacks with named and unnamed routes. Pattern: `setUp(init)`, `tearDown(di.reset)`; Talker with `useConsoleLogs: false` for log assertions. + +Run: `dart run melos exec --scope=core -- flutter test`. `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `TimestampConverter.fromJson` throws `ArgumentError` on unsupported input; the nullable variant returns `null`. String input is converted `.toLocal()`. +- `CoreRouteObserver` skips routes whose `settings.name` is null. +- `emulators.init` calls `di.get()` first, so `core.init()` must have run. +- `lib/logger/index.dart` exports `TalkerLoggerImpl`, but the `core.dart` barrel exports only `logger/logger.dart`. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/README.md b/packages/nonstop_cli/example/nonstop_example/packages/core/README.md new file mode 100644 index 0000000..cb34437 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/README.md @@ -0,0 +1,18 @@ +# Core + +A Melos-managed project for mono-repo, created using NonStop CLI. + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) + +## Installation 💻 + +**❗ In order to start using Core you must have the [Flutter SDK][flutter_install_link] installed on your machine.** + +Install via `dart pub add`: + +```sh +dart pub add core +``` + +[flutter_install_link]: https://docs.flutter.dev/get-started/install \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event.dart new file mode 100644 index 0000000..7c6937f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event.dart @@ -0,0 +1,22 @@ +import 'package:equatable/equatable.dart'; + +/// Base type for events broadcast on the app-wide event channel. +/// +/// Use this for the handful of things that genuinely cross feature +/// boundaries - "the signed-in user changed", "this list is stale" - and keep +/// everything else inside the feature that owns it. +abstract class GlobalEventType extends Equatable { + const GlobalEventType(); + + @override + List get props => []; +} + +class FireGlobalEvent extends Equatable { + final GlobalEventType eventType; + + const FireGlobalEvent({required this.eventType}); + + @override + List get props => [eventType]; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_bloc.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_bloc.dart new file mode 100644 index 0000000..7fdc933 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_bloc.dart @@ -0,0 +1,42 @@ +import 'package:bloc/bloc.dart'; +import 'package:core/bloc/global_event.dart'; +import 'package:core/bloc/global_event_channel_state.dart'; +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; + +class GlobalEventChannel extends Bloc { + final Logger _logger; + + GlobalEventChannel({required int maxRecentEvents, Logger? logger}) + : _logger = logger ?? di.get(), + super(GlobalEventState(maxRecentEvents: maxRecentEvents)) { + on(_onFireGlobalEvent); + } + + void _onFireGlobalEvent( + FireGlobalEvent event, + Emitter emit, + ) { + _logger.i('GlobalEventChannel: Processing ${event.eventType.runtimeType}'); + + final eventType = event.eventType; + final newHistory = List.from(state.history); + newHistory.insert(0, eventType); + + if (newHistory.length > state.maxRecentEvents) { + newHistory.removeLast(); + } + + final newEventCounts = Map.from(state.eventCounts); + final eventTypeKey = eventType.runtimeType; + newEventCounts[eventTypeKey] = (newEventCounts[eventTypeKey] ?? 0) + 1; + + emit( + state.copyWith( + history: newHistory, + eventCounts: newEventCounts, + current: eventType, + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_provider.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_provider.dart new file mode 100644 index 0000000..eb84614 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_provider.dart @@ -0,0 +1,92 @@ +import 'package:core/bloc/global_event_channel_bloc.dart'; +import 'package:core/bloc/global_event_channel_state.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class GlobalEventChannelProvider extends StatelessWidget { + final Widget child; + final int maxRecentEvents; + final bool lazy; + + const GlobalEventChannelProvider({ + super.key, + required this.child, + this.maxRecentEvents = 50, + this.lazy = true, + }); + + @override + Widget build(BuildContext context) { + return BlocProvider( + lazy: lazy, + create: (context) => GlobalEventChannel(maxRecentEvents: maxRecentEvents), + child: child, + ); + } +} + +class GlobalEventChannelBuilder extends StatelessWidget { + final BlocWidgetBuilder builder; + final BlocBuilderCondition? buildWhen; + + const GlobalEventChannelBuilder({ + super.key, + required this.builder, + this.buildWhen, + }); + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: buildWhen, + builder: builder, + ); + } +} + +class GlobalEventChannelListener extends StatelessWidget { + final Widget child; + final BlocWidgetListener listener; + final BlocListenerCondition? listenWhen; + + const GlobalEventChannelListener({ + super.key, + required this.child, + required this.listener, + this.listenWhen, + }); + + @override + Widget build(BuildContext context) { + return BlocListener( + listenWhen: listenWhen, + listener: listener, + child: child, + ); + } +} + +class GlobalEventChannelConsumer extends StatelessWidget { + final BlocWidgetBuilder builder; + final BlocWidgetListener listener; + final BlocBuilderCondition? buildWhen; + final BlocListenerCondition? listenWhen; + + const GlobalEventChannelConsumer({ + super.key, + required this.builder, + required this.listener, + this.buildWhen, + this.listenWhen, + }); + + @override + Widget build(BuildContext context) { + return BlocConsumer( + buildWhen: buildWhen, + listenWhen: listenWhen, + builder: builder, + listener: listener, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_state.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_state.dart new file mode 100644 index 0000000..50cf330 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_channel_state.dart @@ -0,0 +1,33 @@ +import 'package:core/bloc/global_event.dart'; +import 'package:equatable/equatable.dart'; + +class GlobalEventState extends Equatable { + final List history; + final Map eventCounts; + final GlobalEventType? current; + final int maxRecentEvents; + + const GlobalEventState({ + this.history = const [], + this.eventCounts = const {}, + this.current, + this.maxRecentEvents = 50, + }); + + GlobalEventState copyWith({ + List? history, + Map? eventCounts, + GlobalEventType? current, + int? maxRecentEvents, + }) { + return GlobalEventState( + history: history ?? this.history, + eventCounts: eventCounts ?? this.eventCounts, + current: current ?? this.current, + maxRecentEvents: maxRecentEvents ?? this.maxRecentEvents, + ); + } + + @override + List get props => [history, eventCounts, current, maxRecentEvents]; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_extension.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_extension.dart new file mode 100644 index 0000000..96feec8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/global_event_extension.dart @@ -0,0 +1,12 @@ +import 'package:core/bloc/global_event.dart'; +import 'package:core/bloc/global_event_channel_bloc.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +extension GlobalEventChannelExtension on BuildContext { + /// Fires a global event with the given [eventType]. + void fire(GlobalEventType eventType) { + final bloc = read(); + bloc.add(FireGlobalEvent(eventType: eventType)); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/index.dart new file mode 100644 index 0000000..f7308ca --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/bloc/index.dart @@ -0,0 +1,5 @@ +export 'global_event.dart'; +export 'global_event_channel_bloc.dart'; +export 'global_event_channel_provider.dart'; +export 'global_event_channel_state.dart'; +export 'global_event_extension.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/defaults.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/defaults.dart new file mode 100644 index 0000000..c7961c2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/defaults.dart @@ -0,0 +1,4 @@ +/// App-wide default values. +abstract final class Defaults { + static const int defaultPageSize = 20; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/environment.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/environment.dart new file mode 100644 index 0000000..ebbd718 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/environment.dart @@ -0,0 +1,16 @@ +/// Build-time configuration. +/// +/// Every value is a `--dart-define`, so the same binary can be pointed at a +/// different backend without a code change: +/// +/// ```sh +/// flutter run --dart-define=BASE_URL=https://staging.example.com +/// ``` +abstract final class Environment { + static const bool useEmulators = bool.fromEnvironment('USE_EMULATORS'); + + static const String baseUrl = String.fromEnvironment( + 'BASE_URL', + defaultValue: 'https://api.example.com', + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/index.dart new file mode 100644 index 0000000..4db272b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/index.dart @@ -0,0 +1,4 @@ +export 'defaults.dart'; +export 'environment.dart'; +export 'keys.dart'; +export 'routes.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/keys.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/keys.dart new file mode 100644 index 0000000..dd8685f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/keys.dart @@ -0,0 +1,9 @@ +/// Query-parameter and `extra` keys shared between routers and screens. +/// +/// Keep these here rather than inline so a rename is a single edit. +abstract final class Keys { + static const String email = 'email'; + static const String title = 'title'; + static const String message = 'message'; + static const String error = 'error'; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/routes.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/routes.dart new file mode 100644 index 0000000..03f0293 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/constants/routes.dart @@ -0,0 +1,11 @@ +/// Paths owned by the app shell itself. +/// +/// Feature packages declare their own route constants; these are the ones +/// every app has. +abstract final class CoreRoutes { + static const String root = '/'; + static const String home = '/home'; + static const String dashboard = '/home/dashboard'; + static const String profile = '/home/profile'; + static const String error = '/error'; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/datetime_converter.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/datetime_converter.dart new file mode 100644 index 0000000..62435be --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/datetime_converter.dart @@ -0,0 +1,33 @@ +import 'package:intl/intl.dart'; + +abstract final class DateTimeConverter { + /// Converts a [DateTime] to a [String] in the format 'MMMM d, y'. + /// If the [date] is null, it returns an empty string. + /// + /// Example: + /// ```dart + /// DateTime date = DateTime.now(); + /// String formattedDate = DateTimeConverter.toViewFormat(date); + /// print(formattedDate); // Output: 'October 1, 2023' + /// ``` + static String toViewFormat(DateTime? date) { + if (date == null) return ''; + final dateFormate = DateFormat('MMMM d, y'); + + return dateFormate.format(date.toLocal()); + } + + static String toViewFormatWithTime(DateTime? date) { + if (date == null) return ''; + final dateFormate = DateFormat('MMMM d, y, h:mm a'); + + return dateFormate.format(date.toLocal()); + } + + static String toViewFormatTime(DateTime? date) { + if (date == null) return ''; + final dateFormate = DateFormat('h:mm:ss a'); + + return dateFormate.format(date.toLocal()); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/index.dart new file mode 100644 index 0000000..3162ba8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/index.dart @@ -0,0 +1,2 @@ +export 'datetime_converter.dart'; +export 'timestamp_converter.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/timestamp_converter.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/timestamp_converter.dart new file mode 100644 index 0000000..419c1ae --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/converters/timestamp_converter.dart @@ -0,0 +1,44 @@ +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:json_annotation/json_annotation.dart'; + +/// Accepts the three shapes a timestamp arrives in - ISO string, +/// Firestore [Timestamp], or the `{_seconds, _nanoseconds}` map that +/// Cloud Functions emit - and always writes back UTC ISO-8601. +class TimestampConverter implements JsonConverter { + const TimestampConverter(); + + @override + DateTime fromJson(dynamic json) { + final parsed = _tryParse(json); + if (parsed == null) { + throw ArgumentError('Invalid timestamp format: $json'); + } + return parsed; + } + + @override + String? toJson(DateTime? date) => date?.toUtc().toIso8601String(); +} + +class TimestampConverterNullable implements JsonConverter { + const TimestampConverterNullable(); + + @override + DateTime? fromJson(dynamic json) => _tryParse(json); + + @override + String? toJson(DateTime? date) => date?.toUtc().toIso8601String(); +} + +DateTime? _tryParse(dynamic json) { + if (json is String && json.isNotEmpty) return DateTime.parse(json).toLocal(); + if (json is Timestamp) return json.toDate(); + if (json is Map) { + final seconds = json['_seconds'] as int; + final nanoseconds = json['_nanoseconds'] as int? ?? 0; + return DateTime.fromMillisecondsSinceEpoch( + seconds * 1000 + nanoseconds ~/ 1000000, + ); + } + return null; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/core.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/core.dart new file mode 100644 index 0000000..ebdd25e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/core.dart @@ -0,0 +1,21 @@ +library; + +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; + +export 'bloc/index.dart'; +export 'constants/index.dart'; +export 'converters/index.dart'; +export 'errors/index.dart'; +export 'extensions/index.dart'; +export 'logger/logger.dart'; +export 'observer/index.dart'; +export 'router/core_router.dart'; + +Future init() async { + registerLoggerWithDI(); + final logger = di.get(); + di.onDisposeError = (error, stack) => + logger.e('Failed to dispose a DI registration', error, stack); + logger.i('Core module initialized'); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/developer/emulators.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/developer/emulators.dart new file mode 100644 index 0000000..c3420cf --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/developer/emulators.dart @@ -0,0 +1,28 @@ +import 'package:firebase_auth/firebase_auth.dart'; +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:cloud_functions/cloud_functions.dart'; +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; +import 'package:flutter/foundation.dart'; + +/// Points every Firebase SDK at the local emulator suite. +/// +/// Ports match the defaults in `firebase.json`; change both together. +Future init({String? host}) async { + final logger = di.get(); + final emulatorHost = + host ?? + (!kIsWeb && defaultTargetPlatform == TargetPlatform.android + ? '10.0.2.2' + : 'localhost'); + logger.i('Using Firebase emulators'); + try { + await FirebaseAuth.instance.useAuthEmulator(emulatorHost, 9099); + FirebaseFirestore.instance.useFirestoreEmulator(emulatorHost, 8080); + FirebaseFunctions.instance.useFunctionsEmulator(emulatorHost, 5001); + logger.i('Successfully initialised the Firebase emulators'); + } catch (error, stackTrace) { + logger.e('Failed to initialise the Firebase emulators:', error, stackTrace); + rethrow; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/exceptions.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/exceptions.dart new file mode 100644 index 0000000..704f0bb --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/exceptions.dart @@ -0,0 +1,11 @@ +import 'package:localization/localization.dart'; + +class CoreException implements Exception { + final String message; + + CoreException({required this.message}); +} + +class UserNotFoundException extends CoreException { + UserNotFoundException() : super(message: strings.errors.user_not_found); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/index.dart new file mode 100644 index 0000000..104418b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/errors/index.dart @@ -0,0 +1 @@ +export 'exceptions.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/basic.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/basic.dart new file mode 100644 index 0000000..5d04989 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/basic.dart @@ -0,0 +1,7 @@ +extension BasicStringExtensions on String? { + bool get asBool { + if (this == null) return false; + final lower = this!.toLowerCase(); + return lower == 'true' || lower == '1'; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/index.dart new file mode 100644 index 0000000..0f1b76c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/extensions/index.dart @@ -0,0 +1 @@ +export 'basic.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/index.dart new file mode 100644 index 0000000..b9836dd --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/index.dart @@ -0,0 +1,2 @@ +export 'logger.dart'; +export 'talker_logger_impl.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/logger.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/logger.dart new file mode 100644 index 0000000..dace388 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/logger.dart @@ -0,0 +1,22 @@ +import 'package:core/logger/talker_logger_impl.dart'; +import 'package:di/di.dart'; +import 'package:talker_flutter/talker_flutter.dart'; + +void registerLoggerWithDI() { + final talker = TalkerFlutter.init(); + final logger = TalkerLoggerImpl(talker); + + di.register(logger); +} + +abstract interface class Logger { + Object get logger; + + void d(String message); + + void i(String message); + + void w(String message); + + void e(String message, [Object? error, StackTrace? stackTrace]); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/talker_logger_impl.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/talker_logger_impl.dart new file mode 100644 index 0000000..2db6aee --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/logger/talker_logger_impl.dart @@ -0,0 +1,31 @@ +import 'package:core/logger/logger.dart'; +import 'package:talker_flutter/talker_flutter.dart'; + +class TalkerLoggerImpl implements Logger { + final Talker _talker; + + TalkerLoggerImpl(this._talker); + + @override + void d(String message) { + _talker.debug(message); + } + + @override + void i(String message) { + _talker.info(message); + } + + @override + void w(String message) { + _talker.warning(message); + } + + @override + void e(String message, [Object? error, StackTrace? stackTrace]) { + _talker.error(message, error, stackTrace); + } + + @override + Object get logger => _talker; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_bloc_observer.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_bloc_observer.dart new file mode 100644 index 0000000..695f29e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_bloc_observer.dart @@ -0,0 +1,29 @@ +import 'package:bloc/bloc.dart'; +import 'package:core/core.dart'; +import 'package:di/di.dart'; + +class CoreBlocObserver extends BlocObserver { + final Logger _logger; + + CoreBlocObserver({Logger? logger}) : _logger = logger ?? di.get(); + + @override + void onEvent(Bloc bloc, Object? event) { + super.onEvent(bloc, event); + _logger.d('${bloc.runtimeType}: event ${event.runtimeType}'); + } + + @override + void onTransition(Bloc bloc, Transition transition) { + super.onTransition(bloc, transition); + _logger.d( + '${bloc.runtimeType}: ${transition.currentState.runtimeType} -> ${transition.nextState.runtimeType}', + ); + } + + @override + void onError(BlocBase bloc, Object error, StackTrace stackTrace) { + super.onError(bloc, error, stackTrace); + _logger.e('${bloc.runtimeType}: unhandled error', error, stackTrace); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_route_observer.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_route_observer.dart new file mode 100644 index 0000000..3042cd1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/core_route_observer.dart @@ -0,0 +1,39 @@ +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; + +class CoreRouteObserver extends NavigatorObserver { + CoreRouteObserver({Logger? logger}) : _logger = logger ?? di.get(); + + final Logger _logger; + + void _log(String action, Route? route) { + final name = route?.settings.name; + if (name == null) return; + _logger.d('$action route named $name'); + } + + @override + void didPush(Route route, Route? previousRoute) { + super.didPush(route, previousRoute); + _log('push', route); + } + + @override + void didPop(Route route, Route? previousRoute) { + super.didPop(route, previousRoute); + _log('pop', route); + } + + @override + void didRemove(Route route, Route? previousRoute) { + super.didRemove(route, previousRoute); + _log('remove', route); + } + + @override + void didReplace({Route? newRoute, Route? oldRoute}) { + super.didReplace(newRoute: newRoute, oldRoute: oldRoute); + _log('replace', newRoute); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/index.dart new file mode 100644 index 0000000..a0c67eb --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/observer/index.dart @@ -0,0 +1,2 @@ +export 'core_bloc_observer.dart'; +export 'core_route_observer.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/lib/router/core_router.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/router/core_router.dart new file mode 100644 index 0000000..272be55 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/lib/router/core_router.dart @@ -0,0 +1,5 @@ +import 'package:go_router/go_router.dart'; + +abstract interface class CoreRouter { + List get routes; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/core/pubspec.yaml new file mode 100644 index 0000000..15fcc47 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/pubspec.yaml @@ -0,0 +1,36 @@ +name: core +description: "Cross-cutting foundation for Nonstop Example: logging, DI wiring, routing contracts, error types and BLoC plumbing." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + bloc: ^9.0.0 + equatable: ^2.0.5 + flutter_bloc: ^9.1.1 + go_router: ^18.0.1 + intl: ^0.20.2 + json_annotation: ^4.9.0 + talker_flutter: ^5.1.20 + di: + path: ../di + localization: + path: ../localization + firebase_auth: ^6.7.0 + cloud_firestore: ^6.10.0 + cloud_functions: ^6.5.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/test/core_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/core/test/core_test.dart new file mode 100644 index 0000000..d3c83a0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/test/core_test.dart @@ -0,0 +1,233 @@ +import 'package:core/developer/emulators.dart' as emulators; +import 'package:cloud_firestore/cloud_firestore.dart'; + +import 'package:core/core.dart'; +import 'package:core/logger/talker_logger_impl.dart'; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:talker_flutter/talker_flutter.dart'; + +class _Counter extends Bloc { + _Counter() : super(0) { + on((event, emit) => emit(event)); + } +} + +class _Ping extends GlobalEventType { + const _Ping(); +} + +void main() { + test( + 'emulator setup failures are surfaced before Firebase initialization', + () async { + await expectLater(emulators.init(), throwsA(anything)); + }, + ); + + setUp(init); + tearDown(di.reset); + + test( + 'event base defines value equality and DI exposes its configured container', + () { + final event = _Ping(); + expect(event.props, isEmpty); + expect(event, _Ping()); + expect(di.getIt.isRegistered(), isTrue); + }, + ); + + test('DI dispose failures are reported through the logger', () async { + final talker = di.get().logger as Talker; + di.register(1, dispose: (_) => throw StateError('cleanup')); + await di.reset(); + expect(talker.history.last.exception, isA()); + }); + + testWidgets('context event extension broadcasts to the owned channel', ( + tester, + ) async { + late BuildContext context; + await tester.pumpWidget( + GlobalEventChannelProvider( + child: Builder( + builder: (ctx) { + context = ctx; + return const SizedBox(); + }, + ), + ), + ); + context.fire(const _Ping()); + await tester.pump(); + expect(context.read().state.current, const _Ping()); + }); + + test('event channel bounds history while retaining total counts', () async { + final channel = GlobalEventChannel( + maxRecentEvents: 2, + logger: TalkerLoggerImpl( + Talker(settings: TalkerSettings(useConsoleLogs: false)), + ), + ); + final states = []; + final subscription = channel.stream.listen(states.add); + for (var i = 0; i < 3; i++) { + channel.add(const FireGlobalEvent(eventType: _Ping())); + } + await pumpEventQueue(); + expect(states, hasLength(3)); + expect(channel.state.history, hasLength(2)); + expect(channel.state.eventCounts[_Ping], 3); + expect(channel.state.current, const _Ping()); + expect(channel.state.copyWith(), channel.state); + expect(channel.state.copyWith(maxRecentEvents: 9).maxRecentEvents, 9); + expect(const FireGlobalEvent(eventType: _Ping()).props, [const _Ping()]); + await subscription.cancel(); + await channel.close(); + }); + + testWidgets( + 'provider, builder, listener and consumer share the event channel', + (tester) async { + var listeners = 0; + await tester.pumpWidget( + MaterialApp( + home: GlobalEventChannelProvider( + lazy: false, + child: GlobalEventChannelListener( + listener: (_, state) { + listeners++; + }, + child: GlobalEventChannelConsumer( + listener: (_, state) { + listeners++; + }, + builder: (_, state) => GlobalEventChannelBuilder( + builder: (_, state) => + Text('Events: ${state.history.length}'), + ), + ), + ), + ), + ), + ); + expect(find.text('Events: 0'), findsOneWidget); + BlocProvider.of( + tester.element(find.text('Events: 0')), + ).add(const FireGlobalEvent(eventType: _Ping())); + await tester.pumpAndSettle(); + expect(find.text('Events: 1'), findsOneWidget); + expect(listeners, 2); + await tester.pumpWidget(const SizedBox()); + }, + ); + + test('date and string helpers handle null and valid input', () { + final date = DateTime(2026, 1, 15, 13, 14, 15); + expect(DateTimeConverter.toViewFormat(null), ''); + expect(DateTimeConverter.toViewFormat(date), 'January 15, 2026'); + expect(DateTimeConverter.toViewFormatWithTime(null), ''); + expect( + DateTimeConverter.toViewFormatWithTime(date), + 'January 15, 2026, 1:14 PM', + ); + expect(DateTimeConverter.toViewFormatTime(null), ''); + expect(DateTimeConverter.toViewFormatTime(date), '1:14:15 PM'); + // Every view format renders in local time, whatever zone the value is in. + final utc = date.toUtc(); + expect(DateTimeConverter.toViewFormat(utc), 'January 15, 2026'); + expect( + DateTimeConverter.toViewFormatWithTime(utc), + 'January 15, 2026, 1:14 PM', + ); + expect(DateTimeConverter.toViewFormatTime(utc), '1:14:15 PM'); + expect((null as String?).asBool, isFalse); + for (final value in ['TRUE', 'true', '1']) { + expect(value.asBool, isTrue); + } + expect('false'.asBool, isFalse); + expect(CoreException(message: 'message').message, 'message'); + expect(UserNotFoundException().message, isNotEmpty); + }); + + test( + 'timestamp adapters accept documented forms and reject invalid shapes', + () { + // Exercise runtime construction as well as annotation-style const use. + // ignore: prefer_const_constructors + final converter = TimestampConverter(); + // ignore: prefer_const_constructors + final nullable = TimestampConverterNullable(); + final date = DateTime.utc(2026); + expect(converter.fromJson(date.toIso8601String()).toUtc(), date); + expect(converter.fromJson(Timestamp.fromDate(date)).toUtc(), date); + + expect( + converter.fromJson({ + '_seconds': 1, + '_nanoseconds': 500000000, + }).millisecondsSinceEpoch, + 1500, + ); + expect(converter.toJson(date), date.toIso8601String()); + expect(converter.toJson(null), isNull); + expect(nullable.fromJson(null), isNull); + expect(nullable.toJson(null), isNull); + expect(nullable.toJson(date), date.toIso8601String()); + expect(() => converter.fromJson(null), throwsArgumentError); + }, + ); + + test('logger forwards every level and exposes its adapter', () { + final talker = Talker(settings: TalkerSettings(useConsoleLogs: false)); + final logger = TalkerLoggerImpl(talker); + logger.d('debug'); + logger.i('info'); + logger.w('warning'); + logger.e('error'); + expect(logger.logger, same(talker)); + expect(talker.history, hasLength(4)); + }); + + test( + 'observers support event, transition, error and route lifecycles', + () async { + final bloc = _Counter(); + final observer = CoreBlocObserver(); + observer.onEvent(bloc, 1); + observer.onTransition( + bloc, + const Transition(currentState: 0, event: 1, nextState: 1), + ); + observer.onError(bloc, StateError('test'), StackTrace.current); + final routes = CoreRouteObserver(); + final named = MaterialPageRoute( + builder: (_) => const SizedBox(), + settings: const RouteSettings(name: '/test', arguments: 'arg'), + ); + final unnamed = MaterialPageRoute(builder: (_) => const SizedBox()); + for (final route in [named, unnamed]) { + routes.didPush(route, null); + routes.didPop(route, null); + routes.didRemove(route, null); + routes.didReplace(newRoute: route); + } + routes.didReplace(); + final talker = di.get().logger as Talker; + expect( + talker.history.map((log) => log.message), + containsAll([ + 'push route named /test', + 'pop route named /test', + 'remove route named /test', + 'replace route named /test', + ]), + ); + await bloc.close(); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/CLAUDE.md new file mode 100644 index 0000000..26e479d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/CLAUDE.md @@ -0,0 +1,60 @@ +# Nonstop Example: `packages/crashlytics` + +Owns crash and non-fatal error reporting behind `CrashlyticsClient`: the +Firebase Crashlytics adapter, global Flutter/platform error handlers, custom +keys, user metadata and breadcrumbs. It does not decide consent or what user +data is reported; the app does. Layer 2: depends on `core`, `di`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | +|---|---| +| `CrashlyticsClient` / `FirebaseCrashlyticsClient(config:, logger:, crashlytics:)` | `abstract interface class` / Firebase implementation: `initialize`, `recordError`, `recordFlutterFatalError`, `log`, `setUserIdentifier`, `setUserMetadata`, `setCustomKey(s)`, `isCrashlyticsCollectionEnabled`, `setCrashlyticsCollectionEnabled`, `send`/`delete`/`checkForUnsentReports`, `dispose`; plus `bufferedLogs`, `clearLogBuffer` on the implementation | +| `init({config, crashlytics})`, `registerCrashlyticsWithDI` | Initializes, sends pending reports, then registers `CrashlyticsConfig` and `CrashlyticsClient` (with `dispose`) | +| `CrashlyticsConfig` / `DefaultCrashlyticsConfig` | `enableInDebugMode`, `installGlobalErrorHandlers`, `enableCustomLogs`, `logBufferSize`, `enableUserMetadata`, `customKeys` | +| `UserMetadata` | `userId` (opaque, e.g. auth uid) and `customAttributes` | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/crashlytics.dart` | Barrel, `init`, `registerCrashlyticsWithDI` | +| `lib/src/client/` | Contract and `FirebaseCrashlyticsClient` | +| `lib/src/config/crashlytics_config.dart` | Config with value equality | +| `lib/src/models/` | `UserMetadata` | + +## Rules + +- **Only a fully initialized client is registered.** If `initialize()` or the unsent-report check throws, `registerCrashlyticsWithDI` disposes the client, logs, rethrows, and registers nothing; `init` can be retried. +- **Collection** is `config.enableInDebugMode || kReleaseMode`. Startup `customKeys` are applied before the client counts as initialized. +- **Handler ownership.** `installGlobalErrorHandlers` (default true) installs `FlutterError.onError` and `PlatformDispatcher.instance.onError`. Both record the error as fatal, then call the previous handler. `dispose()` puts the previous handlers back only if ours are still the installed ones. Never set these handlers anywhere else. +- **Failure policy.** After startup every call catches SDK errors and logs them. Before `initialize()`, or after `dispose()`, calls are no-ops (`recordError` logs a warning). +- **Opt-outs.** `enableCustomLogs: false` disables `log`; `enableUserMetadata: false` disables `setUserIdentifier` and `setUserMetadata`. +- **Privacy.** `UserMetadata` carries only an opaque `userId` and non-personal `customAttributes` (sent as custom keys); never put an email or name in either. `setUserIdentifier` does not log the ID, `setCustomKey` logs only the key, and `log` does not echo the message to the app logger. +- **Injected:** `FirebaseCrashlytics` and `Logger`. The breadcrumb buffer (`logBufferSize`, oldest dropped first) is stamped with `DateTime.now()`. + +## Common changes + +- **Add a reporting method:** declare it on `CrashlyticsClient`, implement it in `FirebaseCrashlyticsClient` with the `_isInitialized` guard and try/catch, add the call to `exerciseClient()` in `test/client_test.dart` (runs before init, after init, and with a failing SDK) and stub the SDK in `setUp`. +- **Add a config option:** add the field to `CrashlyticsConfig` and to `copyWith`, `toMap`, `toString`, `==`, `hashCode` and the `DefaultCrashlyticsConfig` constructor. Extend "crash configuration copying..." in `test/models_test.dart`. +- **Attach context to fatal Flutter errors:** use `recordFlutterFatalError(..., context:)`, which writes the context as custom keys first. + +## Tests + +| File | Covers | +|---|---| +| `test/client_test.dart` | Guarded no-ops, idempotent init, buffer trimming, contained SDK failures, retryable init, handler chaining and restore, `init` with and without pending reports, nothing registered on failure | +| `test/models_test.dart` | `UserMetadata`/config equality, hashing, `copyWith`, `toMap` | +| `test/crashlytics_test.dart` | Default and custom construction | + +Doubles: mocktail `FirebaseCrashlytics` (`_Sdk`), `Logger`, `UserMetadata`. Handler tests save and restore the real `FlutterError.onError` / `PlatformDispatcher.instance.onError` in `finally`. + +`dart run melos exec --scope=crashlytics -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- Tests that call `initialize()` with default config install global handlers; construct with `installGlobalErrorHandlers: false` unless the test restores them. +- `init` needs `Logger` in `di`, and runs only when Firebase is ready (see `apps/nonstop_example/lib/bootstrap.dart`), so consumers must handle a missing `CrashlyticsClient`. +- In debug builds collection is off unless `enableInDebugMode` is set; reports will not appear in the console. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/README.md b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/README.md new file mode 100644 index 0000000..0e8978f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/README.md @@ -0,0 +1,64 @@ +# crashlytics + +Crash and non-fatal error reporting for Nonstop Example behind the +`CrashlyticsClient` interface, implemented with Firebase Crashlytics. + +## Initialise + +Firebase must be initialised and a `Logger` registered. + +```dart +import 'package:crashlytics/crashlytics.dart' as crashlytics; + +await crashlytics.init(); +``` + +`init` initialises the client, sends any unsent reports from a previous run, +then registers `CrashlyticsClient` and `CrashlyticsConfig`. If startup fails, +nothing is registered, the error propagates and `init` can be retried. + +## Configure + +| `CrashlyticsConfig` field | Default | Effect | +| --- | --- | --- | +| `enableInDebugMode` | `false` | collect in debug builds (release builds always collect) | +| `installGlobalErrorHandlers` | `true` | report uncaught Flutter and platform errors as fatal; previous handlers still run and are restored on `dispose()` | +| `enableCustomLogs` | `true` | forward `log()` breadcrumbs | +| `logBufferSize` | `100` | breadcrumbs kept locally in `bufferedLogs` | +| `enableUserMetadata` | `true` | allow `setUserIdentifier` / `setUserMetadata` | +| `customKeys` | `{}` | keys set once at startup | + +## Reporting + +```dart +final crash = di.get(); + +await crash.recordError(error, stack); // non-fatal +await crash.recordError(error, stack, fatal: true); // fatal +await crash.recordFlutterFatalError( + error, + stack, + context: {'screen': 'checkout'}, // set as custom keys +); +await crash.log('checkout started'); +await crash.setUserMetadata( + UserMetadata(userId: user.uid, customAttributes: {'plan': 'pro'}), +); +await crash.setCustomKey('build_flavor', 'staging'); +``` + +Also available: `setUserIdentifier`, `setCustomKeys`, +`setCrashlyticsCollectionEnabled`, `isCrashlyticsCollectionEnabled`, +`sendUnsentReports`, `deleteUnsentReports`, `checkForUnsentReports`. + +## Errors + +Calls made before `init` completes are skipped. After that, SDK failures are +logged and contained; reporting never throws. + +## Privacy rules + +- `UserMetadata` carries only an opaque `userId` plus custom attributes; do not + put emails, names or other personal data in either. +- `log()` messages and custom key values are sent to Crashlytics but never + written to the local debug log. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/crashlytics.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/crashlytics.dart new file mode 100644 index 0000000..cd9b48d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/crashlytics.dart @@ -0,0 +1,61 @@ +library; + +import 'package:core/core.dart'; +import 'package:crashlytics/src/client/index.dart'; +import 'package:crashlytics/src/config/index.dart'; +import 'package:di/di.dart'; +import 'package:firebase_crashlytics/firebase_crashlytics.dart'; + +export 'src/client/index.dart'; +export 'src/config/index.dart'; +export 'src/models/index.dart'; + +/// Initialize the crashlytics module with dependency injection +Future init({ + CrashlyticsConfig? config, + FirebaseCrashlytics? crashlytics, +}) async { + await registerCrashlyticsWithDI( + config ?? const DefaultCrashlyticsConfig(), + crashlytics: crashlytics, + ); + final logger = di.get(); + logger.i('Crashlytics module initialized'); +} + +/// Register crashlytics components with DI container +Future registerCrashlyticsWithDI( + CrashlyticsConfig config, { + FirebaseCrashlytics? crashlytics, +}) async { + final logger = di.get(); + + final client = FirebaseCrashlyticsClient( + config: config, + logger: logger, + crashlytics: crashlytics ?? FirebaseCrashlytics.instance, + ); + try { + // Publish only a fully initialized client; failed startup remains retryable. + await client.initialize(); + + // Check if there are any unsent reports + if (await client.checkForUnsentReports()) { + logger.w('There are unsent crash reports.'); + await client.sendUnsentReports(); + } else { + logger.i('No unsent crash reports found.'); + } + + di.register(config); + di.register( + client, + dispose: (client) => client.dispose(), + ); + logger.i('Crashlytics registered with DI container'); + } catch (e, stackTrace) { + client.dispose(); + logger.e('Failed to register crashlytics with DI', e, stackTrace); + rethrow; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/crashlytics_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/crashlytics_client.dart new file mode 100644 index 0000000..409c277 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/crashlytics_client.dart @@ -0,0 +1,54 @@ +import 'package:crashlytics/src/models/user_metadata.dart'; + +abstract interface class CrashlyticsClient { + /// Initialize the crashlytics client + Future initialize(); + + /// Record an error; non-fatal unless [fatal] is true. + Future recordError( + dynamic exception, + StackTrace? stackTrace, { + bool fatal = false, + Iterable information = const [], + }); + + /// Record a fatal Flutter error, first attaching [context] as custom keys. + Future recordFlutterFatalError( + dynamic exception, + StackTrace stackTrace, { + Map? context, + }); + + /// Log a custom message for debugging + Future log(String message); + + /// Set user identifier for crash reports + Future setUserIdentifier(String identifier); + + /// Set the opaque user id and non-personal custom attributes. + Future setUserMetadata(UserMetadata metadata); + + /// Set custom key-value pairs for debugging + Future setCustomKey(String key, dynamic value); + + /// Set custom keys from a map + Future setCustomKeys(Map keys); + + /// Check if crashlytics collection is enabled + bool get isCrashlyticsCollectionEnabled; + + /// Enable or disable crashlytics collection + Future setCrashlyticsCollectionEnabled(bool enabled); + + /// Send any unsent crash reports + Future sendUnsentReports(); + + /// Delete any unsent crash reports + Future deleteUnsentReports(); + + /// Check if there are any unsent crash reports + Future checkForUnsentReports(); + + /// Dispose of resources + void dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/firebase_crashlytics_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/firebase_crashlytics_client.dart new file mode 100644 index 0000000..b6dc8d5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/firebase_crashlytics_client.dart @@ -0,0 +1,296 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:core/core.dart'; +import 'package:crashlytics/src/client/crashlytics_client.dart'; +import 'package:crashlytics/src/config/crashlytics_config.dart'; +import 'package:crashlytics/src/models/user_metadata.dart'; +import 'package:firebase_crashlytics/firebase_crashlytics.dart'; +import 'package:flutter/foundation.dart'; + +class FirebaseCrashlyticsClient implements CrashlyticsClient { + FirebaseCrashlyticsClient({ + required this.config, + required Logger logger, + required FirebaseCrashlytics crashlytics, + }) : _logger = logger, + _crashlytics = crashlytics; + + final CrashlyticsConfig config; + final Logger _logger; + final FirebaseCrashlytics _crashlytics; + final Queue _logBuffer = Queue(); + bool _isInitialized = false; + FlutterExceptionHandler? _previousFlutterHandler; + bool Function(Object, StackTrace)? _previousPlatformHandler; + FlutterExceptionHandler? _flutterHandler; + bool Function(Object, StackTrace)? _platformHandler; + + @override + Future initialize() async { + if (_isInitialized) return; + try { + // Set crashlytics collection enabled based on config + await _crashlytics.setCrashlyticsCollectionEnabled( + config.enableInDebugMode || kReleaseMode, + ); + + // Apply startup metadata before advertising readiness. + for (final entry in config.customKeys.entries) { + await _crashlytics.setCustomKey(entry.key, entry.value); + } + _isInitialized = true; + + // Own the handlers we install and restore them on disposal. + if (config.installGlobalErrorHandlers) { + _previousFlutterHandler = FlutterError.onError; + _previousPlatformHandler = PlatformDispatcher.instance.onError; + _flutterHandler = (errorDetails) { + unawaited( + recordError( + errorDetails.exception, + errorDetails.stack, + fatal: true, + ), + ); + _previousFlutterHandler?.call(errorDetails); + }; + _platformHandler = (error, stack) { + unawaited(recordError(error, stack, fatal: true)); + _previousPlatformHandler?.call(error, stack); + return true; + }; + FlutterError.onError = _flutterHandler; + PlatformDispatcher.instance.onError = _platformHandler; + } + _logger.i('Firebase Crashlytics initialized successfully'); + } catch (e, stackTrace) { + _logger.e('Failed to initialize Firebase Crashlytics', e, stackTrace); + rethrow; + } + } + + @override + Future recordError( + dynamic exception, + StackTrace? stackTrace, { + bool fatal = false, + Iterable information = const [], + }) async { + if (!_isInitialized) { + _logger.w('Crashlytics not initialized, skipping error recording'); + return; + } + + try { + await _crashlytics.recordError( + exception, + stackTrace, + fatal: fatal, + information: information, + ); + + _logger.d('Recorded ${fatal ? 'fatal' : 'non-fatal'} error: $exception'); + } catch (e) { + _logger.e('Failed to record error: $e'); + } + } + + @override + Future recordFlutterFatalError( + dynamic exception, + StackTrace stackTrace, { + Map? context, + }) async { + if (!_isInitialized) { + _logger.w( + 'Crashlytics not initialized, skipping Flutter fatal error recording', + ); + return; + } + + try { + // Set context as custom keys if provided + if (context != null && context.isNotEmpty) { + await setCustomKeys(context); + } + + await _crashlytics.recordError(exception, stackTrace, fatal: true); + + _logger.d('Recorded Flutter fatal error: $exception'); + } catch (e) { + _logger.e('Failed to record Flutter fatal error: $e'); + } + } + + @override + Future log(String message) async { + if (!_isInitialized || !config.enableCustomLogs) { + return; + } + + try { + await _crashlytics.log(message); + + // Add to local buffer for debugging + _logBuffer.add('[${DateTime.now().toIso8601String()}] $message'); + + // Maintain buffer size + while (_logBuffer.length > config.logBufferSize) { + _logBuffer.removeFirst(); + } + } catch (e) { + _logger.e('Failed to log message: $e'); + } + } + + @override + Future setUserIdentifier(String identifier) async { + if (!_isInitialized || !config.enableUserMetadata) { + return; + } + + try { + await _crashlytics.setUserIdentifier(identifier); + _logger.d('User identifier updated'); + } catch (e) { + _logger.e('Failed to set user identifier: $e'); + } + } + + @override + Future setUserMetadata(UserMetadata metadata) async { + if (!_isInitialized || !config.enableUserMetadata) { + return; + } + + try { + if (metadata.userId != null) { + await setUserIdentifier(metadata.userId!); + } + + await setCustomKeys(metadata.customAttributes); + _logger.d('User metadata updated'); + } catch (e) { + _logger.e('Failed to set user metadata: $e'); + } + } + + @override + Future setCustomKey(String key, dynamic value) async { + if (!_isInitialized) { + return; + } + + try { + await _crashlytics.setCustomKey(key, value); + _logger.d('Set custom key: $key'); + } catch (e) { + _logger.e('Failed to set custom key: $e'); + } + } + + @override + Future setCustomKeys(Map keys) async { + if (!_isInitialized || keys.isEmpty) { + return; + } + + try { + for (final entry in keys.entries) { + await _crashlytics.setCustomKey(entry.key, entry.value); + } + _logger.d('Set ${keys.length} custom keys'); + } catch (e) { + _logger.e('Failed to set custom keys: $e'); + } + } + + @override + bool get isCrashlyticsCollectionEnabled { + if (!_isInitialized) return false; + return _crashlytics.isCrashlyticsCollectionEnabled; + } + + @override + Future setCrashlyticsCollectionEnabled(bool enabled) async { + if (!_isInitialized) { + return; + } + + try { + await _crashlytics.setCrashlyticsCollectionEnabled(enabled); + _logger.d('Crashlytics collection ${enabled ? 'enabled' : 'disabled'}'); + } catch (e) { + _logger.e('Failed to set crashlytics collection enabled: $e'); + } + } + + @override + Future sendUnsentReports() async { + if (!_isInitialized) { + return; + } + + try { + await _crashlytics.sendUnsentReports(); + _logger.d('Sent unsent crash reports'); + } catch (e) { + _logger.e('Failed to send unsent reports: $e'); + } + } + + @override + Future deleteUnsentReports() async { + if (!_isInitialized) { + return; + } + + try { + await _crashlytics.deleteUnsentReports(); + _logger.d('Deleted unsent crash reports'); + } catch (e) { + _logger.e('Failed to delete unsent reports: $e'); + } + } + + @override + Future checkForUnsentReports() async { + if (!_isInitialized) { + return false; + } + + try { + final hasUnsent = await _crashlytics.checkForUnsentReports(); + _logger.d('Has unsent reports: $hasUnsent'); + return hasUnsent; + } catch (e) { + _logger.e('Failed to check for unsent reports: $e'); + return false; + } + } + + /// Get buffered log messages for debugging + List get bufferedLogs => _logBuffer.toList(); + + /// Clear the log buffer + void clearLogBuffer() { + _logBuffer.clear(); + _logger.d('Cleared log buffer'); + } + + @override + void dispose() { + if (_flutterHandler != null && + identical(FlutterError.onError, _flutterHandler)) { + FlutterError.onError = _previousFlutterHandler; + } + if (_platformHandler != null && + identical(PlatformDispatcher.instance.onError, _platformHandler)) { + PlatformDispatcher.instance.onError = _previousPlatformHandler; + } + _logBuffer.clear(); + _isInitialized = false; + _logger.d('Firebase Crashlytics client disposed'); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/index.dart new file mode 100644 index 0000000..5d20960 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/client/index.dart @@ -0,0 +1,2 @@ +export 'crashlytics_client.dart'; +export 'firebase_crashlytics_client.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/crashlytics_config.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/crashlytics_config.dart new file mode 100644 index 0000000..9a1b652 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/crashlytics_config.dart @@ -0,0 +1,106 @@ +class CrashlyticsConfig { + const CrashlyticsConfig({ + this.enableInDebugMode = false, + this.installGlobalErrorHandlers = true, + this.enableCustomLogs = true, + this.logBufferSize = 100, + this.enableUserMetadata = true, + this.customKeys = const {}, + }); + + /// Enable crashlytics in debug mode (typically disabled for development) + final bool enableInDebugMode; + + /// Install `FlutterError.onError` and `PlatformDispatcher.onError` handlers + /// that report uncaught errors as fatal (previous handlers still run). + final bool installGlobalErrorHandlers; + + /// Enable custom logging + final bool enableCustomLogs; + + /// Maximum number of log messages to buffer + final int logBufferSize; + + /// Enable user metadata collection + final bool enableUserMetadata; + + /// Default custom keys to set on initialization + final Map customKeys; + + CrashlyticsConfig copyWith({ + bool? enableInDebugMode, + bool? installGlobalErrorHandlers, + bool? enableCustomLogs, + int? logBufferSize, + bool? enableUserMetadata, + Map? customKeys, + }) { + return CrashlyticsConfig( + enableInDebugMode: enableInDebugMode ?? this.enableInDebugMode, + installGlobalErrorHandlers: + installGlobalErrorHandlers ?? this.installGlobalErrorHandlers, + enableCustomLogs: enableCustomLogs ?? this.enableCustomLogs, + logBufferSize: logBufferSize ?? this.logBufferSize, + enableUserMetadata: enableUserMetadata ?? this.enableUserMetadata, + customKeys: customKeys ?? this.customKeys, + ); + } + + Map toMap() { + return { + 'enableInDebugMode': enableInDebugMode, + 'installGlobalErrorHandlers': installGlobalErrorHandlers, + 'enableCustomLogs': enableCustomLogs, + 'logBufferSize': logBufferSize, + 'enableUserMetadata': enableUserMetadata, + 'customKeys': customKeys, + }; + } + + @override + String toString() { + return 'CrashlyticsConfig{enableInDebugMode: $enableInDebugMode, installGlobalErrorHandlers: $installGlobalErrorHandlers, enableCustomLogs: $enableCustomLogs, logBufferSize: $logBufferSize, enableUserMetadata: $enableUserMetadata, customKeys: $customKeys}'; + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is CrashlyticsConfig && + runtimeType == other.runtimeType && + enableInDebugMode == other.enableInDebugMode && + installGlobalErrorHandlers == other.installGlobalErrorHandlers && + enableCustomLogs == other.enableCustomLogs && + logBufferSize == other.logBufferSize && + enableUserMetadata == other.enableUserMetadata && + _mapEquals(customKeys, other.customKeys); + + @override + int get hashCode => + enableInDebugMode.hashCode ^ + installGlobalErrorHandlers.hashCode ^ + enableCustomLogs.hashCode ^ + logBufferSize.hashCode ^ + enableUserMetadata.hashCode ^ + Object.hashAllUnordered( + customKeys.entries.map((entry) => Object.hash(entry.key, entry.value)), + ); + + bool _mapEquals(Map a, Map b) { + if (a.length != b.length) return false; + for (final key in a.keys) { + if (!b.containsKey(key) || a[key] != b[key]) return false; + } + return true; + } +} + +class DefaultCrashlyticsConfig extends CrashlyticsConfig { + const DefaultCrashlyticsConfig({ + super.enableInDebugMode = false, + super.installGlobalErrorHandlers = true, + super.enableCustomLogs = true, + super.logBufferSize = 100, + super.enableUserMetadata = true, + super.customKeys = const {}, + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/index.dart new file mode 100644 index 0000000..2caf5ad --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/config/index.dart @@ -0,0 +1 @@ +export 'crashlytics_config.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/index.dart new file mode 100644 index 0000000..c52a260 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/index.dart @@ -0,0 +1 @@ +export 'user_metadata.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/user_metadata.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/user_metadata.dart new file mode 100644 index 0000000..9300bb8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/lib/src/models/user_metadata.dart @@ -0,0 +1,51 @@ +/// Crash-report user context. [userId] must be an opaque identifier (for +/// example the auth uid), never an email or name; [customAttributes] must not +/// contain personal data either. +class UserMetadata { + const UserMetadata({this.userId, this.customAttributes = const {}}); + + final String? userId; + final Map customAttributes; + + UserMetadata copyWith({ + String? userId, + Map? customAttributes, + }) { + return UserMetadata( + userId: userId ?? this.userId, + customAttributes: customAttributes ?? this.customAttributes, + ); + } + + Map toMap() { + return {'userId': userId, 'customAttributes': customAttributes}; + } + + @override + String toString() { + return 'UserMetadata{userId: $userId, customAttributes: $customAttributes}'; + } + + @override + bool operator ==(Object other) => + identical(this, other) || + other is UserMetadata && + runtimeType == other.runtimeType && + userId == other.userId && + _mapEquals(customAttributes, other.customAttributes); + + @override + int get hashCode => + userId.hashCode ^ + Object.hashAllUnordered( + customAttributes.entries.map((e) => Object.hash(e.key, e.value)), + ); + + bool _mapEquals(Map a, Map b) { + if (a.length != b.length) return false; + for (final key in a.keys) { + if (!b.containsKey(key) || a[key] != b[key]) return false; + } + return true; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/pubspec.yaml new file mode 100644 index 0000000..cd9a41c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/pubspec.yaml @@ -0,0 +1,27 @@ +name: crashlytics +description: "Crash and non-fatal error reporting for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + firebase_crashlytics: ^5.4.0 + core: + path: ../core + di: + path: ../di + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/client_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/client_test.dart new file mode 100644 index 0000000..9178b8f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/client_test.dart @@ -0,0 +1,247 @@ +import 'package:core/core.dart'; +import 'package:crashlytics/crashlytics.dart'; +import 'package:crashlytics/crashlytics.dart' as crash; +import 'package:di/di.dart'; +import 'package:firebase_crashlytics/firebase_crashlytics.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Sdk extends Mock implements FirebaseCrashlytics {} + +class _Logger extends Mock implements Logger {} + +class _Metadata extends Mock implements UserMetadata {} + +void main() { + late _Sdk sdk; + late _Logger logger; + late FirebaseCrashlyticsClient client; + setUp(() { + sdk = _Sdk(); + logger = _Logger(); + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + when(() => sdk.setCustomKey(any(), any())).thenAnswer((_) async {}); + when(() => sdk.setUserIdentifier(any())).thenAnswer((_) async {}); + when(() => sdk.log(any())).thenAnswer((_) async {}); + when( + () => sdk.recordError( + any(), + any(), + fatal: any(named: 'fatal'), + information: any(named: 'information'), + ), + ).thenAnswer((_) async {}); + when(() => sdk.isCrashlyticsCollectionEnabled).thenReturn(true); + when(sdk.checkForUnsentReports).thenAnswer((_) async => false); + when(sdk.sendUnsentReports).thenAnswer((_) async {}); + when(sdk.deleteUnsentReports).thenAnswer((_) async {}); + client = FirebaseCrashlyticsClient( + config: const CrashlyticsConfig( + installGlobalErrorHandlers: false, + logBufferSize: 2, + customKeys: {'build': 'test'}, + ), + logger: logger, + crashlytics: sdk, + ); + }); + tearDown(() async { + client.dispose(); + await di.reset(); + }); + + Future exerciseClient() async { + await client.recordError('error', StackTrace.current); + await client.recordFlutterFatalError( + 'fatal', + StackTrace.current, + context: {'screen': 'home'}, + ); + await client.log('log'); + await client.setUserIdentifier('user'); + await client.setUserMetadata( + const UserMetadata(userId: 'user', customAttributes: {'role': 'tester'}), + ); + await client.setCustomKey('key', 'value'); + await client.setCustomKeys({'key': 'value'}); + await client.setCrashlyticsCollectionEnabled(false); + await client.sendUnsentReports(); + await client.deleteUnsentReports(); + await client.checkForUnsentReports(); + } + + test( + 'invalid metadata is contained and startup SDK errors propagate', + () async { + await client.initialize(); + final metadata = _Metadata(); + when(() => metadata.userId).thenThrow(StateError('invalid metadata')); + await client.setUserMetadata(metadata); + verify(() => logger.e(any())).called(1); + di.register(logger); + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenThrow(StateError('startup')); + await expectLater(crash.init(crashlytics: sdk), throwsStateError); + expect(di.has(), isFalse); + expect(di.has(), isFalse); + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + await crash.init(crashlytics: sdk); + expect(di.has(), isTrue); + }, + ); + + test('before initialization operations safely skip SDK calls', () async { + await exerciseClient(); + expect(client.isCrashlyticsCollectionEnabled, isFalse); + verifyNever(() => sdk.log(any())); + }); + + test( + 'metadata sends only the opaque id and logs never carry values', + () async { + await client.initialize(); + await client.setUserMetadata( + const UserMetadata(userId: 'uid-1', customAttributes: {'plan': 'pro'}), + ); + verify(() => sdk.setUserIdentifier('uid-1')).called(1); + verify(() => sdk.setCustomKey('plan', 'pro')).called(1); + await client.setCustomKey('token', 'secret-value'); + await client.log('secret-message'); + final messages = verify(() => logger.d(captureAny())).captured; + expect(messages.where((m) => '$m'.contains('secret')), isEmpty); + }, + ); + + test('initialization failures log the error and its stack trace', () async { + final failure = StateError('startup'); + when(() => sdk.setCrashlyticsCollectionEnabled(any())).thenThrow(failure); + await expectLater(client.initialize(), throwsStateError); + verify( + () => logger.e( + 'Failed to initialize Firebase Crashlytics', + failure, + any(that: isA()), + ), + ).called(1); + }); + + test('initialization applies custom keys and can be called twice', () async { + await client.initialize(); + await client.initialize(); + verify(() => sdk.setCustomKey('build', 'test')).called(1); + expect(client.isCrashlyticsCollectionEnabled, isTrue); + await exerciseClient(); + await client.log('second'); + await client.log('third'); + expect(client.bufferedLogs, hasLength(2)); + expect(client.bufferedLogs.last, endsWith('third')); + client.clearLogBuffer(); + expect(client.bufferedLogs, isEmpty); + }); + + test('SDK failures are contained after initialization', () async { + await client.initialize(); + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenThrow(StateError('sdk')); + when(() => sdk.setCustomKey(any(), any())).thenThrow(StateError('sdk')); + when(() => sdk.setUserIdentifier(any())).thenThrow(StateError('sdk')); + when(() => sdk.log(any())).thenThrow(StateError('sdk')); + when( + () => sdk.recordError( + any(), + any(), + fatal: any(named: 'fatal'), + information: any(named: 'information'), + ), + ).thenThrow(StateError('sdk')); + when(sdk.checkForUnsentReports).thenThrow(StateError('sdk')); + when(sdk.sendUnsentReports).thenThrow(StateError('sdk')); + when(sdk.deleteUnsentReports).thenThrow(StateError('sdk')); + await exerciseClient(); + expect(await client.checkForUnsentReports(), isFalse); + }); + + test('failed initialization remains retryable', () async { + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenThrow(StateError('sdk')); + await expectLater(client.initialize(), throwsStateError); + expect(client.isCrashlyticsCollectionEnabled, isFalse); + when( + () => sdk.setCrashlyticsCollectionEnabled(any()), + ).thenAnswer((_) async {}); + await client.initialize(); + expect(client.isCrashlyticsCollectionEnabled, isTrue); + }); + + test('global handlers are chained and restored when disposed', () async { + final previousFlutter = FlutterError.onError; + final previousPlatform = PlatformDispatcher.instance.onError; + var flutterCalls = 0; + var platformCalls = 0; + void flutterHandler(FlutterErrorDetails details) { + flutterCalls++; + } + + bool platformHandler(Object error, StackTrace stack) { + platformCalls++; + return true; + } + + FlutterError.onError = flutterHandler; + PlatformDispatcher.instance.onError = platformHandler; + try { + client = FirebaseCrashlyticsClient( + config: const CrashlyticsConfig(), + logger: logger, + crashlytics: sdk, + ); + await client.initialize(); + FlutterError.onError!(FlutterErrorDetails(exception: StateError('test'))); + expect( + PlatformDispatcher.instance.onError!( + StateError('test'), + StackTrace.current, + ), + isTrue, + ); + await pumpEventQueue(); + expect(flutterCalls, 1); + expect(platformCalls, 1); + client.dispose(); + expect(FlutterError.onError, same(flutterHandler)); + expect(PlatformDispatcher.instance.onError, same(platformHandler)); + } finally { + FlutterError.onError = previousFlutter; + PlatformDispatcher.instance.onError = previousPlatform; + } + }); + + for (final hasReports in [false, true]) { + test('module initializes with pending reports=$hasReports', () async { + di.register(logger); + when(sdk.checkForUnsentReports).thenAnswer((_) async => hasReports); + await crash.init( + config: const CrashlyticsConfig(installGlobalErrorHandlers: false), + crashlytics: sdk, + ); + expect(di.has(), isTrue); + if (hasReports) verify(sdk.sendUnsentReports).called(1); + }); + } + + test('equal config values have equal hashes regardless of map order', () { + const first = CrashlyticsConfig(customKeys: {'a': 1, 'b': 2}); + const second = CrashlyticsConfig(customKeys: {'b': 2, 'a': 1}); + expect(first, second); + expect(first.hashCode, second.hashCode); + expect({first, second}, hasLength(1)); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/crashlytics_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/crashlytics_test.dart new file mode 100644 index 0000000..45e300e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/crashlytics_test.dart @@ -0,0 +1,80 @@ +import 'package:crashlytics/crashlytics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Crashlytics', () { + group('CrashlyticsConfig', () { + test('creates default config correctly', () { + const config = DefaultCrashlyticsConfig(); + + expect(config.enableInDebugMode, false); + expect(config.installGlobalErrorHandlers, true); + expect(config.enableCustomLogs, true); + expect(config.logBufferSize, 100); + expect(config.enableUserMetadata, true); + expect(config.customKeys, isEmpty); + }); + + test('creates custom config correctly', () { + const config = CrashlyticsConfig( + enableInDebugMode: true, + installGlobalErrorHandlers: false, + logBufferSize: 50, + customKeys: {'test': 'value'}, + ); + + expect(config.enableInDebugMode, true); + expect(config.installGlobalErrorHandlers, false); + expect(config.logBufferSize, 50); + expect(config.customKeys, {'test': 'value'}); + }); + + test('copyWith works correctly', () { + const config = CrashlyticsConfig(); + final updated = config.copyWith(enableInDebugMode: true); + + expect(updated.enableInDebugMode, true); + expect( + updated.installGlobalErrorHandlers, + config.installGlobalErrorHandlers, + ); + }); + }); + + group('UserMetadata', () { + test('creates user metadata correctly', () { + const metadata = UserMetadata( + userId: 'user123', + customAttributes: {'role': 'admin'}, + ); + + expect(metadata.userId, 'user123'); + expect(metadata.customAttributes, {'role': 'admin'}); + }); + + test('toMap works correctly', () { + const metadata = UserMetadata(userId: 'user123'); + + final map = metadata.toMap(); + expect(map, {'userId': 'user123', 'customAttributes': isEmpty}); + }); + + test('copyWith works correctly', () { + const metadata = UserMetadata(userId: 'user123'); + final updated = metadata.copyWith(customAttributes: {'plan': 'pro'}); + + expect(updated.userId, 'user123'); + expect(updated.customAttributes, {'plan': 'pro'}); + }); + + test('equality works correctly', () { + const metadata1 = UserMetadata(userId: 'user123'); + const metadata2 = UserMetadata(userId: 'user123'); + const metadata3 = UserMetadata(userId: 'user456'); + + expect(metadata1, equals(metadata2)); + expect(metadata1, isNot(equals(metadata3))); + }); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/models_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/models_test.dart new file mode 100644 index 0000000..7056910 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/crashlytics/test/models_test.dart @@ -0,0 +1,43 @@ +import 'package:crashlytics/crashlytics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'user metadata value equality is order-independent and agrees with hashing', + () { + final user = UserMetadata( + userId: 'user', + customAttributes: {'a': 1, 'b': 2}, + ); + final equal = user.copyWith(customAttributes: {'b': 2, 'a': 1}); + expect(user, user); + expect(user, equal); + expect(user.hashCode, equal.hashCode); + expect(user.copyWith(), user); + expect(user.toMap()['userId'], 'user'); + expect(user.toString(), contains('user')); + expect(user, isNot(user.copyWith(customAttributes: {}))); + expect(user, isNot(user.copyWith(customAttributes: {'a': 1, 'b': 3}))); + expect(user, isNot(user.copyWith(userId: 'another'))); + }, + ); + + test('crash configuration copying retains and overrides each option', () { + const config = CrashlyticsConfig(); + final changed = config.copyWith( + enableInDebugMode: true, + installGlobalErrorHandlers: false, + enableCustomLogs: false, + enableUserMetadata: false, + logBufferSize: 10, + customKeys: {'build': 'test'}, + ); + expect(changed.copyWith(), changed); + expect(changed.hashCode, changed.copyWith().hashCode); + expect(changed.toString(), contains('10')); + expect(changed.enableCustomLogs, isFalse); + expect(changed.enableInDebugMode, isTrue); + expect(changed.toMap()['logBufferSize'], 10); + expect(changed, isNot(config)); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/design_system/CLAUDE.md new file mode 100644 index 0000000..fb02bb3 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/CLAUDE.md @@ -0,0 +1,90 @@ +# Nonstop Example: `packages/design_system` + +The visual language of the app: theme, shared components, dialogs, screens, +toasts and loaders. It is product-agnostic: no feature names, no business +logic, no navigation decisions. Layer 3 (see `packages/CLAUDE.md`). + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. **Load the +`design-system` skill** before adding or changing anything here; it holds the +rules for tokens, components and review. + +## Public API + +Everything, including `Toast`, is exported from +`package:design_system/design_system.dart`. + +| Symbol | Kind | Use | +|---|---|---| +| `DesignSystemWrapper` | widget | Wraps `MaterialApp`; picks light/dark from platform brightness, installs `GlobalLoaderOverlay` and `ToastificationWrapper` | +| `DesignSystem` | theme builder | `light()` / `dark()` `ThemeData`; `bodyFont` / `displayFont` (default "Open Sans") | +| `MaterialTheme` | generated | Color schemes (light, dark, contrast variants) | +| `createTextTheme` | generated | Merges Google Fonts body + display text themes | +| `NavigationIcons` | constants | Every navigation icon; one edit re-skins the shell | +| `Toast` | static API | `notification`, `error`, `success`, `warning` | +| `Loader` / `DefaultLoader` | overlay / widget | Blocking overlay; inline adaptive spinner | +| `DefaultErrorView`, `ErrorScreen` | widgets | Inline error with retry; full-screen error with retry/home | +| `NetworkUrlImage`, `AppAssetImage`, `Header` | widgets | Cached network image, raster/SVG asset with fallback, header banner | +| `DateFilterChips` | widget | Week/month filter | +| `AuthHeadersBuilder` | widget | Builds a child with current auth headers | +| `FileInfoDialog` | dialog | `FileInfoDialog.show(context, file)`; tap-to-copy confirms with `Toast.success` | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/design_system.dart` | `DesignSystem`: component theme overrides on top of `MaterialTheme` | +| `lib/generated/` | Material Theme Builder export (`theme.dart`, `util.dart`). Never hand-edit | +| `lib/components/` | Reusable widgets (`app_asset_image.dart`, ...), hand-maintained `index.dart` barrel | +| `lib/screens/`, `lib/dialogs/` | Full screens and dialogs | +| `lib/toast/`, `lib/loader/` | Toast and overlay APIs | +| `lib/wrapper/wrappers.dart` | `DesignSystemWrapper` | +| `lib/constants/navigation_icons.dart` | Navigation icon set | +| `lib/utils/extensions/` | Package-private string helpers | + +## Rules + +- Component styling (buttons, app bar, navigation bar, inputs) is set once in + `DesignSystem._baseTheme`. Change it there, not with per-widget `style:`. +- Colors come from `Theme.of(context).colorScheme` roles; text from + `textTheme`. Components never use raw `Color(...)`; even input borders use + `outlineVariant`. +- Every user-visible string comes from `strings.*` (`localization`). +- Components take everything they render as constructor parameters. They + never call `di.get`, except `AuthHeadersBuilder`, which falls back to the + registered `AuthTokenProvider` / `Logger` when none is passed. +- `network` (`AuthTokenProvider`) and `core` (`Logger`) are imported only by + `AuthHeadersBuilder`. Do not add other imports from them. +- The wrapper owns brightness. The app passes only `theme:` to + `MaterialApp.router`; do not add a separate `darkTheme` there. + +## Common changes + +- **Rebrand the palette:** export from Material Theme Builder, replace + `lib/generated/theme.dart` wholesale, then check both brightnesses. +- **Change fonts:** pass `bodyFont` / `displayFont` to `DesignSystem` in + `DesignSystemWrapper` (any Google Fonts family name). +- **Add a component:** follow the `design-system` skill. Add a file to + `lib/components/`, export it from `components/index.dart`, and test it in + `test/components_test.dart`. +- **Add a toast variant:** add a static method to `Toast` that mirrors the + others, and add it to the toast test in `test/integration_test.dart`. + +## Tests + +| File | Covers | +|---|---| +| `design_system_test.dart` | Wrapper hands the builder a themed context | +| `components_test.dart` | Theme building, loaders, error view/screen, asset fallbacks, network image, wrapper brightness + loader, string helpers | +| `integration_test.dart` | Image adapters, `AuthHeadersBuilder` (missing provider, failures, rebuilds), dialogs, toast variants | + +Run `dart run melos exec --scope=design_system -- flutter test`. Keep +`dart run melos run coverage` at 100%. + +## Gotchas + +- Google Fonts are fetched at runtime. For offline-first or production builds, + bundle the font files as assets and set + `GoogleFonts.config.allowRuntimeFetching = false`. +- `FileInfoDialog` takes a `dart:io` `File`, so it does not work on web. Its + labels ("File Information", "File Name", ...) are still raw English + literals, not `strings.*`. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/README.md b/packages/nonstop_cli/example/nonstop_example/packages/design_system/README.md new file mode 100644 index 0000000..47e41eb --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/README.md @@ -0,0 +1,18 @@ +# Design System + +A Melos-managed project for mono-repo, created using NonStop CLI. + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) + +## Installation 💻 + +**❗ In order to start using Design System you must have the [Flutter SDK][flutter_install_link] installed on your machine.** + +Install via `dart pub add`: + +```sh +dart pub add design_system +``` + +[flutter_install_link]: https://docs.flutter.dev/get-started/install \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/app_asset_image.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/app_asset_image.dart new file mode 100644 index 0000000..4eef9f4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/app_asset_image.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_svg/svg.dart'; + +class AppAssetImage extends StatelessWidget { + final String assetPath; + final double? width; + final double? height; + final BoxFit boxFit; + final String? package; + + const AppAssetImage({ + super.key, + required this.assetPath, + this.width, + this.height, + this.boxFit = BoxFit.cover, + this.package, + }); + @override + Widget build(BuildContext context) { + // if asset is svg, use SvgPicture.asset + if (assetPath.endsWith('.svg')) { + return SvgPicture.asset( + assetPath, + width: width, + height: height, + fit: boxFit, + package: package, + errorBuilder: (context, error, stackTrace) { + return Icon( + Icons.image, + size: 32, + color: Theme.of(context).colorScheme.onSurface, + ); + }, + ); + } + + // otherwise, use Image.asset + return Image.asset( + assetPath, + width: width, + height: height, + fit: boxFit, + package: package, + errorBuilder: (context, error, stackTrace) { + return Icon( + Icons.image, + size: 32, + color: Theme.of(context).colorScheme.onSurface, + ); + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/auth_headers_builder.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/auth_headers_builder.dart new file mode 100644 index 0000000..f859ced --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/auth_headers_builder.dart @@ -0,0 +1,91 @@ +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:flutter/material.dart'; +import 'package:network/network.dart'; + +/// Supplies bearer headers without starting a new refresh on every rebuild. +/// Inject a provider in tests; the composition-root registration is the default. +/// Use a new key when the signed-in identity changes. +class AuthHeadersBuilder extends StatefulWidget { + const AuthHeadersBuilder({ + super.key, + required this.builder, + this.validateToken = false, + this.provider, + this.logger, + }); + + final Widget Function(BuildContext context, Map headers) + builder; + final bool validateToken; + final AuthTokenProvider? provider; + final Logger? logger; + + @override + State createState() => _AuthHeadersBuilderState(); +} + +class _AuthHeadersBuilderState extends State { + Future>? _headers; + + AuthTokenProvider? get _provider => + widget.provider ?? + (di.has() ? di.get() : null); + + @override + void initState() { + super.initState(); + _refresh(); + } + + @override + void didUpdateWidget(covariant AuthHeadersBuilder oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.provider != widget.provider || + oldWidget.validateToken != widget.validateToken) { + _refresh(); + } + } + + void _refresh() { + _headers = widget.validateToken ? _load() : null; + } + + Map _fromToken(String? token) => + token == null || token.isEmpty ? {} : {'Authorization': 'Bearer $token'}; + + void _log(Object error, StackTrace stack) { + final logger = + widget.logger ?? (di.has() ? di.get() : null); + logger?.e('Unable to obtain image authentication headers', error, stack); + } + + Future> _load() async { + try { + return _fromToken(await _provider?.getValidToken()); + } catch (error, stack) { + _log(error, stack); + return {}; + } + } + + @override + Widget build(BuildContext context) { + if (!widget.validateToken) { + Map headers; + try { + headers = _fromToken(_provider?.getCurrentToken()); + } catch (error, stack) { + _log(error, stack); + headers = {}; + } + return widget.builder(context, headers); + } + return FutureBuilder>( + key: ValueKey(_headers), + future: _headers, + builder: (context, snapshot) => + widget.builder(context, snapshot.data ?? {}), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/date_filter_chips.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/date_filter_chips.dart new file mode 100644 index 0000000..0932cc1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/date_filter_chips.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +enum DateFilterType { + week, + month; + + String get displayName { + switch (this) { + case DateFilterType.week: + return strings.common.week; + case DateFilterType.month: + return strings.common.month; + } + } +} + +class DateFilterChips extends StatelessWidget { + final DateFilterType selectedFilter; + final ValueChanged onFilterChanged; + + const DateFilterChips({ + super.key, + required this.selectedFilter, + required this.onFilterChanged, + }); + + @override + Widget build(BuildContext context) { + final colorScheme = Theme.of(context).colorScheme; + + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: DateFilterType.values.map((filter) { + final isSelected = filter == selectedFilter; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: FilterChip( + label: Text(filter.displayName), + selected: isSelected, + onSelected: (selected) { + if (selected) { + onFilterChanged(filter); + } + }, + backgroundColor: colorScheme.surface, + selectedColor: colorScheme.primary, + checkmarkColor: colorScheme.onPrimary, + labelStyle: TextStyle( + color: isSelected ? colorScheme.onPrimary : colorScheme.onSurface, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide( + color: isSelected + ? colorScheme.primary + : colorScheme.outline.withValues(alpha: 0.5), + width: isSelected ? 1.5 : 1, + ), + ), + ), + ); + }).toList(), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/default_error_view.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/default_error_view.dart new file mode 100644 index 0000000..718e1b6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/default_error_view.dart @@ -0,0 +1,127 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +class DefaultErrorView extends StatelessWidget { + const DefaultErrorView({ + super.key, + this.error, + this.stackTrace, + this.onRetry, + this.descriptionBuilder, + this.padding, + }); + + final Object? error; + final StackTrace? stackTrace; + final VoidCallback? onRetry; + final String? Function(Object?)? descriptionBuilder; + final EdgeInsetsGeometry? padding; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textTheme = theme.textTheme; + + final title = strings.errors.default_error_message; + final description = descriptionBuilder?.call(error); + + return SafeArea( + child: Padding( + padding: padding ?? const EdgeInsets.all(40.0), + child: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + color: colorScheme.errorContainer.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: colorScheme.error.withValues(alpha: 0.2), + width: 1, + ), + ), + child: Icon( + Icons.error_outline_rounded, + size: 40, + color: colorScheme.error, + ), + ), + const SizedBox(height: 24), + Text( + title, + style: textTheme.titleMedium?.copyWith( + color: colorScheme.onSurface, + ), + textAlign: TextAlign.center, + maxLines: 5, + overflow: TextOverflow.ellipsis, + ), + if (description != null) ...[ + const SizedBox(height: 8), + Text( + description, + style: textTheme.labelMedium?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + maxLines: 20, + overflow: TextOverflow.ellipsis, + ), + ], + if (error != null && kDebugMode) ...[ + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: colorScheme.outline.withValues(alpha: 0.3), + width: 1, + ), + ), + child: SelectableText( + 'type:${error.runtimeType}:\n$error\n${stackTrace?.toString() ?? ''}', + style: textTheme.bodySmall?.copyWith( + color: colorScheme.onSurface, + fontFamily: 'monospace', + fontSize: 12, + ), + textAlign: TextAlign.left, + maxLines: 10, + ), + ), + ], + const SizedBox(height: 32), + Wrap( + spacing: 12, + runSpacing: 8, + alignment: WrapAlignment.center, + children: [ + if (onRetry != null) + OutlinedButton( + onPressed: onRetry, + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 24, + vertical: 12, + ), + minimumSize: const Size(88, 44), + ), + child: Text(strings.generic.try_again), + ), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/header.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/header.dart new file mode 100644 index 0000000..a37ab86 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/header.dart @@ -0,0 +1,47 @@ +import 'package:design_system/components/app_asset_image.dart'; +import 'package:design_system/components/network_url_image.dart'; +import 'package:design_system/utils/index.dart'; +import 'package:flutter/material.dart'; + +enum HeaderType { + image, + asset; + + double get ratio => switch (this) { + HeaderType.image => 4 / 1, + HeaderType.asset => 1 / 1, + }; +} + +class Header extends StatelessWidget { + const Header({ + super.key, + this.type = HeaderType.image, + this.assetPath, + this.imageUrl, + }); + + final HeaderType type; + final String? assetPath; + final String? imageUrl; + + @override + Widget build(BuildContext context) { + return AspectRatio(aspectRatio: type.ratio, child: _buildImage(context)); + } + + Widget _buildImage(BuildContext context) { + switch (type) { + case HeaderType.asset: + if (assetPath == null || assetPath!.isEmpty) { + return const Icon(Icons.image); + } + return Hero( + tag: assetPath!, + child: AppAssetImage(assetPath: assetPath!, boxFit: BoxFit.contain), + ); + case HeaderType.image: + return NetworkUrlImage(url: imageUrl.asEmptyIfNull); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/index.dart new file mode 100644 index 0000000..1ffaa67 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/index.dart @@ -0,0 +1,7 @@ +export 'app_asset_image.dart'; +export 'auth_headers_builder.dart'; +export 'date_filter_chips.dart'; +export 'default_error_view.dart'; +export 'header.dart'; +export 'loaders.dart'; +export 'network_url_image.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/loaders.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/loaders.dart new file mode 100644 index 0000000..b215488 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/loaders.dart @@ -0,0 +1,18 @@ +import 'package:flutter/material.dart'; + +class DefaultLoader extends StatelessWidget { + const DefaultLoader({super.key, this.size = 20}); + + final double size; + + @override + Widget build(BuildContext context) { + return Center( + child: SizedBox( + width: size, + height: size, + child: CircularProgressIndicator.adaptive(strokeWidth: 4), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/network_url_image.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/network_url_image.dart new file mode 100644 index 0000000..d5a798b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/components/network_url_image.dart @@ -0,0 +1,45 @@ +import 'dart:math'; + +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; + +class NetworkUrlImage extends StatelessWidget { + final String url; + final double? width; + final double? height; + final BoxFit? boxFit; + + const NetworkUrlImage({ + super.key, + required this.url, + this.width, + this.height, + this.boxFit = BoxFit.cover, + }); + + @override + Widget build(final BuildContext context) => CachedNetworkImage( + imageUrl: url, + placeholder: (final context, final _) { + final theme = Theme.of(context); + + return Container( + color: theme.colorScheme.surface, + width: width, + height: height, + child: Icon( + Icons.image, + size: min(width ?? 32, height ?? 32), + color: theme.cardColor, + ), + ); + }, + width: width, + height: height, + fit: boxFit, + fadeOutDuration: const Duration(), + fadeInDuration: const Duration(), + errorWidget: (final context, final url, final error) => + Icon(Icons.image, size: 32), + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/constants/navigation_icons.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/constants/navigation_icons.dart new file mode 100644 index 0000000..b94aba3 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/constants/navigation_icons.dart @@ -0,0 +1,24 @@ +import 'package:flutter/material.dart'; + +/// Icons used by the app's primary navigation. +/// +/// Swap these for your product's icon set - every navigation surface reads +/// from here so a single edit re-skins the whole shell. +abstract final class NavigationIcons { + static const IconData home = Icons.home_outlined; + static const IconData homeSelected = Icons.home; + + static const IconData explore = Icons.explore_outlined; + static const IconData exploreSelected = Icons.explore; + + static const IconData dashboard = Icons.dashboard_outlined; + static const IconData dashboardSelected = Icons.dashboard; + + static const IconData insights = Icons.trending_up_outlined; + static const IconData insightsSelected = Icons.trending_up; + + static const IconData profile = Icons.person_outline; + static const IconData profileSelected = Icons.person; + + static const IconData settings = Icons.settings_outlined; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/design_system.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/design_system.dart new file mode 100644 index 0000000..aeaed38 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/design_system.dart @@ -0,0 +1,139 @@ +import 'package:design_system/generated/theme.dart'; +import 'package:design_system/generated/util.dart'; +import 'package:flutter/material.dart'; + +export 'components/index.dart'; +export 'constants/navigation_icons.dart'; +export 'dialogs/index.dart'; +export 'generated/theme.dart'; +export 'generated/util.dart'; +export 'loader/loader.dart'; +export 'screens/index.dart'; +export 'toast/toasts.dart'; +export 'wrapper/wrappers.dart'; + +class DesignSystem { + final MaterialTheme theme; + + DesignSystem( + BuildContext context, { + String bodyFont = "Open Sans", + String displayFont = "Open Sans", + }) : theme = buildTheme( + context, + bodyFont: bodyFont, + displayFont: displayFont, + ); + + static MaterialTheme buildTheme( + BuildContext context, { + String bodyFont = "Open Sans", + String displayFont = "Open Sans", + }) { + final textTheme = createTextTheme(context, bodyFont, displayFont); + return MaterialTheme(textTheme); + } + + ThemeData _baseTheme({required bool isDark}) { + final base = isDark ? theme.dark() : theme.light(); + return base.copyWith( + inputDecorationTheme: base.inputDecorationTheme.copyWith( + border: UnderlineInputBorder( + borderSide: BorderSide(color: base.colorScheme.outlineVariant), + ), + hintStyle: base.textTheme.labelSmall?.copyWith( + color: base.colorScheme.onSurface.withValues(alpha: 0.6), + ), + labelStyle: base.textTheme.labelMedium?.copyWith( + color: base.colorScheme.onSurface.withValues(alpha: 0.6), + ), + ), + appBarTheme: AppBarTheme( + backgroundColor: base.colorScheme.surface, + surfaceTintColor: base.colorScheme.surfaceTint, + foregroundColor: base.colorScheme.onSurface, + elevation: 0, + centerTitle: true, + titleTextStyle: base.textTheme.titleLarge?.copyWith( + color: base.colorScheme.onSurface, + fontWeight: FontWeight.w600, + ), + iconTheme: IconThemeData(color: base.colorScheme.onSurface), + actionsIconTheme: IconThemeData(color: base.colorScheme.onSurface), + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: base.colorScheme.surface, + surfaceTintColor: Colors.transparent, + elevation: 0, + height: 70, + labelBehavior: NavigationDestinationLabelBehavior.alwaysShow, + labelTextStyle: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.selected)) { + return base.textTheme.labelSmall?.copyWith( + color: base.colorScheme.onSurface, + fontWeight: FontWeight.w600, + fontSize: 12, + ); + } + return base.textTheme.labelSmall?.copyWith( + color: base.colorScheme.onSurfaceVariant, + fontWeight: FontWeight.w500, + fontSize: 12, + ); + }), + iconTheme: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.selected)) { + return IconThemeData(color: base.colorScheme.onPrimary, size: 20); + } + return IconThemeData( + color: base.colorScheme.onSurfaceVariant, + size: 20, + ); + }), + indicatorColor: base.colorScheme.primary, + indicatorShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4)), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + textStyle: base.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: base.colorScheme.primary, + textStyle: base.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + ), + ), + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + textStyle: base.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: base.colorScheme.primary, + textStyle: base.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + side: BorderSide(color: base.colorScheme.primary, width: 1.5), + ), + ), + ); + } + + ThemeData light() => _baseTheme(isDark: false); + + ThemeData dark() => _baseTheme(isDark: true); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/file_info_dialog.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/file_info_dialog.dart new file mode 100644 index 0000000..8c6c5cb --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/file_info_dialog.dart @@ -0,0 +1,259 @@ +import 'dart:io'; + +import 'package:design_system/toast/toasts.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class FileInfoDialog extends StatelessWidget { + final File file; + + const FileInfoDialog({super.key, required this.file}); + + static Future show(BuildContext context, File file) { + return showDialog( + context: context, + builder: (context) => FileInfoDialog(file: file), + ); + } + + String _getFileType(String extension) { + switch (extension.toLowerCase()) { + case 'jpg': + case 'jpeg': + return 'JPEG Image'; + case 'png': + return 'PNG Image'; + case 'gif': + return 'GIF Image'; + case 'webp': + return 'WebP Image'; + case 'bmp': + return 'BMP Image'; + case 'tiff': + case 'tif': + return 'TIFF Image'; + case 'heic': + case 'heif': + return 'HEIF Image'; + default: + return 'Image File'; + } + } + + String _formatFileSize(int bytes) { + if (bytes < 1024) return '$bytes B'; + if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB'; + return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + } + + Widget _buildInfoRow({ + required IconData icon, + required String label, + required String value, + required ColorScheme colorScheme, + required TextTheme textTheme, + bool isPath = false, + VoidCallback? onTap, + }) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 18, color: colorScheme.onSurfaceVariant), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: textTheme.bodySmall?.copyWith( + color: colorScheme.onSurfaceVariant, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 4), + SelectableText( + value, + style: textTheme.bodyMedium?.copyWith( + color: colorScheme.onSurface, + fontFamily: isPath ? 'monospace' : null, + ), + ), + ], + ), + ), + if (onTap != null) + Icon( + Icons.copy, + size: 16, + color: colorScheme.onSurfaceVariant.withValues(alpha: 0.7), + ), + ], + ), + ), + ); + } + + void _copyToClipboard(BuildContext context, String value, String label) { + Clipboard.setData(ClipboardData(text: value)); + Toast.success(context, message: '$label copied to clipboard'); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textTheme = theme.textTheme; + + // Get file info + final fileStat = file.statSync(); + final fileSize = fileStat.size; + final fileName = file.path.split('/').last; + final fileExtension = fileName.split('.').last.toLowerCase(); + final fileType = _getFileType(fileExtension); + + return Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + child: Container( + constraints: const BoxConstraints(maxWidth: 400, maxHeight: 600), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Header + Container( + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + color: colorScheme.primaryContainer, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(16), + ), + ), + child: Row( + children: [ + Icon( + Icons.info_outline, + color: colorScheme.onPrimaryContainer, + ), + const SizedBox(width: 12), + Expanded( + child: Text( + 'File Information', + style: textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w600, + color: colorScheme.onPrimaryContainer, + ), + ), + ), + IconButton( + onPressed: () => Navigator.of(context).pop(), + icon: Icon( + Icons.close, + color: colorScheme.onPrimaryContainer, + ), + ), + ], + ), + ), + + // Content + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: Column( + children: [ + _buildInfoRow( + icon: Icons.image_outlined, + label: 'File Name', + value: fileName, + colorScheme: colorScheme, + textTheme: textTheme, + onTap: () => + _copyToClipboard(context, fileName, 'File name'), + ), + _buildInfoRow( + icon: Icons.category_outlined, + label: 'File Type', + value: fileType, + colorScheme: colorScheme, + textTheme: textTheme, + onTap: () => + _copyToClipboard(context, fileType, 'File type'), + ), + _buildInfoRow( + icon: Icons.extension_outlined, + label: 'File Extension', + value: '.$fileExtension', + colorScheme: colorScheme, + textTheme: textTheme, + onTap: () => _copyToClipboard( + context, + '.$fileExtension', + 'File extension', + ), + ), + _buildInfoRow( + icon: Icons.storage_outlined, + label: 'File Size', + value: _formatFileSize(fileSize), + colorScheme: colorScheme, + textTheme: textTheme, + onTap: () => _copyToClipboard( + context, + _formatFileSize(fileSize), + 'File size', + ), + ), + _buildInfoRow( + icon: Icons.folder_outlined, + label: 'File Path', + value: file.path, + colorScheme: colorScheme, + textTheme: textTheme, + isPath: true, + onTap: () => + _copyToClipboard(context, file.path, 'File path'), + ), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHighest.withValues( + alpha: 0.5, + ), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Icon( + Icons.touch_app, + size: 16, + color: colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Tap any field to copy to clipboard', + style: textTheme.bodySmall?.copyWith( + color: colorScheme.onSurfaceVariant, + fontStyle: FontStyle.italic, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/index.dart new file mode 100644 index 0000000..df0904f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/dialogs/index.dart @@ -0,0 +1 @@ +export 'file_info_dialog.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/theme.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/theme.dart new file mode 100644 index 0000000..33d3a0f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/theme.dart @@ -0,0 +1,386 @@ +import "package:flutter/material.dart"; + +class MaterialTheme { + final TextTheme textTheme; + + const MaterialTheme(this.textTheme); + + static ColorScheme lightScheme() { + return const ColorScheme( + brightness: Brightness.light, + primary: Color(0xff446732), + surfaceTint: Color(0xff446732), + onPrimary: Color(0xffffffff), + primaryContainer: Color(0xffc5efab), + onPrimaryContainer: Color(0xff2d4f1c), + secondary: Color(0xff55624c), + onSecondary: Color(0xffffffff), + secondaryContainer: Color(0xffd9e7cb), + onSecondaryContainer: Color(0xff3e4a35), + tertiary: Color(0xff386666), + onTertiary: Color(0xffffffff), + tertiaryContainer: Color(0xffbbebec), + onTertiaryContainer: Color(0xff1e4e4e), + error: Color(0xffba1a1a), + onError: Color(0xffffffff), + errorContainer: Color(0xffffdad6), + onErrorContainer: Color(0xff93000a), + surface: Color(0xfff8faf0), + onSurface: Color(0xff191d16), + onSurfaceVariant: Color(0xff43483e), + outline: Color(0xff74796d), + outlineVariant: Color(0xffc3c8bb), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xff2e312b), + inversePrimary: Color(0xffaad291), + primaryFixed: Color(0xffc5efab), + onPrimaryFixed: Color(0xff072100), + primaryFixedDim: Color(0xffaad291), + onPrimaryFixedVariant: Color(0xff2d4f1c), + secondaryFixed: Color(0xffd9e7cb), + onSecondaryFixed: Color(0xff131f0d), + secondaryFixedDim: Color(0xffbdcbb0), + onSecondaryFixedVariant: Color(0xff3e4a35), + tertiaryFixed: Color(0xffbbebec), + onTertiaryFixed: Color(0xff002020), + tertiaryFixedDim: Color(0xffa0cfcf), + onTertiaryFixedVariant: Color(0xff1e4e4e), + surfaceDim: Color(0xffd9dbd1), + surfaceBright: Color(0xfff8faf0), + surfaceContainerLowest: Color(0xffffffff), + surfaceContainerLow: Color(0xfff2f5ea), + surfaceContainer: Color(0xffedefe5), + surfaceContainerHigh: Color(0xffe7e9df), + surfaceContainerHighest: Color(0xffe1e4d9), + ); + } + + ThemeData light() { + return theme(lightScheme()); + } + + static ColorScheme lightMediumContrastScheme() { + return const ColorScheme( + brightness: Brightness.light, + primary: Color(0xff1d3e0c), + surfaceTint: Color(0xff446732), + onPrimary: Color(0xffffffff), + primaryContainer: Color(0xff53773f), + onPrimaryContainer: Color(0xffffffff), + secondary: Color(0xff2d3a26), + onSecondary: Color(0xffffffff), + secondaryContainer: Color(0xff64715a), + onSecondaryContainer: Color(0xffffffff), + tertiary: Color(0xff073d3e), + onTertiary: Color(0xffffffff), + tertiaryContainer: Color(0xff477575), + onTertiaryContainer: Color(0xffffffff), + error: Color(0xff740006), + onError: Color(0xffffffff), + errorContainer: Color(0xffcf2c27), + onErrorContainer: Color(0xffffffff), + surface: Color(0xfff8faf0), + onSurface: Color(0xff0f120c), + onSurfaceVariant: Color(0xff33382e), + outline: Color(0xff4f544a), + outlineVariant: Color(0xff6a6f64), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xff2e312b), + inversePrimary: Color(0xffaad291), + primaryFixed: Color(0xff53773f), + onPrimaryFixed: Color(0xffffffff), + primaryFixedDim: Color(0xff3b5d29), + onPrimaryFixedVariant: Color(0xffffffff), + secondaryFixed: Color(0xff64715a), + onSecondaryFixed: Color(0xffffffff), + secondaryFixedDim: Color(0xff4c5943), + onSecondaryFixedVariant: Color(0xffffffff), + tertiaryFixed: Color(0xff477575), + onTertiaryFixed: Color(0xffffffff), + tertiaryFixedDim: Color(0xff2e5c5d), + onTertiaryFixedVariant: Color(0xffffffff), + surfaceDim: Color(0xffc5c8be), + surfaceBright: Color(0xfff8faf0), + surfaceContainerLowest: Color(0xffffffff), + surfaceContainerLow: Color(0xfff2f5ea), + surfaceContainer: Color(0xffe7e9df), + surfaceContainerHigh: Color(0xffdbded4), + surfaceContainerHighest: Color(0xffd0d3c9), + ); + } + + ThemeData lightMediumContrast() { + return theme(lightMediumContrastScheme()); + } + + static ColorScheme lightHighContrastScheme() { + return const ColorScheme( + brightness: Brightness.light, + primary: Color(0xff133304), + surfaceTint: Color(0xff446732), + onPrimary: Color(0xffffffff), + primaryContainer: Color(0xff30511e), + onPrimaryContainer: Color(0xffffffff), + secondary: Color(0xff242f1c), + onSecondary: Color(0xffffffff), + secondaryContainer: Color(0xff404d38), + onSecondaryContainer: Color(0xffffffff), + tertiary: Color(0xff003233), + onTertiary: Color(0xffffffff), + tertiaryContainer: Color(0xff215051), + onTertiaryContainer: Color(0xffffffff), + error: Color(0xff600004), + onError: Color(0xffffffff), + errorContainer: Color(0xff98000a), + onErrorContainer: Color(0xffffffff), + surface: Color(0xfff8faf0), + onSurface: Color(0xff000000), + onSurfaceVariant: Color(0xff000000), + outline: Color(0xff292e25), + outlineVariant: Color(0xff464b41), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xff2e312b), + inversePrimary: Color(0xffaad291), + primaryFixed: Color(0xff30511e), + onPrimaryFixed: Color(0xffffffff), + primaryFixedDim: Color(0xff1a3a09), + onPrimaryFixedVariant: Color(0xffffffff), + secondaryFixed: Color(0xff404d38), + onSecondaryFixed: Color(0xffffffff), + secondaryFixedDim: Color(0xff2a3622), + onSecondaryFixedVariant: Color(0xffffffff), + tertiaryFixed: Color(0xff215051), + onTertiaryFixed: Color(0xffffffff), + tertiaryFixedDim: Color(0xff02393a), + onTertiaryFixedVariant: Color(0xffffffff), + surfaceDim: Color(0xffb7bab0), + surfaceBright: Color(0xfff8faf0), + surfaceContainerLowest: Color(0xffffffff), + surfaceContainerLow: Color(0xfff0f2e7), + surfaceContainer: Color(0xffe1e4d9), + surfaceContainerHigh: Color(0xffd3d5cb), + surfaceContainerHighest: Color(0xffc5c8be), + ); + } + + ThemeData lightHighContrast() { + return theme(lightHighContrastScheme()); + } + + static ColorScheme darkScheme() { + return const ColorScheme( + brightness: Brightness.dark, + primary: Color(0xffaad291), + surfaceTint: Color(0xffaad291), + onPrimary: Color(0xff173807), + primaryContainer: Color(0xff2d4f1c), + onPrimaryContainer: Color(0xffc5efab), + secondary: Color(0xffbdcbb0), + onSecondary: Color(0xff283420), + secondaryContainer: Color(0xff3e4a35), + onSecondaryContainer: Color(0xffd9e7cb), + tertiary: Color(0xffa0cfcf), + onTertiary: Color(0xff003738), + tertiaryContainer: Color(0xff1e4e4e), + onTertiaryContainer: Color(0xffbbebec), + error: Color(0xffffb4ab), + onError: Color(0xff690005), + errorContainer: Color(0xff93000a), + onErrorContainer: Color(0xffffdad6), + surface: Color(0xff11140e), + onSurface: Color(0xffe1e4d9), + onSurfaceVariant: Color(0xffc3c8bb), + outline: Color(0xff8d9286), + outlineVariant: Color(0xff43483e), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xffe1e4d9), + inversePrimary: Color(0xff446732), + primaryFixed: Color(0xffc5efab), + onPrimaryFixed: Color(0xff072100), + primaryFixedDim: Color(0xffaad291), + onPrimaryFixedVariant: Color(0xff2d4f1c), + secondaryFixed: Color(0xffd9e7cb), + onSecondaryFixed: Color(0xff131f0d), + secondaryFixedDim: Color(0xffbdcbb0), + onSecondaryFixedVariant: Color(0xff3e4a35), + tertiaryFixed: Color(0xffbbebec), + onTertiaryFixed: Color(0xff002020), + tertiaryFixedDim: Color(0xffa0cfcf), + onTertiaryFixedVariant: Color(0xff1e4e4e), + surfaceDim: Color(0xff11140e), + surfaceBright: Color(0xff373a33), + surfaceContainerLowest: Color(0xff0c0f09), + surfaceContainerLow: Color(0xff191d16), + surfaceContainer: Color(0xff1d211a), + surfaceContainerHigh: Color(0xff282b24), + surfaceContainerHighest: Color(0xff32362f), + ); + } + + ThemeData dark() { + return theme(darkScheme()); + } + + static ColorScheme darkMediumContrastScheme() { + return const ColorScheme( + brightness: Brightness.dark, + primary: Color(0xffbfe8a5), + surfaceTint: Color(0xffaad291), + onPrimary: Color(0xff0c2c00), + primaryContainer: Color(0xff759b5f), + onPrimaryContainer: Color(0xff000000), + secondary: Color(0xffd2e1c5), + onSecondary: Color(0xff1d2916), + secondaryContainer: Color(0xff87957c), + onSecondaryContainer: Color(0xff000000), + tertiary: Color(0xffb5e5e5), + onTertiary: Color(0xff002b2c), + tertiaryContainer: Color(0xff6b9999), + onTertiaryContainer: Color(0xff000000), + error: Color(0xffffd2cc), + onError: Color(0xff540003), + errorContainer: Color(0xffff5449), + onErrorContainer: Color(0xff000000), + surface: Color(0xff11140e), + onSurface: Color(0xffffffff), + onSurfaceVariant: Color(0xffd9ded0), + outline: Color(0xffafb4a7), + outlineVariant: Color(0xff8d9286), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xffe1e4d9), + inversePrimary: Color(0xff2f501d), + primaryFixed: Color(0xffc5efab), + onPrimaryFixed: Color(0xff041500), + primaryFixedDim: Color(0xffaad291), + onPrimaryFixedVariant: Color(0xff1d3e0c), + secondaryFixed: Color(0xffd9e7cb), + onSecondaryFixed: Color(0xff091405), + secondaryFixedDim: Color(0xffbdcbb0), + onSecondaryFixedVariant: Color(0xff2d3a26), + tertiaryFixed: Color(0xffbbebec), + onTertiaryFixed: Color(0xff001415), + tertiaryFixedDim: Color(0xffa0cfcf), + onTertiaryFixedVariant: Color(0xff073d3e), + surfaceDim: Color(0xff11140e), + surfaceBright: Color(0xff42463e), + surfaceContainerLowest: Color(0xff060804), + surfaceContainerLow: Color(0xff1b1f18), + surfaceContainer: Color(0xff262922), + surfaceContainerHigh: Color(0xff30342d), + surfaceContainerHighest: Color(0xff3b3f38), + ); + } + + ThemeData darkMediumContrast() { + return theme(darkMediumContrastScheme()); + } + + static ColorScheme darkHighContrastScheme() { + return const ColorScheme( + brightness: Brightness.dark, + primary: Color(0xffd2fcb7), + surfaceTint: Color(0xffaad291), + onPrimary: Color(0xff000000), + primaryContainer: Color(0xffa6ce8d), + onPrimaryContainer: Color(0xff020e00), + secondary: Color(0xffe6f5d8), + onSecondary: Color(0xff000000), + secondaryContainer: Color(0xffb9c7ac), + onSecondaryContainer: Color(0xff040e02), + tertiary: Color(0xffc9f9f9), + onTertiary: Color(0xff000000), + tertiaryContainer: Color(0xff9ccbcb), + onTertiaryContainer: Color(0xff000e0e), + error: Color(0xffffece9), + onError: Color(0xff000000), + errorContainer: Color(0xffffaea4), + onErrorContainer: Color(0xff220001), + surface: Color(0xff11140e), + onSurface: Color(0xffffffff), + onSurfaceVariant: Color(0xffffffff), + outline: Color(0xffedf2e4), + outlineVariant: Color(0xffbfc4b7), + shadow: Color(0xff000000), + scrim: Color(0xff000000), + inverseSurface: Color(0xffe1e4d9), + inversePrimary: Color(0xff2f501d), + primaryFixed: Color(0xffc5efab), + onPrimaryFixed: Color(0xff000000), + primaryFixedDim: Color(0xffaad291), + onPrimaryFixedVariant: Color(0xff041500), + secondaryFixed: Color(0xffd9e7cb), + onSecondaryFixed: Color(0xff000000), + secondaryFixedDim: Color(0xffbdcbb0), + onSecondaryFixedVariant: Color(0xff091405), + tertiaryFixed: Color(0xffbbebec), + onTertiaryFixed: Color(0xff000000), + tertiaryFixedDim: Color(0xffa0cfcf), + onTertiaryFixedVariant: Color(0xff001415), + surfaceDim: Color(0xff11140e), + surfaceBright: Color(0xff4e514a), + surfaceContainerLowest: Color(0xff000000), + surfaceContainerLow: Color(0xff1d211a), + surfaceContainer: Color(0xff2e312b), + surfaceContainerHigh: Color(0xff393c35), + surfaceContainerHighest: Color(0xff444840), + ); + } + + ThemeData darkHighContrast() { + return theme(darkHighContrastScheme()); + } + + ThemeData theme(ColorScheme colorScheme) => ThemeData( + useMaterial3: true, + brightness: colorScheme.brightness, + colorScheme: colorScheme, + textTheme: textTheme.apply( + bodyColor: colorScheme.onSurface, + displayColor: colorScheme.onSurface, + ), + scaffoldBackgroundColor: colorScheme.surface, + canvasColor: colorScheme.surface, + ); + + List get extendedColors => []; +} + +class ExtendedColor { + final Color seed, value; + final ColorFamily light; + final ColorFamily lightHighContrast; + final ColorFamily lightMediumContrast; + final ColorFamily dark; + final ColorFamily darkHighContrast; + final ColorFamily darkMediumContrast; + + const ExtendedColor({ + required this.seed, + required this.value, + required this.light, + required this.lightHighContrast, + required this.lightMediumContrast, + required this.dark, + required this.darkHighContrast, + required this.darkMediumContrast, + }); +} + +class ColorFamily { + const ColorFamily({ + required this.color, + required this.onColor, + required this.colorContainer, + required this.onColorContainer, + }); + + final Color color; + final Color onColor; + final Color colorContainer; + final Color onColorContainer; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/util.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/util.dart new file mode 100644 index 0000000..10a2d84 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/generated/util.dart @@ -0,0 +1,27 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +TextTheme createTextTheme( + BuildContext context, + String bodyFontString, + String displayFontString, +) { + TextTheme baseTextTheme = Theme.of(context).textTheme; + TextTheme bodyTextTheme = GoogleFonts.getTextTheme( + bodyFontString, + baseTextTheme, + ); + TextTheme displayTextTheme = GoogleFonts.getTextTheme( + displayFontString, + baseTextTheme, + ); + TextTheme textTheme = displayTextTheme.copyWith( + bodyLarge: bodyTextTheme.bodyLarge, + bodyMedium: bodyTextTheme.bodyMedium, + bodySmall: bodyTextTheme.bodySmall, + labelLarge: bodyTextTheme.labelLarge, + labelMedium: bodyTextTheme.labelMedium, + labelSmall: bodyTextTheme.labelSmall, + ); + return textTheme; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/loader/loader.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/loader/loader.dart new file mode 100644 index 0000000..3e75782 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/loader/loader.dart @@ -0,0 +1,15 @@ +import 'package:design_system/components/index.dart'; +import 'package:flutter/material.dart'; +import 'package:loader_overlay/loader_overlay.dart'; + +class Loader { + static void show(BuildContext context) { + context.loaderOverlay.show( + widgetBuilder: (_) => const Center(child: DefaultLoader()), + ); + } + + static void hide(BuildContext context) { + context.loaderOverlay.hide(); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/error_screen.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/error_screen.dart new file mode 100644 index 0000000..25c9f79 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/error_screen.dart @@ -0,0 +1,152 @@ +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +class ErrorScreen extends StatelessWidget { + const ErrorScreen({ + super.key, + this.title, + this.message, + this.onRetry, + this.onGoHome, + this.error, + }); + + final String? title; + final String? message; + final VoidCallback? onRetry; + final VoidCallback? onGoHome; + final String? error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final textTheme = theme.textTheme; + + final resolvedTitle = title ?? strings.errors.default_error_message; + final resolvedMessage = message ?? strings.errors.default_error_description; + + return Scaffold( + backgroundColor: colorScheme.surface, + appBar: AppBar( + backgroundColor: colorScheme.surface, + foregroundColor: colorScheme.onSurface, + elevation: 0, + surfaceTintColor: colorScheme.surfaceTint, + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Center( + child: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + color: colorScheme.errorContainer.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: colorScheme.error.withValues(alpha: 0.2), + width: 1, + ), + ), + child: Icon( + Icons.error_outline_rounded, + size: 40, + color: colorScheme.error, + ), + ), + const SizedBox(height: 24), + Text( + resolvedTitle, + style: textTheme.titleLarge?.copyWith( + color: colorScheme.onSurface, + fontWeight: FontWeight.w600, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + Text( + resolvedMessage, + style: textTheme.bodyMedium?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + if (error != null) ...[ + const SizedBox(height: 16), + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: colorScheme.outline.withValues(alpha: 0.3), + width: 1, + ), + ), + child: SelectableText( + error!, + style: textTheme.bodySmall?.copyWith( + color: colorScheme.onSurface, + fontFamily: 'monospace', + fontSize: 12, + ), + textAlign: TextAlign.left, + maxLines: 4, + ), + ), + ], + const SizedBox(height: 32), + Wrap( + spacing: 12, + runSpacing: 8, + alignment: WrapAlignment.center, + children: [ + if (onRetry != null) + FilledButton( + onPressed: onRetry, + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 24, + vertical: 12, + ), + minimumSize: const Size(88, 44), + ), + child: Text(strings.generic.try_again), + ), + if (onGoHome != null) + OutlinedButton( + onPressed: onGoHome, + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 24, + vertical: 12, + ), + minimumSize: const Size(88, 44), + side: BorderSide( + color: colorScheme.outline, + width: 1, + ), + ), + child: Text(strings.generic.retry), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/index.dart new file mode 100644 index 0000000..807a6de --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/screens/index.dart @@ -0,0 +1 @@ +export 'error_screen.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/toast/toasts.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/toast/toasts.dart new file mode 100644 index 0000000..3e06134 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/toast/toasts.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; +import 'package:iconsax_flutter/iconsax_flutter.dart'; +import 'package:toastification/toastification.dart'; + +class Toast { + static void notification({required String title, required String body}) => + toastification.show( + type: ToastificationType.info, + style: ToastificationStyle.fillColored, + title: Text(title), + description: Text(body), + alignment: Alignment.topCenter, + autoCloseDuration: const Duration(seconds: 3, milliseconds: 500), + animationBuilder: (context, animation, alignment, child) { + return ScaleTransition(scale: animation, child: child); + }, + icon: Icon(Iconsax.notification), + borderRadius: BorderRadius.circular(12.0), + showProgressBar: true, + dragToClose: true, + applyBlurEffect: true, + ); + + static void error( + BuildContext context, { + required String message, + String? description, + }) => toastification.show( + context: context, + type: ToastificationType.error, + style: ToastificationStyle.fillColored, + title: Text(message), + description: description != null ? Text(description) : null, + alignment: Alignment.topCenter, + autoCloseDuration: const Duration(seconds: 3, milliseconds: 500), + animationBuilder: (context, animation, alignment, child) { + return ScaleTransition(scale: animation, child: child); + }, + icon: Icon(Iconsax.warning_2), + borderRadius: BorderRadius.circular(12.0), + showProgressBar: true, + dragToClose: true, + applyBlurEffect: true, + ); + + static void success( + BuildContext context, { + required String message, + String? description, + }) => toastification.show( + context: context, + type: ToastificationType.success, + style: ToastificationStyle.fillColored, + title: Text(message), + description: description != null ? Text(description) : null, + alignment: Alignment.topCenter, + autoCloseDuration: const Duration(seconds: 3, milliseconds: 500), + animationBuilder: (context, animation, alignment, child) { + return ScaleTransition(scale: animation, child: child); + }, + icon: Icon(Iconsax.tick_circle), + borderRadius: BorderRadius.circular(12.0), + showProgressBar: true, + dragToClose: true, + applyBlurEffect: true, + ); + + static void warning( + BuildContext context, { + required String message, + String? description, + }) => toastification.show( + context: context, + type: ToastificationType.warning, + style: ToastificationStyle.fillColored, + title: Text(message), + description: description != null ? Text(description) : null, + alignment: Alignment.topCenter, + autoCloseDuration: const Duration(seconds: 3, milliseconds: 500), + animationBuilder: (context, animation, alignment, child) { + return ScaleTransition(scale: animation, child: child); + }, + icon: Icon(Iconsax.danger), + borderRadius: BorderRadius.circular(12.0), + showProgressBar: true, + dragToClose: true, + applyBlurEffect: true, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/index.dart new file mode 100644 index 0000000..33b3d66 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/index.dart @@ -0,0 +1 @@ +export 'string.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/string.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/string.dart new file mode 100644 index 0000000..c68c177 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/extensions/string.dart @@ -0,0 +1,33 @@ +/// String extensions for common utility operations +extension StringExtensions on String? { + /// Returns true if the string is not null and not empty + /// + /// Example: + /// ```dart + /// String? text = "Hello"; + /// print(text.isNotNullAndNotEmpty); // true + /// + /// String? emptyText = ""; + /// print(emptyText.isNotNullAndNotEmpty); // false + /// + /// String? nullText = null; + /// print(nullText.isNotNullAndNotEmpty); // false + /// ``` + bool get isNotNullAndNotEmpty { + return this != null && this!.isNotEmpty; + } + + /// Returns an empty string if the string is null, otherwise returns the string itself + /// + /// Example: + /// ```dart + /// String? text = "Hello"; + /// print(text.asEmptyIfNull); // "Hello" + /// + /// String? nullText = null; + /// print(nullText.asEmptyIfNull); // "" + /// ``` + String get asEmptyIfNull { + return this ?? ''; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/index.dart new file mode 100644 index 0000000..49893a1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/utils/index.dart @@ -0,0 +1 @@ +export 'extensions/index.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/wrapper/wrappers.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/wrapper/wrappers.dart new file mode 100644 index 0000000..1a08c02 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/lib/wrapper/wrappers.dart @@ -0,0 +1,54 @@ +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:loader_overlay/loader_overlay.dart'; +import 'package:toastification/toastification.dart'; + +class DesignSystemWrapper extends StatefulWidget { + const DesignSystemWrapper({super.key, required this.builder}); + + final Widget Function(BuildContext context, ThemeData theme) builder; + + @override + State createState() => _DesignSystemWrapperState(); +} + +class _DesignSystemWrapperState extends State + with WidgetsBindingObserver { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangePlatformBrightness() { + setState(() {}); + } + + @override + Widget build(BuildContext context) { + final brightness = MediaQuery.platformBrightnessOf(context); + final materialTheme = DesignSystem(context); + final theme = brightness != Brightness.dark + ? materialTheme.light() + : materialTheme.dark(); + + return Theme( + data: theme, + child: GlobalLoaderOverlay( + overlayColor: theme.colorScheme.surface.withValues(alpha: 0.8), + duration: const Duration(milliseconds: 300), + reverseDuration: const Duration(milliseconds: 200), + switchInCurve: Curves.easeInOut, + switchOutCurve: Curves.easeInOut, + child: ToastificationWrapper(child: widget.builder(context, theme)), + ), + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/design_system/pubspec.yaml new file mode 100644 index 0000000..a3585df --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/pubspec.yaml @@ -0,0 +1,36 @@ +name: design_system +description: "Theme, components and dialogs shared across Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + cached_network_image: ^4.0.0 + flutter_svg: ^2.2.0 + google_fonts: ^8.2.1 + iconsax_flutter: ^1.0.1 + loader_overlay: ^5.0.0 + toastification: ^3.0.3 + core: + path: ../core + di: + path: ../di + localization: + path: ../localization + network: + path: ../network + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/components_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/components_test.dart new file mode 100644 index 0000000..0386456 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/components_test.dart @@ -0,0 +1,209 @@ +import 'package:design_system/design_system.dart' as ds; +import 'package:design_system/utils/extensions/string.dart'; +import 'package:design_system/generated/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:localization/localization.dart'; + +void main() { + test( + 'extended palettes retain custom color families for each contrast mode', + () { + final family = ColorFamily( + color: Colors.red, + onColor: Colors.white, + colorContainer: Colors.pink, + onColorContainer: Colors.black, + ); + final extended = ExtendedColor( + seed: Colors.red, + value: Colors.pink, + light: family, + lightHighContrast: family, + lightMediumContrast: family, + dark: family, + darkHighContrast: family, + darkMediumContrast: family, + ); + expect(extended.seed, Colors.red); + expect(extended.light.color, Colors.red); + expect(extended.dark.onColorContainer, Colors.black); + }, + ); + testWidgets( + 'date filters select another period without deselecting the current one', + (tester) async { + final changes = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ds.DateFilterChips( + selectedFilter: ds.DateFilterType.week, + onFilterChanged: changes.add, + ), + ), + ), + ); + await tester.tap(find.text(strings.common.week)); + expect(changes, isEmpty); + await tester.tap(find.text(strings.common.month)); + expect(changes, [ds.DateFilterType.month]); + }, + ); + + testWidgets('error view explains failures and exposes retry', (tester) async { + var retries = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ds.DefaultErrorView( + error: StateError('failure'), + stackTrace: StackTrace.current, + descriptionBuilder: (_) => 'Try another connection', + onRetry: () { + retries++; + }, + ), + ), + ), + ); + expect(find.text('Try another connection'), findsOneWidget); + await tester.tap(find.text(strings.generic.try_again)); + expect(retries, 1); + }); + + testWidgets('error screen provides retry and home actions', (tester) async { + var retries = 0; + var homes = 0; + await tester.pumpWidget( + MaterialApp( + home: ds.ErrorScreen( + title: 'Unavailable', + message: 'Try later', + error: 'Details', + onRetry: () { + retries++; + }, + onGoHome: () { + homes++; + }, + ), + ), + ); + expect(find.text('Unavailable'), findsOneWidget); + await tester.tap(find.byType(FilledButton)); + await tester.tap(find.byType(OutlinedButton)); + expect(retries, 1); + expect(homes, 1); + }); + + for (final extension in ['png', 'svg']) { + testWidgets('missing $extension assets render a fallback', (tester) async { + await tester.pumpWidget( + MaterialApp(home: ds.AppAssetImage(assetPath: 'missing.$extension')), + ); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 100)), + ); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.image), findsOneWidget); + }); + } + + testWidgets( + 'all theme variants expose appropriate brightness and selected styles', + (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) { + final design = ds.DesignSystem(context); + for (final theme in [design.light(), design.dark()]) { + expect( + theme.navigationBarTheme.iconTheme!.resolve({ + WidgetState.selected, + })!.size, + 20, + ); + expect( + theme.navigationBarTheme.iconTheme!.resolve({})!.size, + 20, + ); + expect( + theme.navigationBarTheme.labelTextStyle!.resolve({ + WidgetState.selected, + })!.fontWeight, + FontWeight.w600, + ); + expect( + theme.navigationBarTheme.labelTextStyle! + .resolve({})! + .fontWeight, + FontWeight.w500, + ); + } + final palette = design.theme; + for (final theme in [ + palette.light(), + palette.lightMediumContrast(), + palette.lightHighContrast(), + ]) { + expect(theme.brightness, Brightness.light); + } + for (final theme in [ + palette.dark(), + palette.darkMediumContrast(), + palette.darkHighContrast(), + ]) { + expect(theme.brightness, Brightness.dark); + } + expect(palette.extendedColors, isEmpty); + return const SizedBox(); + }, + ), + ), + ); + }, + ); + + testWidgets('wrapper changes brightness and supports loader show and hide', ( + tester, + ) async { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.light; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + late BuildContext loaderContext; + await tester.pumpWidget( + ds.DesignSystemWrapper( + builder: (_, theme) => MaterialApp( + theme: theme, + home: Builder( + builder: (context) { + loaderContext = context; + return Scaffold(body: Text(theme.brightness.name)); + }, + ), + ), + ), + ); + expect(find.text('light'), findsOneWidget); + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + await tester.pumpAndSettle(); + expect(find.text('dark'), findsOneWidget); + ds.Loader.show(loaderContext); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(ds.DefaultLoader), findsOneWidget); + ds.Loader.hide(loaderContext); + await tester.pumpAndSettle(); + expect(find.byType(ds.DefaultLoader), findsNothing); + }); + + test('nullable string helpers preserve nonempty text', () { + expect((null as String?).asEmptyIfNull, ''); + expect('text'.asEmptyIfNull, 'text'); + expect((null as String?).isNotNullAndNotEmpty, isFalse); + expect(''.isNotNullAndNotEmpty, isFalse); + expect('text'.isNotNullAndNotEmpty, isTrue); + expect(ds.HeaderType.image.ratio, 4); + expect(ds.HeaderType.asset.ratio, 1); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/design_system_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/design_system_test.dart new file mode 100644 index 0000000..8cd1ae7 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/design_system_test.dart @@ -0,0 +1,25 @@ +import 'package:design_system/design_system.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('DesignSystemWrapper hands the builder a themed context', ( + tester, + ) async { + late ThemeData built; + + await tester.pumpWidget( + MaterialApp( + home: DesignSystemWrapper( + builder: (context, theme) { + built = theme; + return const SizedBox.shrink(); + }, + ), + ), + ); + + expect(built.useMaterial3, isTrue); + expect(built.colorScheme.primary, isNot(Colors.transparent)); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/integration_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/integration_test.dart new file mode 100644 index 0000000..2346e52 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/design_system/test/integration_test.dart @@ -0,0 +1,237 @@ +import 'dart:io'; + +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:core/core.dart'; + +import 'package:design_system/design_system.dart' as ds; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:network/network.dart'; + +import 'package:toastification/toastification.dart'; + +class _File extends Mock implements File {} + +class _Stat extends Mock implements FileStat {} + +class _Tokens extends Mock implements AuthTokenProvider {} + +class _Logger extends Mock implements Logger {} + +void main() { + testWidgets( + 'file dialog renders supported metadata sizes and copies each field', + (tester) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + for (final (extension, label, size, expectedSize) in [ + ('jpg', 'JPEG Image', 20, '20 B'), + ('png', 'PNG Image', 1024, '1.0 KB'), + ('gif', 'GIF Image', 1048576, '1.0 MB'), + ('webp', 'WebP Image', 0, '0 B'), + ('bmp', 'BMP Image', 0, '0 B'), + ('tiff', 'TIFF Image', 0, '0 B'), + ('heic', 'HEIF Image', 0, '0 B'), + ('unknown', 'Image File', 0, '0 B'), + ]) { + final file = _File(); + final stat = _Stat(); + when(() => file.path).thenReturn('/fixture/image.$extension'); + when(file.statSync).thenReturn(stat); + when(() => stat.size).thenReturn(size); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => ds.FileInfoDialog.show(context, file), + child: const Text('show'), + ), + ), + ), + ), + ); + await tester.tap(find.text('show')); + await tester.pumpAndSettle(); + expect(find.text(label), findsOneWidget); + expect(find.text(expectedSize), findsOneWidget); + for (final field in [ + 'File Name', + 'File Type', + 'File Extension', + 'File Size', + 'File Path', + ]) { + await tester.ensureVisible(find.text(field)); + await tester.tap(find.text(field)); + await tester.pump(); + } + expect(copied.last, file.path); + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + expect(find.byType(ds.FileInfoDialog), findsNothing); + } + expect(copied.length, 40); + }, + ); + + testWidgets( + 'image adapters expose placeholder and errors and tolerate missing header assets', + (tester) async { + late CachedNetworkImage image; + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (ctx) { + context = ctx; + image = + const ds.NetworkUrlImage( + url: 'https://example.test/image', + width: 40, + height: 60, + ).build(ctx) + as CachedNetworkImage; + return image.placeholder!(ctx, ''); + }, + ), + ), + ); + expect(image.width, 40); + expect(find.byIcon(Icons.image), findsOneWidget); + final error = image.errorWidget!(context, '', Exception('missing')); + await tester.pumpWidget(MaterialApp(home: error)); + expect(find.byIcon(Icons.image), findsOneWidget); + for (final path in [null, '', 'missing.png']) { + await tester.pumpWidget( + MaterialApp( + home: ds.Header(type: ds.HeaderType.asset, assetPath: path), + ), + ); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.image), findsOneWidget); + expect(tester.takeException(), isNull); + } + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) { + final header = + const ds.Header( + imageUrl: 'https://example.test/cover', + ).build(context) + as AspectRatio; + expect(header.aspectRatio, 4); + expect( + (header.child as ds.NetworkUrlImage).url, + 'https://example.test/cover', + ); + return const SizedBox(); + }, + ), + ), + ); + }, + ); + + testWidgets( + 'auth headers support missing providers, failures and stable async rebuilds', + (tester) async { + final tokens = _Tokens(); + when(tokens.getCurrentToken).thenReturn('cached'); + when(tokens.getValidToken).thenAnswer((_) async => 'fresh'); + Widget subject({AuthTokenProvider? provider, bool validate = false}) => + MaterialApp( + home: ds.AuthHeadersBuilder( + provider: provider, + logger: _Logger(), + validateToken: validate, + builder: (_, headers) => + Text(headers['Authorization'] ?? 'anonymous'), + ), + ); + await tester.pumpWidget(subject()); + expect(find.text('anonymous'), findsOneWidget); + await tester.pumpWidget(subject(provider: tokens)); + expect(find.text('Bearer cached'), findsOneWidget); + await tester.pumpWidget(subject(provider: tokens, validate: true)); + await tester.pumpAndSettle(); + await tester.pumpWidget(subject(provider: tokens, validate: true)); + await tester.pumpAndSettle(); + expect(find.text('Bearer fresh'), findsOneWidget); + verify(tokens.getValidToken).called(1); + when(tokens.getCurrentToken).thenThrow(StateError('unavailable')); + await tester.pumpWidget(subject(provider: tokens)); + expect(find.text('anonymous'), findsOneWidget); + when(tokens.getValidToken).thenThrow(StateError('unavailable')); + await tester.pumpWidget(subject(provider: tokens, validate: true)); + await tester.pumpAndSettle(); + expect(find.text('anonymous'), findsOneWidget); + await tester.pumpWidget(subject(validate: true)); + await tester.pumpAndSettle(); + expect(find.text('anonymous'), findsOneWidget); + }, + ); + + testWidgets('toast variants render their messages and dismiss cleanly', ( + tester, + ) async { + late BuildContext context; + await tester.pumpWidget( + ToastificationWrapper( + child: MaterialApp( + home: Scaffold( + body: Builder( + builder: (ctx) { + context = ctx; + return const SizedBox(); + }, + ), + ), + ), + ), + ); + final callbacks = [ + () => ds.Toast.notification(title: 'Notice', body: 'Details'), + () => ds.Toast.error(context, message: 'Notice', description: 'Details'), + () => + ds.Toast.success(context, message: 'Notice', description: 'Details'), + () => + ds.Toast.warning(context, message: 'Notice', description: 'Details'), + ]; + for (final show in callbacks) { + show(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(const Duration(milliseconds: 500)); + expect( + find.text('Notice'), + findsOneWidget, + reason: 'toast variant ${callbacks.indexOf(show)}', + ); + expect(find.text('Details'), findsOneWidget); + toastification.dismissAll(delayForAnimation: false); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + } + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/developer/CLAUDE.md new file mode 100644 index 0000000..864b003 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/CLAUDE.md @@ -0,0 +1,58 @@ +# Nonstop Example: `packages/developer` + +In-app developer tools (layer 4): a hidden multi-tap gesture that opens a +Talker log viewer, and the flag-guarded `/developer` route. It owns dev-only +UI and its route guard. It must not own logging, flag evaluation or product +screens; those come from `core` and `feature_flags`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. Load the +`design-system` skill before changing UI. + +## Public API + +Exported from `package:developer/developer.dart`. There is no `init()`; nothing is registered with `di`. + +| Symbol | Kind | Notes | +|---|---|---| +| `DeveloperRoutes.developer` | constant | `'/developer'` | +| `DeveloperFlags.screenEnabled` | constant | `'developer_screen_enabled'`; gates both the gesture and the route | +| `DeveloperRouter` | `implements core.CoreRouter` | Resolves `Logger` from `di` at construction; one `GoRoute` named `developer-screen`; spread into the app router (`apps/nonstop_example/lib/router/router.dart`) | +| `DeveloperScreen({required Logger logger})` | widget | `TalkerScreen` when `logger.logger is Talker`, otherwise a `Scaffold` showing `strings.developer.no_viewer` | +| `OpenDevToolsWrapper` | widget | `child`, `tapCount = 5`, `tapWindow = 2s`, `enableHaptics = true`, `enableVisualFeedback = false`; used on the profile avatar in `features/dashboard` | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/developer.dart` | Barrel | +| `lib/src/routes/developer_routes.dart` | `DeveloperRoutes`, `DeveloperFlags`, `DeveloperRouter` with the redirect guard | +| `lib/src/screens/developer_screen.dart` | `DeveloperScreen` | +| `lib/src/widgets/open_dev_tools_wrapper.dart` | Tap counter, reset timer, haptics, optional scale animation and tap-count badge | + +## Rules + +- The route guard is the real protection: `redirect` sends to `core.CoreRoutes.root` when `FeatureFlag` is not registered, when `isEnabled(DeveloperFlags.screenEnabled)` is false, or when it throws. Keep all three paths; hiding the gesture alone does not protect a typed URL. +- The gesture is shown only through `FeatureFlagWrapper(flagKey: DeveloperFlags.screenEnabled)`; when disabled it returns `child` untouched (no `GestureDetector`). +- `DeveloperScreen` takes its `Logger` as a parameter (no `di` lookup) and must keep working with a non-Talker logger. +- `_OpenDevToolsWrapperState.dispose` cancels `_resetTimer` and disposes `_animationController`; any new timer, controller or subscription must be released there too. Guard `setState` / `context.push` with `mounted`. +- Always reference the flag through `DeveloperFlags.screenEnabled`; never inline the string. + +## Common changes + +- **Add a dev-tools entry (e.g. a flags or environment page):** add a screen under `lib/src/screens/` and export it from `screens/index.dart`, add a constant to `DeveloperRoutes` and a `GoRoute` to `DeveloperRouter.routes` with the same `redirect` guard, and add a denied-navigation and an allowed-navigation case to `test/navigation_test.dart`. +- **Change the unlock gesture:** edit `OpenDevToolsWrapper` defaults or `_handleTap`; update the default-value assertions in `test/developer_test.dart` and the tap-window test in `test/navigation_test.dart`. +- **Change the guard flag:** change `DeveloperFlags.screenEnabled` and the flag name in your remote config. + +## Tests + +- `test/developer_test.dart`: route constant and `OpenDevToolsWrapper` default/custom constructor values. +- `test/navigation_test.dart`: non-Talker logger shows `strings.developer.no_viewer`; disabled flag keeps the gesture inert; direct navigation redirected to `/` with no `FeatureFlag` registered; enabled gesture honours `tapWindow` and opens `TalkerScreen`, run with `enableVisualFeedback` false and true. +- Pattern: `setUp(core.init)`, `tearDown(di.reset)`; a fake `FeatureFlagProvider` (`_Flags`) wrapped in a real `FeatureFlag(provider:, logger:)` registered with `di`; `GoRouter` with `addTearDown(router.dispose)`. + +Run: `dart run melos exec --scope=developer -- flutter test`. `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `DeveloperRouter` calls `di.get()` when constructed, so `core.init()` must run before the app router is built. +- The tap-count badge uses `colorScheme.error` / `onError`; keep it on theme roles. +- `DeveloperRouter` resolves `FeatureFlag` from `di` inside `redirect`, so a flag registered after router creation is still honoured. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/developer.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/developer.dart new file mode 100644 index 0000000..546a189 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/developer.dart @@ -0,0 +1,3 @@ +export 'src/routes/index.dart'; +export 'src/screens/index.dart'; +export 'src/widgets/index.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/developer_routes.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/developer_routes.dart new file mode 100644 index 0000000..ccafe3b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/developer_routes.dart @@ -0,0 +1,44 @@ +import 'package:core/core.dart' as core; +import 'package:developer/src/screens/index.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/feature_flags.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; + +class DeveloperRoutes { + static const String developer = '/developer'; +} + +/// Feature flag keys owned by the developer tools. +abstract final class DeveloperFlags { + /// Gates both the entry gesture and the route itself. + static const String screenEnabled = 'developer_screen_enabled'; +} + +class DeveloperRouter implements core.CoreRouter { + final core.Logger _logger = di.get(); + + @override + List get routes => [ + GoRoute( + path: DeveloperRoutes.developer, + name: 'developer-screen', + redirect: (context, state) async { + // Hiding the entry gesture does not protect a directly entered route. + if (!di.has()) return core.CoreRoutes.root; + try { + return await di.get().isEnabled( + DeveloperFlags.screenEnabled, + ) + ? null + : core.CoreRoutes.root; + } catch (_) { + return core.CoreRoutes.root; + } + }, + builder: (BuildContext context, GoRouterState state) { + return DeveloperScreen(logger: _logger); + }, + ), + ]; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/index.dart new file mode 100644 index 0000000..34e52a8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/routes/index.dart @@ -0,0 +1 @@ +export 'developer_routes.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/developer_screen.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/developer_screen.dart new file mode 100644 index 0000000..afd397e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/developer_screen.dart @@ -0,0 +1,18 @@ +import 'package:core/core.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; +import 'package:talker_flutter/talker_flutter.dart'; + +class DeveloperScreen extends StatelessWidget { + const DeveloperScreen({super.key, required this.logger}); + + final Logger logger; + + @override + Widget build(BuildContext context) { + if (logger.logger case final Talker talker) { + return TalkerScreen(talker: talker); + } + return Scaffold(body: Center(child: Text(strings.developer.no_viewer))); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/index.dart new file mode 100644 index 0000000..1f2dffb --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/screens/index.dart @@ -0,0 +1 @@ +export 'developer_screen.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/index.dart new file mode 100644 index 0000000..dfcb372 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/index.dart @@ -0,0 +1 @@ +export 'open_dev_tools_wrapper.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/open_dev_tools_wrapper.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/open_dev_tools_wrapper.dart new file mode 100644 index 0000000..d0e102b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/lib/src/widgets/open_dev_tools_wrapper.dart @@ -0,0 +1,187 @@ +import 'dart:async'; + +import 'package:developer/src/routes/index.dart'; +import 'package:feature_flags/feature_flags.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:go_router/go_router.dart'; + +class OpenDevToolsWrapper extends StatefulWidget { + const OpenDevToolsWrapper({ + super.key, + required this.child, + this.tapCount = 5, + this.tapWindow = const Duration(seconds: 2), + this.enableHaptics = true, + this.enableVisualFeedback = false, + }); + + final Widget child; + final int tapCount; + final Duration tapWindow; + final bool enableHaptics; + final bool enableVisualFeedback; + + @override + State createState() => _OpenDevToolsWrapperState(); +} + +class _OpenDevToolsWrapperState extends State + with SingleTickerProviderStateMixin { + int _currentTapCount = 0; + Timer? _resetTimer; + late AnimationController _animationController; + late Animation _scaleAnimation; + bool _isAnimating = false; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: const Duration(milliseconds: 200), + vsync: this, + ); + _scaleAnimation = Tween(begin: 1.0, end: 0.95).animate( + CurvedAnimation(parent: _animationController, curve: Curves.easeInOut), + ); + } + + @override + void dispose() { + _resetTimer?.cancel(); + _animationController.dispose(); + super.dispose(); + } + + void _handleTap() { + setState(() { + _currentTapCount++; + }); + + // Provide haptic feedback for progress + if (widget.enableHaptics) { + HapticFeedback.selectionClick(); + } + + // Visual feedback animation + if (widget.enableVisualFeedback && !_isAnimating) { + _isAnimating = true; + _animationController.forward().then((_) { + _animationController.reverse().then((_) { + if (mounted) { + setState(() { + _isAnimating = false; + }); + } + }); + }); + } + + // Check if we've reached the required tap count + if (_currentTapCount >= widget.tapCount) { + _navigateToDeveloperScreen(); + return; + } + + // Reset the timer + _resetTimer?.cancel(); + _resetTimer = Timer(widget.tapWindow, _resetTapCount); + } + + void _navigateToDeveloperScreen() { + // Provide success haptic feedback + if (widget.enableHaptics) { + HapticFeedback.mediumImpact(); + } + + // Reset state + _resetTapCount(); + + // Navigate to developer screen + if (mounted) { + context.push(DeveloperRoutes.developer); + } + } + + void _resetTapCount() { + _resetTimer?.cancel(); + if (mounted) { + setState(() { + _currentTapCount = 0; + }); + } + } + + Widget _buildChild() { + if (widget.enableVisualFeedback) { + return AnimatedBuilder( + animation: _scaleAnimation, + builder: (context, child) { + return Transform.scale( + scale: _scaleAnimation.value, + child: widget.child, + ); + }, + ); + } + return widget.child; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return FeatureFlagWrapper( + flagKey: DeveloperFlags.screenEnabled, + builder: (context, isEnabled) { + if (!isEnabled) { + return widget.child; // Just return the child if feature is disabled + } + + return GestureDetector( + onTap: _handleTap, + behavior: HitTestBehavior.translucent, + child: Stack( + children: [ + _buildChild(), + // Optional debug indicator (only visible in debug and with visual feedback enabled) + if (widget.enableVisualFeedback && _currentTapCount > 0) ...[ + Positioned.fill( + child: IgnorePointer( + child: Container( + decoration: BoxDecoration( + border: Border.all( + color: theme.colorScheme.error.withValues(alpha: 0.3), + width: 2, + ), + ), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: theme.colorScheme.error, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + '$_currentTapCount/${widget.tapCount}', + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onError, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ), + ), + ], + ], + ), + ); + }, + ); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/developer/pubspec.yaml new file mode 100644 index 0000000..52cc1a5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/pubspec.yaml @@ -0,0 +1,31 @@ +name: developer +description: "In-app developer tools for Nonstop Example: logs, flags and environment inspection." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + go_router: ^18.0.1 + talker_flutter: ^5.1.20 + core: + path: ../core + di: + path: ../di + feature_flags: + path: ../feature_flags + localization: + path: ../localization + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/test/developer_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/test/developer_test.dart new file mode 100644 index 0000000..a3f8817 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/test/developer_test.dart @@ -0,0 +1,38 @@ +import 'package:developer/developer.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('Developer Package', () { + test('package exports are available', () { + expect(DeveloperRoutes.developer, '/developer'); + }); + + testWidgets('OpenDevToolsWrapper exports are available', (tester) async { + // Test that the widget can be instantiated + const widget = OpenDevToolsWrapper(child: Text('Test')); + + expect(widget, isNotNull); + expect(widget.tapCount, 5); // Default value + expect(widget.tapWindow, const Duration(seconds: 2)); // Default value + expect(widget.enableHaptics, true); // Default value + expect(widget.enableVisualFeedback, false); // Default value + }); + + testWidgets('OpenDevToolsWrapper custom values work', (tester) async { + // Test custom configuration + const widget = OpenDevToolsWrapper( + tapCount: 7, + tapWindow: Duration(seconds: 2), + enableHaptics: false, + enableVisualFeedback: true, + child: Text('Test'), + ); + + expect(widget.tapCount, 7); + expect(widget.tapWindow, const Duration(seconds: 2)); + expect(widget.enableHaptics, false); + expect(widget.enableVisualFeedback, true); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/developer/test/navigation_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/developer/test/navigation_test.dart new file mode 100644 index 0000000..2876b74 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/developer/test/navigation_test.dart @@ -0,0 +1,128 @@ +import 'package:core/core.dart' as core; +import 'package:developer/developer.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/feature_flags.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:localization/localization.dart'; +import 'package:talker_flutter/talker_flutter.dart'; + +class _PlainLogger implements core.Logger { + @override + Object get logger => this; + @override + void d(String message) {} + @override + void i(String message) {} + @override + void w(String message) {} + @override + void e(String message, [Object? error, StackTrace? stackTrace]) {} +} + +class _Flags implements FeatureFlagProvider { + bool enabled = true; + @override + Future init() async {} + @override + Future getBool(String key, {bool defaultValue = false}) async => + enabled; + @override + void dispose() {} + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + setUp(core.init); + tearDown(di.reset); + + testWidgets('a custom logger does not need to expose Talker', (tester) async { + await tester.pumpWidget( + MaterialApp(home: DeveloperScreen(logger: _PlainLogger())), + ); + expect(find.text(strings.developer.no_viewer), findsOneWidget); + }); + + testWidgets('disabled developer gesture remains inert', (tester) async { + final provider = _Flags()..enabled = false; + final service = FeatureFlag( + provider: provider, + logger: di.get(), + ); + await service.init(); + di.register(service, dispose: (service) => service.dispose()); + await tester.pumpWidget( + const MaterialApp(home: OpenDevToolsWrapper(child: Text('Demo'))), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Demo')); + await tester.pumpAndSettle(); + expect(find.text('Demo'), findsOneWidget); + expect(find.byType(TalkerScreen), findsNothing); + }); + + testWidgets( + 'direct navigation is denied before feature flags are configured', + (tester) async { + final router = GoRouter( + initialLocation: DeveloperRoutes.developer, + routes: [ + GoRoute(path: '/', builder: (_, _) => const Text('Home')), + ...DeveloperRouter().routes, + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + expect(find.byType(TalkerScreen), findsNothing); + }, + ); + + for (final visual in [false, true]) { + testWidgets('enabled gesture respects its tap window (visual=$visual)', ( + tester, + ) async { + final provider = _Flags(); + final flags = FeatureFlag( + provider: provider, + logger: di.get(), + ); + await flags.init(); + di.register(flags); + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (_, _) => Scaffold( + body: Center( + child: OpenDevToolsWrapper( + tapCount: 3, + enableVisualFeedback: visual, + child: const Text('Open tools'), + ), + ), + ), + ), + ...DeveloperRouter().routes, + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget(MaterialApp.router(routerConfig: router)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open tools')); + await tester.pump(const Duration(seconds: 3)); + await tester.tap(find.text('Open tools')); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(TalkerScreen), findsNothing); + await tester.tap(find.text('Open tools')); + await tester.pump(const Duration(milliseconds: 500)); + await tester.tap(find.text('Open tools')); + await tester.pumpAndSettle(); + expect(find.byType(TalkerScreen), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/di/CLAUDE.md new file mode 100644 index 0000000..948d9d3 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/CLAUDE.md @@ -0,0 +1,60 @@ +# Nonstop Example: `packages/di` + +The service-locator abstraction (layer 0): the `DependencyInjection` contract, +its GetIt implementation, and the global `di` instance. It owns registration, +lookup and ordered disposal, nothing else. It must not know about any other +workspace package or contain app types. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | Notes | +|---|---|---| +| `di` | global | `final di = GetItDependencyInjection();` over `GetIt.instance` | +| `DependencyInjection` | contract (`abstract interface class`) | `dispose`, `register`, `unregister`, `get`, `has`, `reset` | +| `GetItDependencyInjection({GetIt? getIt, DisposeErrorHandler? onDisposeError})` | implementation | Pass `GetIt.asNewInstance()` for an isolated container | +| `DisposeFunc` | typedef | `FutureOr Function(T param)` | +| `DisposeErrorHandler` | typedef | `void Function(Object error, StackTrace stack)` | +| `onDisposeError` | settable field | Receives dispose-callback failures; defaults to `dart:developer` `log(name: 'di')`. `core.init()` points it at the `Logger` | +| `register(instance, {dispose})` | method | Singleton; `dispose` is stored per type `T` | +| `unregister(instance)` | method | No-op if `T` is not registered; `ArgumentError` if `instance` is not the registered one | +| `has()` / `get()` | methods | `get` throws `StateError` when missing | +| `reset()` | method | Same as `dispose()`; the container is reusable afterwards | +| `getIt` | getter | Underlying `GetIt` (tests use `di.getIt.isRegistered`) | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/di.dart` | Barrel + global `di` | +| `lib/src/dependency_injection.dart` | Contract and `DisposeFunc` | +| `lib/src/dependency_injection_imp.dart` | GetIt implementation, `DisposeErrorHandler`, dispose bookkeeping | + +## Rules + +- `get_it` is imported only here (`pubspec.yaml` depends on `get_it` and Flutter, nothing in the workspace). +- `dispose()` runs dispose callbacks in **reverse registration order**, awaits each, reports failures to `onDisposeError` and keeps going, then clears its maps and calls `GetIt.reset()`. Register dependencies before their dependents. +- `unregister` removes the registration even when its dispose callback throws; a wrong-instance call throws before any disposal. +- Instances and dispose callbacks are keyed by the type argument `T`, so always register with an explicit type (`di.register(...)`) matching how consumers `get` it. +- There is no `init()`; the container is usable as soon as it is constructed. +- A registration without `dispose:` is dropped on reset with no cleanup; anything holding streams, timers or SDK handles must pass `dispose:`. + +## Common changes + +- **Change disposal semantics:** edit `dispose()` / `unregister()` in `dependency_injection_imp.dart` and extend `test/lifecycle_test.dart` (ordering, awaited async cleanup, failure isolation). +- **Add a contract method:** add it to `DependencyInjection`, implement it in `GetItDependencyInjection`, and add a group in `test/di_test.dart`. Every consumer uses `di`, so keep it additive. + +## Tests + +- `test/di_test.dart`: register/get/has, dispose callbacks on unregister and dispose, registration with no prior setup, missing-type errors, unregistering unknown types, reset, multiple dependencies. +- `test/lifecycle_test.dart`: reverse-order awaited disposal that continues past a throwing callback, idempotent second reset, unregister cleanup failure, failures routed to `onDisposeError`, wrong-instance unregistration without side effects. +- Pattern: a fresh `GetItDependencyInjection(getIt: GetIt.asNewInstance())` per test, disposed in `tearDown`. Never test against the global `di` here. + +Run: `dart run melos exec --scope=di -- flutter test`. `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `di` wraps the process-wide `GetIt.instance`; other packages' tests share it, which is why they use `tearDown(di.reset)`. +- Registering the same `T` twice throws from GetIt; `unregister` or `reset` first. +- This package cannot depend on `core`, so dispose failures reach the `Logger` only after `core.init()` sets `di.onDisposeError`; before that (and for isolated containers) they go to `dart:developer` logs. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/README.md b/packages/nonstop_cli/example/nonstop_example/packages/di/README.md new file mode 100644 index 0000000..77627d1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/README.md @@ -0,0 +1,6 @@ +# Dependency Injection (DI) Package + +A clean dependency injection abstraction for the Nonstop Example monorepo, built on top of GetIt. + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/lib/di.dart b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/di.dart new file mode 100644 index 0000000..ab6134d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/di.dart @@ -0,0 +1,14 @@ +/// Dependency Injection package for Nonstop Example +/// +/// This package provides a clean abstraction over dependency injection +/// using GetIt as the underlying implementation. +library; + +import 'package:di/di.dart'; + +// Core interfaces +export 'src/dependency_injection.dart'; +// GetIt implementation +export 'src/dependency_injection_imp.dart'; + +final di = GetItDependencyInjection(); diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection.dart b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection.dart new file mode 100644 index 0000000..1850d35 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection.dart @@ -0,0 +1,20 @@ +import 'dart:async'; + +typedef DisposeFunc = FutureOr Function(T param); + +abstract interface class DependencyInjection { + Future dispose(); + + void register( + final T instance, { + final DisposeFunc? dispose, + }); + + Future unregister(final T? instance); + + T get(); + + bool has(); + + Future reset(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection_imp.dart b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection_imp.dart new file mode 100644 index 0000000..9c54fa4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/lib/src/dependency_injection_imp.dart @@ -0,0 +1,128 @@ +import 'dart:async'; + +import 'dart:developer' as dev; + +import 'package:di/src/dependency_injection.dart'; +import 'package:get_it/get_it.dart'; + +/// Receives a failure thrown by a registration's dispose callback. +typedef DisposeErrorHandler = void Function(Object error, StackTrace stack); + +/// Implementation of DependencyInjection using GetIt +class GetItDependencyInjection implements DependencyInjection { + final GetIt _getIt; + final Map _disposeFunctions = {}; + final Map _registeredInstances = {}; + + /// Called when a dispose callback throws; disposal carries on regardless. + /// + /// Defaults to `dart:developer` logging. Settable so the app can route it + /// to its logger once one is registered, without `di` depending on it. + DisposeErrorHandler onDisposeError; + + /// Creates a new instance with optional GetIt instance + /// If no instance is provided, uses GetIt.instance + GetItDependencyInjection({GetIt? getIt, DisposeErrorHandler? onDisposeError}) + : _getIt = getIt ?? GetIt.instance, + onDisposeError = onDisposeError ?? _logDisposeError; + + static void _logDisposeError(Object error, StackTrace stack) => dev.log( + 'Error disposing a registered instance', + name: 'di', + error: error, + stackTrace: stack, + ); + + @override + Future dispose() async { + // Call dispose functions for all registered instances + // Dependents are registered after dependencies; tear them down first. + for (final entry in _disposeFunctions.entries.toList().reversed) { + final type = entry.key; + final disposeFunc = entry.value; + final instance = _registeredInstances[type]; + + if (instance != null) { + try { + await disposeFunc(instance); + } catch (error, stack) { + // Report but continue disposing other instances + onDisposeError(error, stack); + } + } + } + + // Clear dispose functions and registered instances maps + _disposeFunctions.clear(); + _registeredInstances.clear(); + + // Reset GetIt instance + await _getIt.reset(); + } + + @override + void register( + final T instance, { + final DisposeFunc? dispose, + }) { + // Register the instance as a singleton + _getIt.registerSingleton(instance); + + // Store the instance and dispose function if provided + _registeredInstances[T] = instance; + if (dispose != null) { + _disposeFunctions[T] = dispose; + } + } + + @override + Future unregister(final T? instance) async { + if (!_getIt.isRegistered()) { + return; + } + if (instance != null && !identical(instance, _getIt.get())) { + throw ArgumentError.value( + instance, + 'instance', + 'Does not match the registered instance of $T', + ); + } + + // Call dispose function if it exists + final disposeFunc = _disposeFunctions[T]; + if (disposeFunc != null) { + try { + final registeredInstance = instance ?? _registeredInstances[T]; + if (registeredInstance != null) { + await disposeFunc(registeredInstance); + } + } catch (error, stack) { + // Report but continue with unregistration + onDisposeError(error, stack); + } + _disposeFunctions.remove(T); + } + + // Remove from our tracking + _registeredInstances.remove(T); + + // Unregister from GetIt + await _getIt.unregister(instance: instance); + } + + @override + T get() { + return _getIt.get(); + } + + @override + bool has() { + return _getIt.isRegistered(); + } + + @override + Future reset() => dispose(); + + /// Get the underlying GetIt instance (for advanced usage) + GetIt get getIt => _getIt; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/di/pubspec.yaml new file mode 100644 index 0000000..e696c4d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/pubspec.yaml @@ -0,0 +1,22 @@ +name: di +description: "Service locator abstraction for Nonstop Example, backed by GetIt." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + get_it: ^9.3.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/test/di_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/di/test/di_test.dart new file mode 100644 index 0000000..b9b895b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/test/di_test.dart @@ -0,0 +1,225 @@ +import 'package:di/di.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:get_it/get_it.dart'; + +// Test classes for dependency injection +class TestService { + final String name; + bool isDisposed = false; + + TestService(this.name); + + void dispose() { + isDisposed = true; + } +} + +class TestRepository { + final TestService service; + bool isDisposed = false; + + TestRepository(this.service); + + void dispose() { + isDisposed = true; + } +} + +void main() { + group('GetItDependencyInjection', () { + late GetItDependencyInjection di; + late GetIt testGetIt; + + setUp(() { + // Create a separate GetIt instance for testing + testGetIt = GetIt.asNewInstance(); + di = GetItDependencyInjection(getIt: testGetIt); + }); + + tearDown(() async { + await di.dispose(); + }); + + group('Registration', () { + test('should register and retrieve instances', () async { + final service = TestService('test'); + + di.register(service); + + expect(di.has(), true); + final retrieved = di.get(); + expect(retrieved, same(service)); + expect(retrieved.name, 'test'); + }); + + test('should register with dispose function', () async { + final service = TestService('test'); + bool disposeCalled = false; + + di.register( + service, + dispose: (instance) { + disposeCalled = true; + instance.dispose(); + }, + ); + + expect(di.has(), true); + await di.unregister(null); + + expect(disposeCalled, true); + expect(service.isDisposed, true); + expect(di.has(), false); + }); + }); + + group('Error handling', () { + test('registration needs no prior setup', () { + final service = TestService('test'); + + di.register(service); + + expect(di.get(), same(service)); + }); + + test('should throw when getting before registration', () { + expect(() => di.get(), throwsA(isA())); + }); + + test('should return false when nothing is registered', () { + expect(di.has(), false); + }); + }); + + group('Retrieval', () { + test('should get registered instances', () { + final service = TestService('test'); + di.register(service); + + final retrieved = di.get(); + expect(retrieved, same(service)); + }); + + test('should throw when getting unregistered type', () { + expect(() => di.get(), throwsA(isA())); + }); + }); + + group('Has/Contains', () { + test('should return true for registered types', () { + final service = TestService('test'); + di.register(service); + + expect(di.has(), true); + }); + + test('should return false for unregistered types', () { + expect(di.has(), false); + }); + }); + + group('Unregistration', () { + test('should unregister instances', () async { + final service = TestService('test'); + di.register(service); + + expect(di.has(), true); + await di.unregister(null); + expect(di.has(), false); + }); + + test('should call dispose function when unregistering', () async { + final service = TestService('test'); + bool disposeCalled = false; + + di.register( + service, + dispose: (instance) { + disposeCalled = true; + instance.dispose(); + }, + ); + + await di.unregister(null); + + expect(disposeCalled, true); + expect(service.isDisposed, true); + }); + + test( + 'should handle unregistering non-existent types gracefully', + () async { + // Should not throw + await di.unregister(null); + expect(di.has(), false); + }, + ); + + test('should handle unregistering on an empty container', () async { + // Should not throw + await di.unregister(null); + }); + }); + + group('Disposal', () { + test('should dispose all registered instances', () async { + final service = TestService('service'); + final repository = TestRepository(service); + + di.register( + service, + dispose: (instance) => instance.dispose(), + ); + + di.register( + repository, + dispose: (instance) => instance.dispose(), + ); + + await di.dispose(); + + expect(service.isDisposed, true); + expect(repository.isDisposed, true); + expect(di.has(), false); + expect(di.has(), false); + }); + }); + + group('Reset', () { + test('should reset and dispose registrations', () async { + final service = TestService('test'); + di.register( + service, + dispose: (instance) => instance.dispose(), + ); + + expect(di.has(), true); + + await di.reset(); + + expect(di.has(), false); + expect(service.isDisposed, true); + }); + }); + + group('Complex scenarios', () { + test('should handle multiple dependencies', () { + final service = TestService('service'); + final repository = TestRepository(service); + + di.register(service); + di.register(repository); + + expect(di.has(), true); + expect(di.has(), true); + + final retrievedService = di.get(); + final retrievedRepository = di.get(); + + expect(retrievedService, same(service)); + expect(retrievedRepository, same(repository)); + expect(retrievedRepository.service, same(service)); + }); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/di/test/lifecycle_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/di/test/lifecycle_test.dart new file mode 100644 index 0000000..5e19f8e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/di/test/lifecycle_test.dart @@ -0,0 +1,91 @@ +import 'package:di/di.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:get_it/get_it.dart'; + +class _Service {} + +void main() { + late GetItDependencyInjection container; + setUp( + () => container = GetItDependencyInjection(getIt: GetIt.asNewInstance()), + ); + tearDown(() => container.dispose()); + + test( + 'disposes dependents first, awaits cleanup and continues after failures', + () async { + final order = []; + container.register( + 'service', + dispose: (_) async { + order.add('service'); + }, + ); + container.register( + 1, + dispose: (_) async { + order.add('repository'); + throw StateError('cleanup'); + }, + ); + container.register( + true, + dispose: (_) async { + order.add('controller'); + }, + ); + await container.reset(); + expect(order, ['controller', 'repository', 'service']); + expect(container.has(), isFalse); + await container.reset(); + expect(order, hasLength(3)); + }, + ); + + test('unregister cleanup failure still removes the registration', () async { + container.register( + 'value', + dispose: (_) => throw StateError('cleanup'), + ); + await container.unregister(null); + expect(container.has(), isFalse); + }); + + test('dispose failures are routed to the configured handler', () async { + final errors = []; + container = GetItDependencyInjection( + getIt: GetIt.asNewInstance(), + onDisposeError: (error, _) => errors.add(error), + ); + container.register( + 'value', + dispose: (_) => throw StateError('unregister'), + ); + await container.unregister(null); + container.register(1, dispose: (_) => throw StateError('dispose')); + await container.dispose(); + expect(errors.map((e) => (e as StateError).message), [ + 'unregister', + 'dispose', + ]); + }); + + test('wrong-instance unregistration has no disposal side effects', () async { + final first = _Service(); + var disposed = false; + container.register<_Service>( + first, + dispose: (_) { + disposed = true; + }, + ); + await expectLater( + container.unregister<_Service>(_Service()), + throwsArgumentError, + ); + expect(container.get<_Service>(), same(first)); + expect(disposed, isFalse); + await container.unregister<_Service>(first); + expect(disposed, isTrue); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/CLAUDE.md new file mode 100644 index 0000000..1b7e67f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/CLAUDE.md @@ -0,0 +1,61 @@ +# Nonstop Example: `packages/feature_flags` + +Owns remote feature flags and config values: the `FeatureFlag` contract and its +`FeatureFlagService` implementation, the `FeatureFlagProvider` backend contract +with its Firebase Remote Config adapter, and the `FeatureFlagWrapper` widget. It +does not own flag meaning or product rollout decisions; flag keys and defaults +come from callers. Layer 2: depends on `core`, `di`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | +|---|---| +| `FeatureFlag` / `FeatureFlagService(provider:, logger:)` | `abstract interface class` (factory `FeatureFlag(...)` builds the service) / implementation: `init`, `isInitialized`, `isEnabled`, `hasFlag`, `getConfig`, `getIntConfig`, `getDoubleConfig`, `dispose` | +| `FeatureFlagProvider` / `FirebaseRemoteConfigProvider(remoteConfig:, logger:, config:)` | `abstract interface class` / Remote Config implementation: `init`, `getBool`, `getString`, `getInt`, `getDouble`, `hasFlag`, `dispose`; adapter also exposes `lastFetchTime`, `lastFetchStatus`, `config` | +| `FeatureFlagsConfig` | `fetchTimeout` (default `defaultFetchTimeout`, 10s), `minimumFetchInterval` (default `defaultMinimumFetchInterval`, 30 min), `defaultParameters` | +| `init({provider, config})` | Registers, then awaits `FeatureFlag.init()` | +| `registerFeatureFlagsWithDI({config, provider})` | Registers `FeatureFlagProvider` (no dispose) and `FeatureFlag` (with dispose) | +| `FeatureFlagWrapper(flagKey:, builder:, defaultValue:, loading:, service:, logger:)`, `FeatureFlagWrapper.resolve()` | Widget rendering `builder(context, enabled)`; `resolve()` is the locator fallback for unpassed collaborators | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/feature_flags.dart` | Barrel and `init` | +| `lib/src/client/` | `FeatureFlag` contract, `FeatureFlagService` | +| `lib/src/config/` | `FeatureFlagsConfig` | +| `lib/src/di/` | `registerFeatureFlagsWithDI` | +| `lib/src/providers/` | `FeatureFlagProvider` contract, `FirebaseRemoteConfigProvider` | +| `lib/src/widgets/` | `FeatureFlagWrapper` | + +Each folder has an `index.dart` barrel. + +## Rules + +- **Reads before init throw.** `FeatureFlagService` throws `StateError` from every getter until `init()` succeeds. `init()` is idempotent and a failed one can be retried. +- **Local setup failures propagate; offline fetch does not.** A `setConfigSettings` or `setDefaults` error is logged and rethrown by the adapter, the service and module `init`. A `fetchAndActivate` failure (e.g. offline) is only logged as a warning and startup continues with cached or default values. +- **Read failures fall back.** Adapter getters return the caller's `defaultValue` when the SDK throws. A key whose source is `ValueSource.valueStatic` (unknown to both remote and `defaultParameters`) also returns the caller default. Remote `false`, `0` and `''` are real values. +- **Disposal ownership.** `FeatureFlagService.dispose()` disposes the provider. The provider is registered without a `dispose:` callback so a DI reset disposes it exactly once. Keep it that way. +- **Wrapper.** Caches the read future and re-reads only when `flagKey`, `defaultValue` or `service` changes. Unpassed `service`/`logger` come from `FeatureFlagWrapper.resolve()` (`di.has` guarded, the package's single locator fallback). No registered `FeatureFlag` or a read error renders `defaultValue`; errors are logged. Pass `service:` in tests and leaf widgets. +- **Injected:** `FirebaseRemoteConfig` and `Logger` into the adapter; `FeatureFlagProvider` and `Logger` into the service. + +## Common changes + +- **Add a flag:** read it with `di.get().isEnabled('key', defaultValue: ...)` or `FeatureFlagWrapper(flagKey: 'key', ...)` at the call site. For a default shared by every read, put it in `FeatureFlagsConfig.defaultParameters` passed to `init` (bootstrap currently calls `feature_flags.init()` with the default empty map). There is no key registry in this package. +- **Add a typed getter:** add it to `FeatureFlagProvider`, implement it in `FirebaseRemoteConfigProvider` with the `valueStatic` check and try/catch, then declare it on `FeatureFlag` and implement it in `FeatureFlagService` behind `_ensureInitialized()`. Extend the "missing keys", "configured false, zero and empty" and "SDK read failures" tests and "typed reads preserve caller defaults". +- **Swap the backend:** implement `FeatureFlagProvider` and pass it as `init(provider: ...)`. + +## Tests + +`test/feature_flags_test.dart` covers the init guard and idempotency, retry after failure, typed reads with caller defaults, module init and single disposal on `di.reset`, init failure, wrapper caching, fallback and `resolve()` with logged read failures (widget tests), and the Firebase adapter (settings, defaults, metadata, offline startup, missing vs configured values, SDK failures). + +Doubles: mocktail `FeatureFlagProvider` (`_Provider`), `FirebaseRemoteConfig` (`_RemoteConfig`), `Logger` (`_Logger`). + +`dart run melos exec --scope=feature_flags -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- Module `init` still awaits `fetchAndActivate` (bounded by `fetchTimeout`) before bootstrap continues, even though a failed fetch no longer fails it. +- Real-time Remote Config updates are not wired; values change only on the next `init` fetch. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/README.md b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/README.md new file mode 100644 index 0000000..4056bd0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/README.md @@ -0,0 +1,79 @@ +# feature_flags + +Remote-config backed feature flags for Nonstop Example: a `FeatureFlag` +contract, a Firebase Remote Config provider and a `FeatureFlagWrapper` widget. + +## Initialise + +Firebase must be initialised and a `Logger` registered. + +```dart +import 'package:feature_flags/feature_flags.dart' as feature_flags; + +await feature_flags.init( + config: const feature_flags.FeatureFlagsConfig( + defaultParameters: {'developer_screen_enabled': false}, + ), +); +``` + +`init` registers `FeatureFlagProvider` and `FeatureFlag`, then initialises the +provider. If the Remote Config fetch fails (for example when the device is +offline), a warning is logged and the app starts with cached or default values. +Failures applying settings or defaults still propagate. + +Pass `provider:` to use another backend; implement `FeatureFlagProvider`. + +## Configure + +| `FeatureFlagsConfig` field | Default | +| --- | --- | +| `fetchTimeout` | `FeatureFlagsConfig.defaultFetchTimeout` (10 s) | +| `minimumFetchInterval` | `FeatureFlagsConfig.defaultMinimumFetchInterval` (30 min) | +| `defaultParameters` | `{}` (in-app values used until a fetch succeeds) | + +## Reading flags + +Depend on the `FeatureFlag` contract (inject it, or read `di.get()` +at a composition edge): + +```dart +final flags = di.get(); + +if (await flags.isEnabled('new_checkout')) { ... } +await flags.hasFlag('new_checkout'); +await flags.getConfig('welcome_text', defaultValue: 'Hi'); +await flags.getIntConfig('max_items', defaultValue: 10); +await flags.getDoubleConfig('discount', defaultValue: 0.1); +``` + +Keys without a remote or in-app value return the `defaultValue` you pass. + +## Widget + +```dart +FeatureFlagWrapper( + flagKey: 'new_checkout', + loading: const CircularProgressIndicator(), + builder: (context, enabled) => + enabled ? const NewCheckout() : const OldCheckout(), +); +``` + +`service` and `logger` are optional constructor parameters. When omitted they +are resolved once per read through `FeatureFlagWrapper.resolve()`, the package's +only locator fallback. With no `FeatureFlag` registered the builder receives +`defaultValue`. + +## Errors + +- Reading before `init()` completes throws `StateError`. +- Provider read failures return the default value and are logged. +- `FeatureFlagWrapper` logs read failures through `Logger` and renders with + `defaultValue`. + +## Privacy rules + +- Flag reads are not logged. +- Do not use Remote Config to deliver secrets or personal data: values are + readable by anyone with the app. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/feature_flags.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/feature_flags.dart new file mode 100644 index 0000000..0f030ba --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/feature_flags.dart @@ -0,0 +1,30 @@ +library; + +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/src/client/index.dart'; +import 'package:feature_flags/src/config/index.dart'; +import 'package:feature_flags/src/di/index.dart'; +import 'package:feature_flags/src/providers/index.dart'; + +export 'src/client/index.dart'; +export 'src/config/index.dart'; +export 'src/di/index.dart'; +export 'src/providers/index.dart'; +export 'src/widgets/index.dart'; + +/// Initialize the feature flags module and register with DI +Future init({ + FeatureFlagProvider? provider, + FeatureFlagsConfig config = const FeatureFlagsConfig(), +}) async { + final logger = di.get(); + try { + await registerFeatureFlagsWithDI(config: config, provider: provider); + await di.get().init(); + logger.i('Feature flags module initialized'); + } catch (e, stackTrace) { + logger.e('Failed to initialize feature flags module', e, stackTrace); + rethrow; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag.dart new file mode 100644 index 0000000..d5da445 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag.dart @@ -0,0 +1,33 @@ +import 'package:core/logger/logger.dart'; +import 'package:feature_flags/src/client/feature_flag_service.dart'; +import 'package:feature_flags/src/providers/feature_flag_provider.dart'; + +/// Read access to feature flags and remote configuration values. +/// +/// Reads throw [StateError] until [init] has completed. +abstract interface class FeatureFlag { + /// Creates the default [FeatureFlagService] implementation. + factory FeatureFlag({ + required FeatureFlagProvider provider, + required Logger logger, + }) = FeatureFlagService; + + /// Initializes the underlying provider; repeated calls are no-ops. + Future init(); + + bool get isInitialized; + + /// Whether the boolean flag [key] is on, or [defaultValue] when unset. + Future isEnabled(String key, {bool defaultValue = false}); + + /// Whether [key] has a remote or in-app default value. + Future hasFlag(String key); + + Future getConfig(String key, {String defaultValue = ''}); + + Future getIntConfig(String key, {int defaultValue = 0}); + + Future getDoubleConfig(String key, {double defaultValue = 0.0}); + + void dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag_service.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag_service.dart new file mode 100644 index 0000000..2529cbc --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/feature_flag_service.dart @@ -0,0 +1,79 @@ +import 'package:core/logger/logger.dart'; +import 'package:feature_flags/src/client/feature_flag.dart'; +import 'package:feature_flags/src/providers/feature_flag_provider.dart'; + +/// [FeatureFlag] backed by a [FeatureFlagProvider]. +class FeatureFlagService implements FeatureFlag { + FeatureFlagService({ + required FeatureFlagProvider provider, + required Logger logger, + }) : _provider = provider, + _logger = logger; + + final FeatureFlagProvider _provider; + final Logger _logger; + bool _initialized = false; + + @override + Future init() async { + if (_initialized) { + _logger.w('FeatureFlag already initialized'); + return; + } + + try { + await _provider.init(); + _initialized = true; + _logger.i('FeatureFlag initialized successfully'); + } catch (e, stackTrace) { + _logger.e('Failed to initialize FeatureFlag', e, stackTrace); + rethrow; + } + } + + @override + bool get isInitialized => _initialized; + + @override + Future isEnabled(String key, {bool defaultValue = false}) { + _ensureInitialized(); + return _provider.getBool(key, defaultValue: defaultValue); + } + + @override + Future hasFlag(String key) { + _ensureInitialized(); + return _provider.hasFlag(key); + } + + @override + Future getConfig(String key, {String defaultValue = ''}) { + _ensureInitialized(); + return _provider.getString(key, defaultValue: defaultValue); + } + + @override + Future getIntConfig(String key, {int defaultValue = 0}) { + _ensureInitialized(); + return _provider.getInt(key, defaultValue: defaultValue); + } + + @override + Future getDoubleConfig(String key, {double defaultValue = 0.0}) { + _ensureInitialized(); + return _provider.getDouble(key, defaultValue: defaultValue); + } + + @override + void dispose() { + _provider.dispose(); + _initialized = false; + _logger.i('FeatureFlag disposed'); + } + + void _ensureInitialized() { + if (!_initialized) { + throw StateError('FeatureFlag not initialized. Call init() first.'); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/index.dart new file mode 100644 index 0000000..82aba04 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/client/index.dart @@ -0,0 +1,2 @@ +export 'feature_flag.dart'; +export 'feature_flag_service.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/feature_flags_config.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/feature_flags_config.dart new file mode 100644 index 0000000..a142073 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/feature_flags_config.dart @@ -0,0 +1,16 @@ +/// Remote-config fetch settings and in-app defaults. +class FeatureFlagsConfig { + const FeatureFlagsConfig({ + this.fetchTimeout = defaultFetchTimeout, + this.minimumFetchInterval = defaultMinimumFetchInterval, + this.defaultParameters = const {}, + }); + + /// Used by both module startup and the provider when no config is given. + static const defaultFetchTimeout = Duration(seconds: 10); + static const defaultMinimumFetchInterval = Duration(minutes: 30); + + final Duration fetchTimeout; + final Duration minimumFetchInterval; + final Map defaultParameters; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/index.dart new file mode 100644 index 0000000..e708d53 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/config/index.dart @@ -0,0 +1 @@ +export 'feature_flags_config.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/feature_flags_di.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/feature_flags_di.dart new file mode 100644 index 0000000..fc02576 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/feature_flags_di.dart @@ -0,0 +1,31 @@ +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/src/client/index.dart'; +import 'package:feature_flags/src/config/index.dart'; +import 'package:feature_flags/src/providers/index.dart'; +import 'package:firebase_remote_config/firebase_remote_config.dart'; + +/// Register feature flags services with dependency injection +Future registerFeatureFlagsWithDI({ + FeatureFlagsConfig? config, + FeatureFlagProvider? provider, +}) async { + final logger = di.get(); + + final selectedProvider = + provider ?? + FirebaseRemoteConfigProvider( + config: config, + logger: logger, + remoteConfig: FirebaseRemoteConfig.instance, + ); + // The service owns provider disposal; registering it twice would dispose + // platform subscriptions twice when the container is reset. + di.register(selectedProvider); + + final service = FeatureFlagService( + provider: selectedProvider, + logger: logger, + ); + di.register(service, dispose: (s) => s.dispose()); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/index.dart new file mode 100644 index 0000000..69f47be --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/di/index.dart @@ -0,0 +1 @@ +export 'feature_flags_di.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/feature_flag_provider.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/feature_flag_provider.dart new file mode 100644 index 0000000..dfaeac6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/feature_flag_provider.dart @@ -0,0 +1,23 @@ +/// Backend that stores flag values (Firebase Remote Config by default). +abstract interface class FeatureFlagProvider { + /// Initialize the feature flag provider + Future init(); + + /// Get a boolean feature flag value + Future getBool(String key, {bool defaultValue = false}); + + /// Get a string feature flag value + Future getString(String key, {String defaultValue = ''}); + + /// Get an integer feature flag value + Future getInt(String key, {int defaultValue = 0}); + + /// Get a double feature flag value + Future getDouble(String key, {double defaultValue = 0.0}); + + /// Check if a feature flag exists + Future hasFlag(String key); + + /// Dispose resources + void dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/firebase_remote_config_provider.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/firebase_remote_config_provider.dart new file mode 100644 index 0000000..00a5c0b --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/firebase_remote_config_provider.dart @@ -0,0 +1,126 @@ +import 'package:core/logger/logger.dart'; +import 'package:feature_flags/src/config/feature_flags_config.dart'; +import 'package:feature_flags/src/providers/feature_flag_provider.dart'; +import 'package:firebase_remote_config/firebase_remote_config.dart'; + +/// Firebase Remote Config implementation of FeatureFlagProvider +class FirebaseRemoteConfigProvider implements FeatureFlagProvider { + final FirebaseRemoteConfig _remoteConfig; + final FeatureFlagsConfig _config; + final Logger logger; + + FirebaseRemoteConfigProvider({ + required FirebaseRemoteConfig remoteConfig, + required this.logger, + FeatureFlagsConfig? config, + }) : _remoteConfig = remoteConfig, + _config = config ?? const FeatureFlagsConfig(); + + /// Applies settings and defaults, then fetches. A failed fetch (e.g. when + /// offline) is logged and startup continues with cached or default values. + @override + Future init() async { + try { + await _remoteConfig.setConfigSettings( + RemoteConfigSettings( + fetchTimeout: _config.fetchTimeout, + minimumFetchInterval: _config.minimumFetchInterval, + ), + ); + await _remoteConfig.setDefaults(_config.defaultParameters); + } catch (e, stackTrace) { + logger.e('Failed to initialize Firebase Remote Config', e, stackTrace); + rethrow; + } + + try { + final activated = await _remoteConfig.fetchAndActivate(); + logger.i( + 'Firebase Remote Config initialized (activated: $activated, ' + 'status: ${_remoteConfig.lastFetchStatus})', + ); + } catch (e) { + logger.w( + 'Remote Config fetch failed; using cached or default values: $e', + ); + } + } + + @override + Future getBool(String key, {bool defaultValue = false}) async { + try { + final configValue = _remoteConfig.getValue(key); + return configValue.source == ValueSource.valueStatic + ? defaultValue + : _remoteConfig.getBool(key); + } catch (e) { + logger.e( + 'Failed to get bool flag: $key, using default: $defaultValue', + e, + ); + return defaultValue; + } + } + + @override + Future getString(String key, {String defaultValue = ''}) async { + try { + return _remoteConfig.getValue(key).source == ValueSource.valueStatic + ? defaultValue + : _remoteConfig.getString(key); + } catch (e) { + logger.w('Failed to get string flag: $key, using default: $defaultValue'); + return defaultValue; + } + } + + @override + Future getInt(String key, {int defaultValue = 0}) async { + try { + return _remoteConfig.getValue(key).source == ValueSource.valueStatic + ? defaultValue + : _remoteConfig.getInt(key); + } catch (e) { + logger.w('Failed to get int flag: $key, using default: $defaultValue'); + return defaultValue; + } + } + + @override + Future getDouble(String key, {double defaultValue = 0.0}) async { + try { + return _remoteConfig.getValue(key).source == ValueSource.valueStatic + ? defaultValue + : _remoteConfig.getDouble(key); + } catch (e) { + logger.w('Failed to get double flag: $key, using default: $defaultValue'); + return defaultValue; + } + } + + @override + Future hasFlag(String key) async { + try { + final value = _remoteConfig.getValue(key); + return value.source != ValueSource.valueStatic; + } catch (e) { + logger.w('Failed to check if flag exists: $key'); + return false; + } + } + + @override + void dispose() { + // Firebase Remote Config doesn't require explicit disposal + logger.i('Firebase Remote Config provider disposed'); + } + + /// Get the last fetch time + DateTime get lastFetchTime => _remoteConfig.lastFetchTime; + + /// Get the last fetch status + RemoteConfigFetchStatus get lastFetchStatus => _remoteConfig.lastFetchStatus; + + /// Get the current configuration + FeatureFlagsConfig get config => _config; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/index.dart new file mode 100644 index 0000000..a012070 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/providers/index.dart @@ -0,0 +1,2 @@ +export 'feature_flag_provider.dart'; +export 'firebase_remote_config_provider.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/feature_flag_wrapper.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/feature_flag_wrapper.dart new file mode 100644 index 0000000..0130e2d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/feature_flag_wrapper.dart @@ -0,0 +1,105 @@ +import 'package:core/logger/logger.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/src/client/feature_flag.dart'; +import 'package:flutter/material.dart'; + +/// A wrapper widget that conditionally renders content based on feature flags +class FeatureFlagWrapper extends StatefulWidget { + const FeatureFlagWrapper({ + super.key, + required this.flagKey, + required this.builder, + this.defaultValue = false, + this.loading, + this.service, + this.logger, + }); + + /// The single locator fallback in this package, used only for collaborators + /// not passed to the constructor. It resolves the registered [FeatureFlag] + /// and [Logger] at the widget build edge (null when not registered) so a + /// screen can drop the wrapper in without threading services through. + static ({FeatureFlag? service, Logger? logger}) resolve() => ( + service: di.has() ? di.get() : null, + logger: di.has() ? di.get() : null, + ); + + /// The feature flag key to check + final String flagKey; + + /// Builder function that receives the context and feature flag value + final Widget Function(BuildContext context, bool value) builder; + + /// The default value to use if the feature flag service is unavailable + final bool defaultValue; + + /// Widget to show while loading the feature flag value + final Widget? loading; + + /// Flag source; defaults to the registered one (see [resolve]). + final FeatureFlag? service; + + /// Receives read failures; defaults to the registered one (see [resolve]). + final Logger? logger; + + @override + State createState() => _FeatureFlagWrapperState(); +} + +class _FeatureFlagWrapperState extends State { + late Future _value; + + @override + void initState() { + super.initState(); + _value = _checkFeatureFlag(); + } + + @override + void didUpdateWidget(FeatureFlagWrapper oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.flagKey != widget.flagKey || + oldWidget.defaultValue != widget.defaultValue || + oldWidget.service != widget.service) { + _value = _checkFeatureFlag(); + } + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _value, + builder: (context, snapshot) { + // Show loading widget while waiting for feature flag + if (snapshot.connectionState == ConnectionState.waiting) { + return widget.loading ?? const SizedBox.shrink(); + } + + // Get the feature flag value, defaulting to false if there's an error + final isEnabled = snapshot.data ?? widget.defaultValue; + + // Return the widget built by the builder function + return widget.builder(context, isEnabled); + }, + ); + } + + Future _checkFeatureFlag() async { + final service = widget.service ?? FeatureFlagWrapper.resolve().service; + // Feature flags not configured: render with the default. + if (service == null) return widget.defaultValue; + try { + return await service.isEnabled( + widget.flagKey, + defaultValue: widget.defaultValue, + ); + } catch (error, stackTrace) { + (widget.logger ?? FeatureFlagWrapper.resolve().logger)?.e( + 'Feature flag ${widget.flagKey} could not be read; using default', + error, + stackTrace, + ); + return widget.defaultValue; + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/index.dart new file mode 100644 index 0000000..e1fdbc7 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/lib/src/widgets/index.dart @@ -0,0 +1 @@ +export 'feature_flag_wrapper.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/pubspec.yaml new file mode 100644 index 0000000..6f3431f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/pubspec.yaml @@ -0,0 +1,27 @@ +name: feature_flags +description: "Remote-config backed feature flags for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + firebase_remote_config: ^6.7.0 + core: + path: ../core + di: + path: ../di + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/test/feature_flags_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/test/feature_flags_test.dart new file mode 100644 index 0000000..df54ad4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/feature_flags/test/feature_flags_test.dart @@ -0,0 +1,258 @@ +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:feature_flags/feature_flags.dart'; +import 'package:feature_flags/feature_flags.dart' as flags; +import 'package:firebase_remote_config/firebase_remote_config.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _Logger extends Mock implements Logger {} + +class _Provider extends Mock implements FeatureFlagProvider {} + +class _RemoteConfig extends Mock implements FirebaseRemoteConfig {} + +void main() { + late _Logger logger; + late _Provider provider; + late FeatureFlag service; + setUp(() { + logger = _Logger(); + provider = _Provider(); + when(provider.init).thenAnswer((_) async {}); + service = FeatureFlag(provider: provider, logger: logger); + }); + tearDown(di.reset); + + test('reads require initialization; lifecycle is idempotent', () async { + expect(service.isInitialized, isFalse); + expect( + () => service.isEnabled('flag'), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('init()'), + ), + ), + ); + await service.init(); + await service.init(); + verify(provider.init).called(1); + expect(service.isInitialized, isTrue); + service.dispose(); + verify(provider.dispose).called(1); + expect(service.isInitialized, isFalse); + }); + + test('failed initialization propagates and can be retried', () async { + when(provider.init).thenThrow(StateError('offline')); + await expectLater(service.init(), throwsStateError); + expect(service.isInitialized, isFalse); + when(provider.init).thenAnswer((_) async {}); + await service.init(); + expect(service.isInitialized, isTrue); + }); + + test('typed reads preserve caller defaults', () async { + await service.init(); + when( + () => provider.getBool('b', defaultValue: true), + ).thenAnswer((_) async => true); + when( + () => provider.getString('s', defaultValue: 'fallback'), + ).thenAnswer((_) async => 'value'); + when( + () => provider.getInt('i', defaultValue: 3), + ).thenAnswer((_) async => 5); + when( + () => provider.getDouble('d', defaultValue: 1.5), + ).thenAnswer((_) async => 2.5); + when(() => provider.hasFlag('b')).thenAnswer((_) async => true); + expect(await service.hasFlag('b'), isTrue); + expect(await service.isEnabled('b', defaultValue: true), isTrue); + expect(await service.getConfig('s', defaultValue: 'fallback'), 'value'); + expect(await service.getIntConfig('i', defaultValue: 3), 5); + expect(await service.getDoubleConfig('d', defaultValue: 1.5), 2.5); + }); + + test( + 'module injection initializes and disposes the provider exactly once', + () async { + di.register(logger); + await flags.init(provider: provider); + expect(di.get().isInitialized, isTrue); + await di.reset(); + verify(provider.dispose).called(1); + }, + ); + + test('module initialization failures propagate', () async { + di.register(logger); + when(provider.init).thenThrow(StateError('offline')); + await expectLater(flags.init(provider: provider), throwsStateError); + }); + + testWidgets('wrapper caches reads until its inputs change', (tester) async { + await service.init(); + when( + () => provider.getBool('flag', defaultValue: false), + ).thenAnswer((_) async => true); + when( + () => provider.getBool('other', defaultValue: false), + ).thenAnswer((_) async => false); + Widget view(String key) => MaterialApp( + home: FeatureFlagWrapper( + service: service, + flagKey: key, + loading: const Text('Loading'), + builder: (_, value) => Text('Enabled: $value'), + ), + ); + await tester.pumpWidget(view('flag')); + expect(find.text('Loading'), findsOneWidget); + await tester.pumpAndSettle(); + expect(find.text('Enabled: true'), findsOneWidget); + await tester.pumpWidget(view('flag')); + await tester.pumpAndSettle(); + verify(() => provider.getBool('flag', defaultValue: false)).called(1); + await tester.pumpWidget(view('other')); + await tester.pumpAndSettle(); + expect(find.text('Enabled: false'), findsOneWidget); + }); + + testWidgets('wrapper uses fallback when the service is unavailable', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: FeatureFlagWrapper( + flagKey: 'flag', + defaultValue: true, + builder: (_, value) => Text('Enabled: $value'), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Enabled: true'), findsOneWidget); + }); + + testWidgets('wrapper resolves registered services and logs read failures', ( + tester, + ) async { + di.register(logger); + di.register(service); + await tester.pumpWidget( + MaterialApp( + home: FeatureFlagWrapper( + flagKey: 'flag', + defaultValue: true, + builder: (_, value) => Text('Enabled: $value'), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Enabled: true'), findsOneWidget); + verify(() => logger.e(any(), isA(), any())).called(1); + }); + + group('Firebase adapter', () { + late _RemoteConfig remote; + late FirebaseRemoteConfigProvider adapter; + setUp(() { + remote = _RemoteConfig(); + adapter = FirebaseRemoteConfigProvider( + remoteConfig: remote, + logger: logger, + ); + registerFallbackValue( + RemoteConfigSettings( + fetchTimeout: const Duration(seconds: 10), + minimumFetchInterval: const Duration(hours: 1), + ), + ); + when(() => remote.setConfigSettings(any())).thenAnswer((_) async {}); + when(() => remote.setDefaults(any())).thenAnswer((_) async {}); + when(remote.fetchAndActivate).thenAnswer((_) async => true); + when( + () => remote.lastFetchStatus, + ).thenReturn(RemoteConfigFetchStatus.success); + when(() => remote.lastFetchTime).thenReturn(DateTime(2026)); + }); + + test('configures Firebase and exposes update metadata', () async { + await adapter.init(); + verify(() => remote.setDefaults({})).called(1); + expect(adapter.config.defaultParameters, isEmpty); + expect( + adapter.config.minimumFetchInterval, + FeatureFlagsConfig.defaultMinimumFetchInterval, + ); + expect( + const FeatureFlagsConfig().fetchTimeout, + FeatureFlagsConfig.defaultFetchTimeout, + ); + expect(adapter.lastFetchTime, DateTime(2026)); + expect(adapter.lastFetchStatus, RemoteConfigFetchStatus.success); + adapter.dispose(); + }); + + test('local configuration failure propagates', () async { + when(() => remote.setDefaults(any())).thenThrow(StateError('invalid')); + await expectLater(adapter.init(), throwsStateError); + }); + + test('offline startup keeps defaults and completes module init', () async { + when(remote.fetchAndActivate).thenThrow(StateError('offline')); + di.register(logger); + await flags.init(provider: adapter); + expect(di.get().isInitialized, isTrue); + verify(() => logger.w(any(that: contains('fetch failed')))).called(1); + }); + + test('missing keys respect nonzero and true defaults', () async { + when( + () => remote.getValue(any()), + ).thenReturn(RemoteConfigValue([], ValueSource.valueStatic)); + expect(await adapter.getBool('missing', defaultValue: true), isTrue); + expect( + await adapter.getString('missing', defaultValue: 'fallback'), + 'fallback', + ); + expect(await adapter.getInt('missing', defaultValue: 9), 9); + expect(await adapter.getDouble('missing', defaultValue: 1.5), 1.5); + expect(await adapter.hasFlag('missing'), isFalse); + }); + + test( + 'configured false, zero and empty values remain valid values', + () async { + when( + () => remote.getValue(any()), + ).thenReturn(RemoteConfigValue([], ValueSource.valueRemote)); + when(() => remote.getBool(any())).thenReturn(false); + when(() => remote.getString(any())).thenReturn(''); + when(() => remote.getInt(any())).thenReturn(0); + when(() => remote.getDouble(any())).thenReturn(0); + expect(await adapter.getBool('key', defaultValue: true), isFalse); + expect(await adapter.getString('key', defaultValue: 'fallback'), ''); + expect(await adapter.getInt('key', defaultValue: 9), 0); + expect(await adapter.getDouble('key', defaultValue: 1.5), 0); + expect(await adapter.hasFlag('key'), isTrue); + }, + ); + + test('SDK read failures return defaults', () async { + when(() => remote.getValue(any())).thenThrow(StateError('unavailable')); + expect(await adapter.getBool('key', defaultValue: true), isTrue); + expect( + await adapter.getString('key', defaultValue: 'fallback'), + 'fallback', + ); + expect(await adapter.getInt('key', defaultValue: 9), 9); + expect(await adapter.getDouble('key', defaultValue: 1.5), 1.5); + expect(await adapter.hasFlag('key'), isFalse); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/localization/CLAUDE.md new file mode 100644 index 0000000..e796f84 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/CLAUDE.md @@ -0,0 +1,54 @@ +# Nonstop Example: `packages/localization` + +Type-safe user-facing strings (layer 0), generated by i69n from +`lib/messages.i69n.yaml`, plus the global `strings` accessor. It owns copy and +locale selection only: no widgets, no formatting helpers, no dependency on any +workspace package. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +Exported from `package:localization/localization.dart`. + +| Symbol | Kind | Notes | +|---|---|---| +| `strings` | global getter | `LocalizationProvider.messages`; use `strings..` | +| `Messages` | generated | Groups: `app`, `generic`, `common` (only `week`, `month`), `auth`, `profile`, `nav` (incl. `explore`), `notifications`, `errors`, `validation`, `developer` (`no_viewer`) | +| `Messages` | generated | e.g. `ErrorsMessages`, `ValidationMessages`; parameterised keys are methods (`errors.format_exception_message(code, postfix)`, `validation.invalid_key_config(of, key)`) | +| `LocalizationProvider` | static helper | `messages`, `currentLocale`, `supportedLocales`, `isLocaleSupported`, `getBestMatchingLocale(List)` | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/messages.i69n.yaml` | Source of every string, grouped by area | +| `lib/messages.i69n.dart` | Generated from the YAML. Never edit | +| `lib/src/localization_provider.dart` | Locale selection; always returns English `Messages` today | +| `lib/src/strings.dart` | Global `strings` getter | +| `lib/localization.dart` | Barrel | +| `build.yaml` | i69n builder options: `default_locale: en`, `locales: [en]`, `generate_for: lib/messages.i69n.yaml` | + +## Rules + +- Keys are snake_case and live under an existing group (`generic`, `errors`, `validation`, ...). A new top-level group becomes a new `Messages` class and getter on `Messages`. +- Parameterised messages use i69n's signature-as-key form in YAML: `name(String a, String b): "... $a ..."`. +- `LocalizationProvider` supports only `'en'`; `getBestMatchingLocale` returns the first supported language code, else `'en'` (so always `'en'` today). Do not add a locale to `supportedLocales` without adding its translation file and a real lookup. +- `core` reads `strings.errors.user_not_found` for `UserNotFoundException`; renaming a key breaks callers across the workspace. Grep before renaming or deleting. + +## Common changes + +- **Add a string:** add the key to the right group in `lib/messages.i69n.yaml`, run `dart run melos run generate:i69n` (build_runner + `dart format lib/messages.i69n.dart`), then use `strings..`. Commit the YAML and the regenerated `.i69n.dart` together. +- **Add a parameterised string:** `key(String x): "text $x"` in the YAML, regenerate, call `strings..key(x)`. +- **Add a locale:** add `lib/messages_.i69n.yaml`, list the code under `locales` and the file under `generate_for` in `build.yaml`, regenerate, then list the code in `supportedLocales` and pick its generated class in `messages` (the steps in the `LocalizationProvider` doc comment); extend `test/localization_test.dart` for the new match and fallback. + +## Tests + +`test/localization_test.dart` covers `getBestMatchingLocale` (supported, unsupported, empty list), `currentLocale`, `messages`, `supportedLocales` and `isLocaleSupported`. Generated `*.i69n.dart` is excluded from the coverage gate (`tool/coverage.dart`), so new keys need no tests; new logic in `lib/src/` does. + +Run: `dart run melos exec --scope=localization -- flutter test`. `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `messages.i69n.dart` is generated (`// GENERATED FILE, do not edit!`) and is skipped by both `tool/check.dart` and `tool/coverage.dart`. Never hand-edit it; `.claude/hooks/guard_generated.sh` blocks the edit. +- Shared button/state copy (`ok`, `cancel`, `save`, `try_again`, ...) lives in `generic`; `common` holds only `week` and `month`. Do not re-add duplicates to `common`. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/README.md b/packages/nonstop_cli/example/nonstop_example/packages/localization/README.md new file mode 100644 index 0000000..2c22cd2 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/README.md @@ -0,0 +1,163 @@ +# Localization + +Localization package for Nonstop Example using i69n for type-safe internationalization. + +[![nonstop_cli](https://img.shields.io/badge/started%20with-nonstop_cli-166C4E.svg?style=flat-square)](https://pub.dev/packages/nonstop_cli) +[![melos](https://img.shields.io/badge/maintained%20with-melos-f700ff.svg?style=flat-square)](https://github.com/invertase/melos) + +## Features ✨ + +- **Type-safe translations** - Generated classes with compile-time string validation +- **Easy integration** - Simple API with global `strings` access +- **Organized structure** - Categorized messages (auth, profile, generic, etc.) +- **Future-ready** - Built for multi-language support +- **Melos integration** - Seamless monorepo workflow + +## Installation 💻 + +Add to your `pubspec.yaml`: + +```yaml +dependencies: + localization: + path: ../packages/localization +``` + +## Usage 🚀 + +### Basic Usage + +```dart +import 'package:localization/localization.dart'; + +// Simple access to any string +Text(strings.auth.sign_in); // "Sign In" +Text(strings.generic.ok); // "OK" +Text(strings.profile.name); // "Name" +Text(strings.validation.required_field); // "This field is required" +``` + +### In Widgets + +```dart +class LoginButton extends StatelessWidget { + @override + Widget build(BuildContext context) { + return ElevatedButton( + onPressed: () => _login(), + child: Text(strings.auth.sign_in), + ); + } +} +``` + +### Error Handling + +```dart +void showError() { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(strings.errors.network_error)), + ); +} +``` + +### Form Validation + +```dart +String? validateEmail(String? value) { + if (value?.isEmpty ?? true) { + return strings.validation.required_field; + } + if (!value!.contains('@')) { + return strings.validation.invalid_email; + } + return null; +} +``` + +## Development 🛠️ + +### Adding New Strings + +1. Edit `lib/messages.i69n.yaml`: +```yaml +new_category: + new_message: "New Message Text" + another_message: "Another Message" +``` + +2. Generate code: +```bash +# From the monorepo root +melos run generate:i69n + +# Or from this package +dart run build_runner build --delete-conflicting-outputs +``` + +3. Use the new strings: +```dart +Text(strings.new_category.new_message); // "New Message Text" +``` + +### Testing + +```bash +# Run tests +flutter test + +# Run with coverage +flutter test --coverage +``` + +### Linting + +```bash +# From monorepo root +melos run lint + +# Or from this package +dart format . && dart analyze --fatal-infos . +``` + +## Advanced Usage 🔧 + +### Using LocalizationProvider + +```dart +import 'package:localization/localization.dart'; + +// Check supported locales +if (LocalizationProvider.isLocaleSupported('en')) { + // Handle supported locale +} + +``` + +### Adding a Locale + +Only English ships today. To add one (e.g. Spanish): + +1. Add `lib/messages_es.i69n.yaml` with the same keys. +2. Add `es` to `locales` in `build.yaml` and run `melos run generate:i69n`. +3. Add `es` to `LocalizationProvider.supportedLocales` and switch on the + locale where `LocalizationProvider.messages` is chosen. + +## Package Structure 📁 + +``` +packages/localization/ +├── lib/ +│ ├── localization.dart # Main export file +│ ├── messages.i69n.dart # Generated i69n classes +│ ├── messages.i69n.yaml # Translation source +│ └── src/ +│ ├── localization_provider.dart # Advanced utilities +│ └── strings.dart # Global strings instance +├── test/ +│ └── localization_test.dart # Comprehensive tests +├── build.yaml # i69n build configuration +└── pubspec.yaml # Package dependencies +``` + +[flutter_install_link]: https://docs.flutter.dev/get-started/install diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/build.yaml b/packages/nonstop_cli/example/nonstop_example/packages/localization/build.yaml new file mode 100644 index 0000000..cf0faee --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/build.yaml @@ -0,0 +1,10 @@ +targets: + $default: + builders: + i69n: + options: + default_locale: en + locales: + - en + generate_for: + - lib/messages.i69n.yaml \ No newline at end of file diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/localization.dart b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/localization.dart new file mode 100644 index 0000000..9b040cf --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/localization.dart @@ -0,0 +1,14 @@ +/// Nonstop Example Localization Package +/// +/// This package provides internationalization support using i69n. +/// It contains generated message classes and utilities for managing translations. +library; + +// Export generated i69n messages +export 'messages.i69n.dart'; + +// Export localization utilities +export 'src/localization_provider.dart'; + +// Export global strings instance for easy access +export 'src/strings.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.dart b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.dart new file mode 100644 index 0000000..2cf3c76 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.dart @@ -0,0 +1,590 @@ +// ignore_for_file: unused_element, unused_field, camel_case_types, annotate_overrides, prefer_single_quotes +// GENERATED FILE, do not edit! +// dart format off +import 'package:i69n/i69n.dart' as i69n; + +String get _languageCode => 'en'; +String get _localeName => 'en'; + +String _plural(int count, + {String? zero, + String? one, + String? two, + String? few, + String? many, + String? other}) => + i69n.plural(count, _languageCode, + zero: zero, one: one, two: two, few: few, many: many, other: other); +String _ordinal(int count, + {String? zero, + String? one, + String? two, + String? few, + String? many, + String? other}) => + i69n.ordinal(count, _languageCode, + zero: zero, one: one, two: two, few: few, many: many, other: other); +String _cardinal(int count, + {String? zero, + String? one, + String? two, + String? few, + String? many, + String? other}) => + i69n.cardinal(count, _languageCode, + zero: zero, one: one, two: two, few: few, many: many, other: other); + +class Messages implements i69n.I69nMessageBundle { + const Messages(); + AppMessages get app => AppMessages(this); + GenericMessages get generic => GenericMessages(this); + CommonMessages get common => CommonMessages(this); + AuthMessages get auth => AuthMessages(this); + ProfileMessages get profile => ProfileMessages(this); + NavMessages get nav => NavMessages(this); + NotificationsMessages get notifications => NotificationsMessages(this); + ErrorsMessages get errors => ErrorsMessages(this); + ValidationMessages get validation => ValidationMessages(this); + DeveloperMessages get developer => DeveloperMessages(this); + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'app': + return app; + case 'generic': + return generic; + case 'common': + return common; + case 'auth': + return auth; + case 'profile': + return profile; + case 'nav': + return nav; + case 'notifications': + return notifications; + case 'errors': + return errors; + case 'validation': + return validation; + case 'developer': + return developer; + default: + return key; + } + } +} + +class AppMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const AppMessages(this._parent); + String get name => "Nonstop Example"; + String get description => "Reference project generated by nonstop_cli."; + String get welcome_to_app => "Welcome to Nonstop Example!"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'name': + return name; + case 'description': + return description; + case 'welcome_to_app': + return welcome_to_app; + default: + return key; + } + } +} + +class GenericMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const GenericMessages(this._parent); + String get ok => "OK"; + String get cancel => "Cancel"; + String get save => "Save"; + String get delete => "Delete"; + String get edit => "Edit"; + String get update => "Update"; + String get submit => "Submit"; + String get close => "Close"; + String get back => "Back"; + String get next => "Next"; + String get previous => "Previous"; + String get done => "Done"; + String get loading => "Loading..."; + String get error => "Error"; + String get success => "Success"; + String get warning => "Warning"; + String get info => "Info"; + String get retry => "Retry"; + String get refresh => "Refresh"; + String get yes => "Yes"; + String get no => "No"; + String get add => "+ Add"; + String get try_again => "Try Again"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'ok': + return ok; + case 'cancel': + return cancel; + case 'save': + return save; + case 'delete': + return delete; + case 'edit': + return edit; + case 'update': + return update; + case 'submit': + return submit; + case 'close': + return close; + case 'back': + return back; + case 'next': + return next; + case 'previous': + return previous; + case 'done': + return done; + case 'loading': + return loading; + case 'error': + return error; + case 'success': + return success; + case 'warning': + return warning; + case 'info': + return info; + case 'retry': + return retry; + case 'refresh': + return refresh; + case 'yes': + return yes; + case 'no': + return no; + case 'add': + return add; + case 'try_again': + return try_again; + default: + return key; + } + } +} + +class CommonMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const CommonMessages(this._parent); + String get week => "Week"; + String get month => "Month"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'week': + return week; + case 'month': + return month; + default: + return key; + } + } +} + +class AuthMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const AuthMessages(this._parent); + String get register => "Register"; + String get sign_in => "Sign In"; + String get sign_out => "Sign Out"; + String get dont_have_account => "Don't have an account? "; + String get already_have_account => "Already have an account? "; + String get sign_out_confirmation => "Are you sure you want to sign out?"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'register': + return register; + case 'sign_in': + return sign_in; + case 'sign_out': + return sign_out; + case 'dont_have_account': + return dont_have_account; + case 'already_have_account': + return already_have_account; + case 'sign_out_confirmation': + return sign_out_confirmation; + default: + return key; + } + } +} + +class ProfileMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const ProfileMessages(this._parent); + String get profile => "Profile"; + String get settings => "Settings"; + String get account => "Account"; + String get personal_info => "Personal Information"; + String get privacy_settings => "Privacy Settings"; + String get name => "Name"; + String get email_address => "Email Address"; + String get phone_number => "Phone Number"; + String get date_of_birth => "Date of Birth"; + String get delete_confirmation => "Delete Confirmation"; + String get delete_confirmation_message => + "Are you sure you want to delete this item? This action cannot be undone."; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'profile': + return profile; + case 'settings': + return settings; + case 'account': + return account; + case 'personal_info': + return personal_info; + case 'privacy_settings': + return privacy_settings; + case 'name': + return name; + case 'email_address': + return email_address; + case 'phone_number': + return phone_number; + case 'date_of_birth': + return date_of_birth; + case 'delete_confirmation': + return delete_confirmation; + case 'delete_confirmation_message': + return delete_confirmation_message; + default: + return key; + } + } +} + +class NavMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const NavMessages(this._parent); + String get home => "Home"; + String get dashboard => "Dashboard"; + String get explore => "Explore"; + String get explore_placeholder => + "Your second tab. Replace this with a real feature."; + String get profile => "Profile"; + String get settings => "Settings"; + String get notifications => "Notifications"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'home': + return home; + case 'dashboard': + return dashboard; + case 'explore': + return explore; + case 'explore_placeholder': + return explore_placeholder; + case 'profile': + return profile; + case 'settings': + return settings; + case 'notifications': + return notifications; + default: + return key; + } + } +} + +class NotificationsMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const NotificationsMessages(this._parent); + String get title => "Notifications"; + String get mark_as_read => "Mark as read"; + String get mark_all_read => "Mark all as read"; + String get delete => "Delete"; + String get filter_all => "All"; + String get filter_unread => "Unread"; + String get filter_read => "Read"; + String get type_reminder => "Reminder"; + String get type_alert => "Alert"; + String get type_promotion => "Promotion"; + String get type_system => "System"; + String get type_custom => "Custom"; + String get empty_title => "No notifications"; + String get empty_description => + "You're all caught up! New notifications will appear here."; + String get delete_confirmation_title => "Delete notification?"; + String get delete_confirmation_message => + "This notification will be permanently removed from your list."; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'title': + return title; + case 'mark_as_read': + return mark_as_read; + case 'mark_all_read': + return mark_all_read; + case 'delete': + return delete; + case 'filter_all': + return filter_all; + case 'filter_unread': + return filter_unread; + case 'filter_read': + return filter_read; + case 'type_reminder': + return type_reminder; + case 'type_alert': + return type_alert; + case 'type_promotion': + return type_promotion; + case 'type_system': + return type_system; + case 'type_custom': + return type_custom; + case 'empty_title': + return empty_title; + case 'empty_description': + return empty_description; + case 'delete_confirmation_title': + return delete_confirmation_title; + case 'delete_confirmation_message': + return delete_confirmation_message; + default: + return key; + } + } +} + +class ErrorsMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const ErrorsMessages(this._parent); + String get network_error => "Network error. Please check your connection."; + String get unknown_error => "An unknown error occurred."; + String get validation_error => "Please check your input and try again."; + String get server_error => "Server error. Please try again later."; + String get default_error_message => + "Oops! Something went wrong. Please try again."; + String get user_not_found => "User not found. Please check your credentials."; + String get default_error_description => + "We encountered an error while processing your request. We apologize for the inconvenience. Please try again later or contact support if the issue persists."; + String get page_not_found => "Page Not Found"; + String get page_not_found_description => + "The page you are looking for does not exist."; + String get unexpected_error => "An unexpected error occurred."; + String get redirect_error => "Redirect Error"; + String get bad_request => "Invalid request. Please check your input."; + String get unauthorized => "Authentication required. Please sign in again."; + String get forbidden => "Access denied. You don't have permission."; + String get not_found => "Requested resource not found."; + String get conflict => "Data conflict. Please refresh and try again."; + String get unprocessable_entity => + "Invalid data format. Please check your input."; + String get internal_server_error => "Server error. Please try again later."; + String get connection_timeout => + "Connection timeout. Please check your internet."; + String get receive_timeout => "Request timeout. Please try again."; + String get send_timeout => "Upload timeout. Please try again."; + String get no_internet => + "No internet connection. Please check your network."; + String get unknown_network => "Network error occurred. Please try again."; + String format_exception_message(String code, String postfix) => + "This data is wearing the wrong costume, I don't recognize it [$code] $postfix"; + String type_error_message(String code, String postfix) => + "This data is not what I expected, I can't process it [$code] $postfix"; + String index_error_message(String code, String postfix) => + "Hmm, I can't seem to find that item in the list [$code] $postfix"; + String range_error_message(String code, String postfix) => + "Oops! That number is way out of my comfort zone [$code] $postfix"; + String argument_error_message(String code, String postfix) => + "Hey! Something's not right with what you gave me [$code] $postfix"; + String state_error_message(String code, String postfix) => + "I'm a bit confused about what I should be doing right now [$code] $postfix"; + String unimplemented_error_message(String code, String postfix) => + "This feature is still under construction [$code] $postfix"; + String unsupported_error_message(String code, String postfix) => + "Sorry, I don't know how to do that yet [$code] $postfix"; + String concurrent_modification_error_message(String code, String postfix) => + "Whoa! Too many things happening at once [$code] $postfix"; + String out_of_memory_error_message(String code, String postfix) => + "My brain is full! Need to clear some space [$code] $postfix"; + String stack_overflow_error_message(String code, String postfix) => + "I'm stuck in a loop and getting dizzy [$code] $postfix"; + String unknown_error_message(String code, String postfix) => + "Something unexpected happened, but don't worry [$code] $postfix"; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'network_error': + return network_error; + case 'unknown_error': + return unknown_error; + case 'validation_error': + return validation_error; + case 'server_error': + return server_error; + case 'default_error_message': + return default_error_message; + case 'user_not_found': + return user_not_found; + case 'default_error_description': + return default_error_description; + case 'page_not_found': + return page_not_found; + case 'page_not_found_description': + return page_not_found_description; + case 'unexpected_error': + return unexpected_error; + case 'redirect_error': + return redirect_error; + case 'bad_request': + return bad_request; + case 'unauthorized': + return unauthorized; + case 'forbidden': + return forbidden; + case 'not_found': + return not_found; + case 'conflict': + return conflict; + case 'unprocessable_entity': + return unprocessable_entity; + case 'internal_server_error': + return internal_server_error; + case 'connection_timeout': + return connection_timeout; + case 'receive_timeout': + return receive_timeout; + case 'send_timeout': + return send_timeout; + case 'no_internet': + return no_internet; + case 'unknown_network': + return unknown_network; + case 'format_exception_message': + return format_exception_message; + case 'type_error_message': + return type_error_message; + case 'index_error_message': + return index_error_message; + case 'range_error_message': + return range_error_message; + case 'argument_error_message': + return argument_error_message; + case 'state_error_message': + return state_error_message; + case 'unimplemented_error_message': + return unimplemented_error_message; + case 'unsupported_error_message': + return unsupported_error_message; + case 'concurrent_modification_error_message': + return concurrent_modification_error_message; + case 'out_of_memory_error_message': + return out_of_memory_error_message; + case 'stack_overflow_error_message': + return stack_overflow_error_message; + case 'unknown_error_message': + return unknown_error_message; + default: + return key; + } + } +} + +class ValidationMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const ValidationMessages(this._parent); + String get required_field => "This field is required"; + String get invalid_email => "Please enter a valid email address"; + String get password_too_short => "Password must be at least 8 characters"; + String get passwords_dont_match => "Passwords do not match"; + String invalid_key_config(String of, String key) => + "Invalid configuration for $key in $of. Please check your settings."; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'required_field': + return required_field; + case 'invalid_email': + return invalid_email; + case 'password_too_short': + return password_too_short; + case 'passwords_dont_match': + return passwords_dont_match; + case 'invalid_key_config': + return invalid_key_config; + default: + return key; + } + } +} + +class DeveloperMessages implements i69n.I69nMessageBundle { + final Messages _parent; + const DeveloperMessages(this._parent); + String get no_viewer => "This logger has no interactive viewer."; + Object operator [](String key) { + var index = key.indexOf('.'); + if (index > 0) { + return (this[key.substring(0, index)] + as i69n.I69nMessageBundle)[key.substring(index + 1)]; + } + switch (key) { + case 'no_viewer': + return no_viewer; + default: + return key; + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.yaml b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.yaml new file mode 100644 index 0000000..660d67d --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/messages.i69n.yaml @@ -0,0 +1,147 @@ +# Nonstop Example - Internationalization Messages +# Base translations for the application + +# application metadata +app: + name: "Nonstop Example" + description: "Reference project generated by nonstop_cli." + welcome_to_app: "Welcome to Nonstop Example!" + +# Common/Generic messages +generic: + ok: "OK" + cancel: "Cancel" + save: "Save" + delete: "Delete" + edit: "Edit" + update: "Update" + submit: "Submit" + close: "Close" + back: "Back" + next: "Next" + previous: "Previous" + done: "Done" + loading: "Loading..." + error: "Error" + success: "Success" + warning: "Warning" + info: "Info" + retry: "Retry" + refresh: "Refresh" + yes: "Yes" + no: "No" + add: "+ Add" + try_again: "Try Again" + +# Common messages (used for consistency across modules) +common: + week: "Week" + month: "Month" + +# Authentication +auth: + register: "Register" + sign_in: "Sign In" + sign_out: "Sign Out" + dont_have_account: "Don't have an account? " + already_have_account: "Already have an account? " + sign_out_confirmation: "Are you sure you want to sign out?" + +# Profile +profile: + profile: "Profile" + settings: "Settings" + account: "Account" + personal_info: "Personal Information" + privacy_settings: "Privacy Settings" + name: "Name" + email_address: "Email Address" + phone_number: "Phone Number" + date_of_birth: "Date of Birth" + delete_confirmation: "Delete Confirmation" + delete_confirmation_message: "Are you sure you want to delete this item? This action cannot be undone." + +nav: + home: "Home" + dashboard: "Dashboard" + explore: "Explore" + explore_placeholder: "Your second tab. Replace this with a real feature." + profile: "Profile" + settings: "Settings" + notifications: "Notifications" + +# Notifications +notifications: + title: "Notifications" + mark_as_read: "Mark as read" + mark_all_read: "Mark all as read" + delete: "Delete" + + # Filter tabs + filter_all: "All" + filter_unread: "Unread" + filter_read: "Read" + + # Notification types + type_reminder: "Reminder" + type_alert: "Alert" + type_promotion: "Promotion" + type_system: "System" + type_custom: "Custom" + + # Empty states + empty_title: "No notifications" + empty_description: "You're all caught up! New notifications will appear here." + + # Delete confirmation + delete_confirmation_title: "Delete notification?" + delete_confirmation_message: "This notification will be permanently removed from your list." + +# Errors +errors: + network_error: "Network error. Please check your connection." + unknown_error: "An unknown error occurred." + validation_error: "Please check your input and try again." + server_error: "Server error. Please try again later." + default_error_message: "Oops! Something went wrong. Please try again." + user_not_found: "User not found. Please check your credentials." + default_error_description: "We encountered an error while processing your request. We apologize for the inconvenience. Please try again later or contact support if the issue persists." + page_not_found: "Page Not Found" + page_not_found_description: "The page you are looking for does not exist." + unexpected_error: "An unexpected error occurred." + redirect_error: "Redirect Error" + bad_request: "Invalid request. Please check your input." + unauthorized: "Authentication required. Please sign in again." + forbidden: "Access denied. You don't have permission." + not_found: "Requested resource not found." + conflict: "Data conflict. Please refresh and try again." + unprocessable_entity: "Invalid data format. Please check your input." + internal_server_error: "Server error. Please try again later." + connection_timeout: "Connection timeout. Please check your internet." + receive_timeout: "Request timeout. Please try again." + send_timeout: "Upload timeout. Please try again." + no_internet: "No internet connection. Please check your network." + unknown_network: "Network error occurred. Please try again." + format_exception_message(String code, String postfix): "This data is wearing the wrong costume, I don't recognize it [$code] $postfix" + type_error_message(String code, String postfix): "This data is not what I expected, I can't process it [$code] $postfix" + index_error_message(String code, String postfix): "Hmm, I can't seem to find that item in the list [$code] $postfix" + range_error_message(String code, String postfix): "Oops! That number is way out of my comfort zone [$code] $postfix" + argument_error_message(String code, String postfix): "Hey! Something's not right with what you gave me [$code] $postfix" + state_error_message(String code, String postfix): "I'm a bit confused about what I should be doing right now [$code] $postfix" + unimplemented_error_message(String code, String postfix): "This feature is still under construction [$code] $postfix" + unsupported_error_message(String code, String postfix): "Sorry, I don't know how to do that yet [$code] $postfix" + concurrent_modification_error_message(String code, String postfix): "Whoa! Too many things happening at once [$code] $postfix" + out_of_memory_error_message(String code, String postfix): "My brain is full! Need to clear some space [$code] $postfix" + stack_overflow_error_message(String code, String postfix): "I'm stuck in a loop and getting dizzy [$code] $postfix" + unknown_error_message(String code, String postfix): "Something unexpected happened, but don't worry [$code] $postfix" +# Validation messages +validation: + required_field: "This field is required" + invalid_email: "Please enter a valid email address" + password_too_short: "Password must be at least 8 characters" + passwords_dont_match: "Passwords do not match" + invalid_key_config(String of, String key): "Invalid configuration for $key in $of. Please check your settings." + +# Developer tools +developer: + no_viewer: "This logger has no interactive viewer." diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/localization_provider.dart b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/localization_provider.dart new file mode 100644 index 0000000..9e424c3 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/localization_provider.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; +import 'package:localization/messages.i69n.dart'; + +/// Provides localization utilities for the Nonstop Example application. +/// +/// Only English ships today. To add a locale, add +/// `messages_.i69n.yaml`, list the code under `locales` in `build.yaml`, +/// regenerate, add it to [supportedLocales] and pick its generated messages +/// class in [messages]. +class LocalizationProvider { + /// The messages for the current (English) locale. + static Messages get messages => const Messages(); + + /// The current locale. + static String get currentLocale => 'en'; + + /// Locales with generated messages. + static List get supportedLocales => ['en']; + + /// Check if a locale is supported + static bool isLocaleSupported(String locale) { + return supportedLocales.contains(locale); + } + + /// Get the best matching locale from a list of preferred locales + static String getBestMatchingLocale(List preferredLocales) { + for (final locale in preferredLocales) { + if (isLocaleSupported(locale.languageCode)) { + return locale.languageCode; + } + } + return 'en'; // Default to English + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/strings.dart b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/strings.dart new file mode 100644 index 0000000..fdf5e28 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/lib/src/strings.dart @@ -0,0 +1,14 @@ +import 'package:localization/localization.dart'; + +/// Global strings instance for easy access throughout the application +/// +/// Usage: +/// ```dart +/// import 'package:localization/localization.dart'; +/// +/// // Access strings easily +/// Text(strings.auth.sign_in); +/// Text(strings.generic.ok); +/// Text(strings.profile.name); +/// ``` +Messages get strings => LocalizationProvider.messages; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/localization/pubspec.yaml new file mode 100644 index 0000000..1b687a5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/pubspec.yaml @@ -0,0 +1,23 @@ +name: localization +description: "Type-safe strings for Nonstop Example, generated from YAML with i69n." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + i69n: ^3.1.0 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + build_runner: ^2.4.15 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/localization/test/localization_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/localization/test/localization_test.dart new file mode 100644 index 0000000..07382e0 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/localization/test/localization_test.dart @@ -0,0 +1,40 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/material.dart'; +import 'package:localization/localization.dart'; + +void main() { + test('locale matching selects supported language or defaults to English', () { + expect( + LocalizationProvider.getBestMatchingLocale([ + const Locale('es'), + const Locale('en', 'US'), + ]), + 'en', + ); + expect( + LocalizationProvider.getBestMatchingLocale([const Locale('es')]), + 'en', + ); + expect(LocalizationProvider.getBestMatchingLocale([]), 'en'); + }); + group('LocalizationProvider Tests', () { + test('should default to English', () { + expect(LocalizationProvider.currentLocale, 'en'); + }); + + test('should return Messages instance', () { + final messages = LocalizationProvider.messages; + expect(messages, isA()); + }); + + test('should return supported locales', () { + final locales = LocalizationProvider.supportedLocales; + expect(locales, contains('en')); + }); + + test('should check if locale is supported', () { + expect(LocalizationProvider.isLocaleSupported('en'), true); + expect(LocalizationProvider.isLocaleSupported('es'), false); + }); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/network/CLAUDE.md new file mode 100644 index 0000000..4c59012 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/CLAUDE.md @@ -0,0 +1,73 @@ +# Nonstop Example: `packages/network` + +Owns the HTTP layer: the Dio client, auth and logging interceptors, the +`success`/`error` response envelope and the mapping of transport failures to +typed `NetworkException`s. It does not own tokens or sign-in (it consumes an +`AuthTokenProvider` supplied by the app or an auth feature), endpoints or +feature DTOs. Layer 2: depends on `core`, `di`, `localization`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | +|---|---| +| `NetworkClient` / `DioNetworkClient(config, logger:, dio:, authTokenProvider:, useAuthentication:)` | `abstract interface class` / Dio implementation: `get`/`post`/`put`/`patch`/`delete(path, fromJsonT:)`, `handleResponse`, `handleSuccessResponse`, `dispose` | +| `init({required config, useAuthentication = true})`, `registerNetworkWithDI(config, {useAuthentication, dio})` | Registers `NetworkClient` (with `dispose`) and the caller's own `NetworkConfig` instance | +| `NetworkConfig` (interface) / `DefaultNetworkConfig` | `baseUrl`, 30s timeouts, `defaultHeaders`, `enableLogging`, `authTokenProvider` | +| `AuthTokenProvider` | `abstract interface class` token contract implemented outside this package | +| `AuthInterceptor`, `LoggingInterceptor` | Dio interceptors (exported) | +| `NetworkResponse`, `SuccessResponse`, `ErrorResponse`, `ErrorDetails`, `Pagination` | Envelope models (`json_serializable`) | +| `NetworkException` + `BadRequest`/`Unauthorized`/`Forbidden`/`NotFound`/`Conflict`/`UnprocessableEntity`/`InternalServer`/`ConnectionTimeout`/`ReceiveTimeout`/`SendTimeout`/`NoInternetConnection`/`UnknownNetworkException` | Typed failures, localized `displayMessage`; timeout and no-internet exceptions have a null `statusCode` | +| `ErrorMessageExtension.message()`, `ErrorMessageOnError`, `ErrorCodes` | Any error to a localized user message | +| `ApiUrlConfig`, `NetworkApi` | Base classes for feature API definitions | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/network.dart` | Barrel, `init`, `registerNetworkWithDI` (auth provider resolution) | +| `lib/src/client/` | `NetworkClient` contract, `DioNetworkClient` (envelope decoding, error mapping) | +| `lib/src/interceptors/` | `AuthInterceptor` (bearer + single retry), `LoggingInterceptor` (method + path only) | +| `lib/src/config/` | `NetworkConfig`, `DefaultNetworkConfig` | +| `lib/src/auth/` | `AuthTokenProvider` contract | +| `lib/src/models/` | Envelope models; `network_response.g.dart` is generated | +| `lib/src/exceptions/` | `network_exceptions.dart` | +| `lib/src/api/` | `ApiUrlConfig`, `NetworkApi` | +| `lib/src/utils/extensions/` | `error_message_extension.dart` | + +## Rules + +- **Auth origin.** `AuthInterceptor.onRequest` adds `Authorization: Bearer` only when the request origin equals `baseUrl`'s origin and the caller set no `authorization` header (case-insensitive). Absolute URLs to other hosts go out bare. +- **Token failures never fail a request.** If `getValidToken()` throws, the error is logged and the request proceeds unauthenticated. +- **Retry.** Only on 401, only for requests the interceptor authorized (`nonstop.auth.managed`), at most once (`nonstop.auth.retried`). Concurrent 401s share one `refreshToken()` future. `FormData` is `clone()`d for the retry; `Stream` bodies are never retried. A null or failed refresh surfaces the original `UnauthorizedException`. +- **Logs.** `LoggingInterceptor` logs method, status and `uri.path` only; never headers, query values or bodies (asserted by a test). Keep it that way when adding logging. +- **Failure policy.** Non-2xx and transport errors throw a typed `NetworkException` from `Never _handleError` (never returned); non-Dio errors become `UnknownNetworkException`. A 2xx body with `success: false` returns an `ErrorResponse`; `handleResponse`/`handleSuccessResponse` turn it into `UnknownNetworkException`. Envelope `statusCode`/`headers` fields are overwritten by the real HTTP values. Unparseable bodies return `ErrorResponse` with code `PARSE_ERROR`. +- **Injected:** `Logger` and `Dio` (tests pass `Dio()..httpClientAdapter = fake`). `dispose()` closes the Dio transport. +- `init` without `config.authTokenProvider` falls back to `di.get()` when `di.has()`; `useAuthentication: false` strips any provider. The config is registered as passed, so custom `NetworkConfig` implementations are preserved. +- No talker dependency: logging goes through the injected core `Logger` only. + +## Common changes + +- **Add an interceptor:** add it under `lib/src/interceptors/`, export it from `interceptors/index.dart`, add it in `DioNetworkClient._setupDio`. Order matters: auth is added before logging. Test through `DioNetworkClient` with the `_Adapter` fake in `test/dio_network_client_test.dart`. +- **Map a new status code:** add a subclass in `network_exceptions.dart` with a `strings.errors.*` message (new key in `packages/localization`), add the case in `_mapDioException`, add the row to the status table test in `dio_network_client_test.dart` and to the list in `test/models_test.dart`. +- **Change an envelope model:** edit `network_response.dart`, run `dart run melos run generate`, extend `test/models_test.dart`. + +## Tests + +| File | Covers | +|---|---| +| `test/dio_network_client_test.dart` | Verbs, envelope decoding, status/transport mapping, auth origin, refresh sharing, retry limits, multipart/stream, log redaction, `init` provider resolution, dispose | +| `test/response_contract_test.dart` | Non-Dio errors become `UnknownNetworkException`; handler branches (mocktail `Dio`) | +| `test/models_test.dart` | Exception messages, `ErrorMessageExtension`, JSON round-trips, `NetworkApi` | +| `test/network_test.dart` | `DefaultNetworkConfig` defaults | + +Doubles: `_Adapter` (`HttpClientAdapter`), `_Tokens`/`_DelayedTokens` (`AuthTokenProvider`), `_Logger` recording messages. + +`dart run melos exec --scope=network -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `network_response.g.dart` is generated: `dart run melos run generate`. +- `ErrorResponse.toJson()` keeps `error` as an object, not a map; tests reassign it before `fromJson`. +- `sendTimeout` is dropped on web (`kIsWeb`) because Dio rejects it without a body. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/README.md b/packages/nonstop_cli/example/nonstop_example/packages/network/README.md new file mode 100644 index 0000000..623b711 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/README.md @@ -0,0 +1,72 @@ +# network + +HTTP layer for Nonstop Example: a Dio-backed `NetworkClient`, an auth +interceptor, a privacy-safe logging interceptor, typed response envelopes and a +closed set of `NetworkException`s. + +## Initialise + +```dart +import 'package:network/network.dart' as network; + +await network.init( + config: network.DefaultNetworkConfig(baseUrl: Environment.baseUrl), +); + +final client = di.get(); +``` + +`init` registers `NetworkClient` and the `NetworkConfig` instance you passed +(your own `NetworkConfig` implementation is kept as-is). A `Logger` must already +be registered. + +Credentials: with `useAuthentication: true` (the default) the client uses +`config.authTokenProvider`, or otherwise an `AuthTokenProvider` registered in DI +(the auth feature registers one). Pass `useAuthentication: false` for an +unauthenticated client. + +## Configure + +| `DefaultNetworkConfig` field | Default | +| --- | --- | +| `baseUrl` | required | +| `connectTimeout` / `receiveTimeout` / `sendTimeout` | 30 s (send timeout is not applied on web) | +| `defaultHeaders` | `{}` | +| `enableLogging` | `true` | +| `authTokenProvider` | `null` (resolved from DI, see above) | + +## Make requests + +```dart +final response = await client.get( + '/users/me', + fromJsonT: (json) => User.fromJson(json! as Map), +); +final user = client.handleResponse(response); // throws on ErrorResponse +``` + +Bodies shaped `{success: true|false, ...}` decode into `SuccessResponse` / +`ErrorResponse`; any other body is passed to `fromJsonT` as a success. + +## Errors + +Transport and HTTP failures are thrown as a `NetworkException` subtype: + +| Cause | Exception | `statusCode` | +| --- | --- | --- | +| 400 / 401 / 403 / 404 / 409 / 422 | `BadRequest` / `Unauthorized` / `Forbidden` / `NotFound` / `Conflict` / `UnprocessableEntity` `Exception` | the HTTP status | +| 500, 502, 503, 504 | `InternalServerException` | 500 | +| connect / receive / send timeout | `ConnectionTimeout` / `ReceiveTimeout` / `SendTimeout` `Exception` | `null` | +| socket failure | `NoInternetConnectionException` | `null` | +| anything else | `UnknownNetworkException` | the HTTP status, if any | + +`displayMessage` gives a localised message; `error.message()` (from +`ErrorMessageExtension`) turns any thrown object into user-facing text. + +## Privacy rules + +- The logging interceptor records only the HTTP method, path and status code: + never headers, query strings or bodies. +- The auth interceptor adds `Authorization: Bearer ` only to requests on + the configured base URL's origin, never overrides a caller-supplied + `Authorization` header, and retries a 401 at most once after a token refresh. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/network.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/network.dart new file mode 100644 index 0000000..df98f6e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/network.dart @@ -0,0 +1,63 @@ +library; + +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:dio/dio.dart'; +import 'package:network/src/auth/index.dart'; +import 'package:network/src/client/index.dart'; +import 'package:network/src/config/index.dart'; + +export 'src/api/index.dart'; +export 'src/auth/index.dart'; +export 'src/client/index.dart'; +export 'src/config/index.dart'; +export 'src/exceptions/index.dart'; +export 'src/interceptors/index.dart'; +export 'src/models/index.dart'; +export 'src/utils/index.dart'; + +Future init({ + required NetworkConfig config, + bool useAuthentication = true, +}) async { + await registerNetworkWithDI(config, useAuthentication: useAuthentication); + final logger = di.get(); + logger.i('Network module initialized with base URL: ${config.baseUrl}'); +} + +/// Registers [NetworkClient] and the caller's own [config] instance. +/// +/// When [useAuthentication] is true, credentials come from +/// [NetworkConfig.authTokenProvider] or, failing that, from an +/// [AuthTokenProvider] registered in DI (for example by the auth feature). +Future registerNetworkWithDI( + NetworkConfig config, { + bool useAuthentication = true, + Dio? dio, +}) async { + final logger = di.get(); + + final authTokenProvider = !useAuthentication + ? null + : config.authTokenProvider ?? + (di.has() ? di.get() : null); + + final networkClient = DioNetworkClient( + config, + logger: logger, + dio: dio, + authTokenProvider: authTokenProvider, + useAuthentication: useAuthentication, + ); + di.register( + networkClient, + dispose: (client) => client.dispose(), + ); + di.register(config); + + logger.i( + authTokenProvider != null + ? 'Network client registered with authentication support' + : 'Network client registered without authentication', + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/index.dart new file mode 100644 index 0000000..6a4ecae --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/index.dart @@ -0,0 +1 @@ +export 'network_api.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/network_api.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/network_api.dart new file mode 100644 index 0000000..66a684c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/api/network_api.dart @@ -0,0 +1,13 @@ +abstract class ApiUrlConfig { + final String pathPrefix; + + const ApiUrlConfig({required this.pathPrefix}); +} + +abstract class NetworkApi { + final T urlConfig; + + const NetworkApi({required this.urlConfig}); + + Map get headers; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/auth_token_provider.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/auth_token_provider.dart new file mode 100644 index 0000000..251cd5f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/auth_token_provider.dart @@ -0,0 +1,28 @@ +/// Supplies session credentials to the network layer. +abstract interface class AuthTokenProvider { + /// Gets a valid authentication token + /// Returns null if user is not authenticated + Future getValidToken(); + + /// Gets the current token without validation + /// Returns null if no token is available + String? getCurrentToken(); + + /// Stream of authentication token changes + /// Emits new tokens when authentication state changes + Stream get tokenStream; + + /// Forces a token refresh + /// Returns the new token or null if refresh fails + Future refreshToken(); + + /// Checks if the user is currently authenticated + bool get isAuthenticated; + + /// Checks if the current token is expired + /// Returns true if token is null or expired + bool get isTokenExpired; + + /// Sign out the current user + Future signOut(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/index.dart new file mode 100644 index 0000000..5f2f025 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/auth/index.dart @@ -0,0 +1 @@ +export 'auth_token_provider.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/dio_network_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/dio_network_client.dart new file mode 100644 index 0000000..79c4b88 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/dio_network_client.dart @@ -0,0 +1,348 @@ +import 'dart:io'; + +import 'package:core/core.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; +import 'package:localization/localization.dart'; +import 'package:network/src/auth/auth_token_provider.dart'; +import 'package:network/src/client/network_client.dart'; +import 'package:network/src/config/network_config.dart'; +import 'package:network/src/exceptions/network_exceptions.dart'; +import 'package:network/src/interceptors/auth_interceptor.dart'; +import 'package:network/src/models/network_response.dart'; +import 'package:network/src/interceptors/logging_interceptor.dart'; + +class DioNetworkClient implements NetworkClient { + /// [authTokenProvider] overrides [NetworkConfig.authTokenProvider]; pass + /// `useAuthentication: false` to send requests without credentials. + DioNetworkClient( + this._config, { + required Logger logger, + Dio? dio, + AuthTokenProvider? authTokenProvider, + bool useAuthentication = true, + }) : _logger = logger, + _dio = dio ?? Dio(), + _authTokenProvider = useAuthentication + ? authTokenProvider ?? _config.authTokenProvider + : null { + _setupDio(); + } + + final NetworkConfig _config; + final Dio _dio; + final Logger _logger; + final AuthTokenProvider? _authTokenProvider; + + void _setupDio() { + _dio.options = BaseOptions( + baseUrl: _config.baseUrl, + connectTimeout: _config.connectTimeout, + receiveTimeout: _config.receiveTimeout, + //sendTimeout cannot be used without a request body to send on Web + sendTimeout: kIsWeb ? null : _config.sendTimeout, + headers: _config.defaultHeaders, + ); + + // Add authentication interceptor if token provider is available + final tokens = _authTokenProvider; + if (tokens != null) { + _dio.interceptors.add( + AuthInterceptor(tokens, dio: _dio, logger: _logger), + ); + _logger.d('Auth interceptor added to network client'); + } + + if (_config.enableLogging) { + _dio.interceptors.add(LoggingInterceptor(logger: _logger)); + } + } + + @override + Future> get( + String path, { + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }) async { + try { + final response = await _dio.get( + path, + queryParameters: queryParameters, + options: Options(headers: headers), + ); + return _handleResponse(response, fromJsonT: fromJsonT); + } catch (e) { + _handleError(e); + } + } + + @override + Future> post( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }) async { + try { + final response = await _dio.post( + path, + data: data, + queryParameters: queryParameters, + options: Options(headers: headers), + ); + return _handleResponse(response, fromJsonT: fromJsonT); + } catch (e) { + _handleError(e); + } + } + + @override + Future> put( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }) async { + try { + final response = await _dio.put( + path, + data: data, + queryParameters: queryParameters, + options: Options(headers: headers), + ); + return _handleResponse(response, fromJsonT: fromJsonT); + } catch (e) { + _handleError(e); + } + } + + @override + Future> patch( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }) async { + try { + final response = await _dio.patch( + path, + data: data, + queryParameters: queryParameters, + options: Options(headers: headers), + ); + return _handleResponse(response, fromJsonT: fromJsonT); + } catch (e) { + _handleError(e); + } + } + + @override + Future> delete( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }) async { + try { + final response = await _dio.delete( + path, + data: data, + queryParameters: queryParameters, + options: Options(headers: headers), + ); + return _handleResponse(response, fromJsonT: fromJsonT); + } catch (e) { + _handleError(e); + } + } + + NetworkResponse _handleResponse( + Response response, { + required T Function(Object? json) fromJsonT, + }) { + try { + if (response.data is Map) { + final responseData = response.data as Map; + + if (responseData.containsKey('success')) { + if (responseData['success'] == true) { + return SuccessResponse.fromJson({ + ...responseData, + 'statusCode': response.statusCode ?? 200, + 'headers': response.headers.map, + }, fromJsonT); + } else { + return ErrorResponse.fromJson({ + ...responseData, + 'statusCode': response.statusCode ?? 500, + 'headers': response.headers.map, + }); + } + } + } + + // Ideally, should not reach here if the API follows the + // standard response format + _logger.d('Decoding response without an API envelope'); + + // Fallback to a generic success response + return SuccessResponse( + statusCode: response.statusCode ?? 200, + headers: response.headers.map, + success: true, + timestamp: DateTime.now().toIso8601String(), + data: fromJsonT(response.data), + ); + } catch (e, s) { + _logger.e('Error parsing response', e); + return ErrorResponse( + statusCode: response.statusCode ?? 500, + success: false, + message: 'Network Client failed to parse response!', + error: ErrorDetails( + code: 'PARSE_ERROR', + message: e.toString(), + details: {'stackTrace': s.toString()}, + ), + timestamp: DateTime.now().toIso8601String(), + ); + } + } + + Never _handleError(Object error) { + NetworkException networkException; + ErrorResponse? apiError; + + if (error is DioException) { + apiError = _parseApiError(error.response); + networkException = _mapDioException(error, apiError); + } else { + networkException = UnknownNetworkException(message: error.toString()); + } + + _logger.e('Network error occurred', networkException); + + throw networkException; + } + + ErrorResponse? _parseApiError(Response? response) { + try { + final responseData = response?.data; + if (responseData is Map && + responseData.containsKey('success') && + responseData['success'] == false) { + return ErrorResponse.fromJson({ + ...responseData, + 'statusCode': response?.statusCode ?? 500, + 'headers': response?.headers.map, + }); + } + } catch (e) { + _logger.w('Failed to parse API error: $e'); + } + return null; + } + + NetworkException _mapDioException( + DioException dioException, + ErrorResponse? apiError, + ) { + final message = apiError?.error.message; + + switch (dioException.type) { + case DioExceptionType.connectionTimeout: + return ConnectionTimeoutException(message: message); + case DioExceptionType.receiveTimeout: + return ReceiveTimeoutException(message: message); + case DioExceptionType.sendTimeout: + return SendTimeoutException(message: message); + case DioExceptionType.connectionError: + if (dioException.error is SocketException) { + return NoInternetConnectionException(message: message); + } + return UnknownNetworkException(message: message); + case DioExceptionType.badResponse: + final statusCode = dioException.response?.statusCode; + switch (statusCode) { + case 400: + return BadRequestException(message: message, error: apiError); + case 401: + return UnauthorizedException(message: message, error: apiError); + case 403: + return ForbiddenException(message: message, error: apiError); + case 404: + return NotFoundException(message: message, error: apiError); + case 409: + return ConflictException(message: message, error: apiError); + case 422: + return UnprocessableEntityException( + message: message, + error: apiError, + ); + case 500: + case 502: + case 503: + case 504: + return InternalServerException(message: message, error: apiError); + default: + return UnknownNetworkException( + message: message, + statusCode: statusCode, + error: apiError, + ); + } + default: + return UnknownNetworkException(message: message, error: apiError); + } + } + + @override + T handleResponse(final NetworkResponse response) { + switch (response) { + case SuccessResponse(): + return response.data; + case ErrorResponse(): + throw UnknownNetworkException( + message: response.message ?? strings.errors.network_error, + statusCode: response.statusCode, + error: response, + ); + default: + throw UnknownNetworkException( + message: strings.errors.unknown_error, + statusCode: response.statusCode, + ); + } + } + + @override + SuccessResponse handleSuccessResponse( + final NetworkResponse response, + ) { + switch (response) { + case SuccessResponse(): + return response; + case ErrorResponse(): + throw UnknownNetworkException( + message: response.message ?? strings.errors.network_error, + statusCode: response.statusCode, + error: response, + ); + default: + throw UnknownNetworkException( + message: strings.errors.unknown_error, + statusCode: response.statusCode, + ); + } + } + + @override + void dispose() { + _dio.close(); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/index.dart new file mode 100644 index 0000000..23a5e8f --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/index.dart @@ -0,0 +1,2 @@ +export 'dio_network_client.dart'; +export 'network_client.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/network_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/network_client.dart new file mode 100644 index 0000000..50b38ca --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/client/network_client.dart @@ -0,0 +1,50 @@ +import 'package:network/src/models/network_response.dart'; + +abstract interface class NetworkClient { + Future> get( + String path, { + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }); + + Future> post( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }); + + Future> put( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }); + + Future> patch( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }); + + Future> delete( + String path, { + dynamic data, + Map? queryParameters, + Map? headers, + required T Function(Object? json) fromJsonT, + }); + + T handleResponse(final NetworkResponse response); + + SuccessResponse handleSuccessResponse( + final NetworkResponse response, + ); + + void dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/index.dart new file mode 100644 index 0000000..81201c9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/index.dart @@ -0,0 +1 @@ +export 'network_config.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/network_config.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/network_config.dart new file mode 100644 index 0000000..b9cbf9c --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/config/network_config.dart @@ -0,0 +1,44 @@ +import 'package:network/src/auth/auth_token_provider.dart'; + +abstract interface class NetworkConfig { + String get baseUrl; + Duration get connectTimeout; + Duration get receiveTimeout; + Duration get sendTimeout; + Map get defaultHeaders; + bool get enableLogging; + AuthTokenProvider? get authTokenProvider; +} + +class DefaultNetworkConfig implements NetworkConfig { + const DefaultNetworkConfig({ + required this.baseUrl, + this.connectTimeout = const Duration(seconds: 30), + this.receiveTimeout = const Duration(seconds: 30), + this.sendTimeout = const Duration(seconds: 30), + this.defaultHeaders = const {}, + this.enableLogging = true, + this.authTokenProvider, + }); + + @override + final String baseUrl; + + @override + final Duration connectTimeout; + + @override + final Duration receiveTimeout; + + @override + final Duration sendTimeout; + + @override + final Map defaultHeaders; + + @override + final bool enableLogging; + + @override + final AuthTokenProvider? authTokenProvider; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/index.dart new file mode 100644 index 0000000..8df1c24 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/index.dart @@ -0,0 +1 @@ +export 'network_exceptions.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/network_exceptions.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/network_exceptions.dart new file mode 100644 index 0000000..d359ee7 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/exceptions/network_exceptions.dart @@ -0,0 +1,107 @@ +import 'package:localization/localization.dart'; +import 'package:network/network.dart'; + +abstract class NetworkException implements Exception { + const NetworkException({this.message, this.statusCode, this.error}); + + final String? message; + final int? statusCode; + final ErrorResponse? error; + + String get displayMessage => message ?? strings.errors.unknown_network; + + @override + String toString() => '$runtimeType: $displayMessage'; +} + +class BadRequestException extends NetworkException { + const BadRequestException({super.message, super.error}) + : super(statusCode: 400); + + @override + String get displayMessage => message ?? strings.errors.bad_request; +} + +class UnauthorizedException extends NetworkException { + const UnauthorizedException({super.message, super.error}) + : super(statusCode: 401); + + @override + String get displayMessage => message ?? strings.errors.unauthorized; +} + +class ForbiddenException extends NetworkException { + const ForbiddenException({super.message, super.error}) + : super(statusCode: 403); + + @override + String get displayMessage => message ?? strings.errors.forbidden; +} + +class NotFoundException extends NetworkException { + const NotFoundException({super.message, super.error}) + : super(statusCode: 404); + + @override + String get displayMessage => message ?? strings.errors.not_found; +} + +class ConflictException extends NetworkException { + const ConflictException({super.message, super.error}) + : super(statusCode: 409); + + @override + String get displayMessage => message ?? strings.errors.conflict; +} + +class UnprocessableEntityException extends NetworkException { + const UnprocessableEntityException({super.message, super.error}) + : super(statusCode: 422); + + @override + String get displayMessage => message ?? strings.errors.unprocessable_entity; +} + +class InternalServerException extends NetworkException { + const InternalServerException({super.message, super.error}) + : super(statusCode: 500); + + @override + String get displayMessage => message ?? strings.errors.internal_server_error; +} + +class ConnectionTimeoutException extends NetworkException { + const ConnectionTimeoutException({super.message}) : super(statusCode: null); + + @override + String get displayMessage => message ?? strings.errors.connection_timeout; +} + +class ReceiveTimeoutException extends NetworkException { + const ReceiveTimeoutException({super.message}) : super(statusCode: null); + + @override + String get displayMessage => message ?? strings.errors.receive_timeout; +} + +class SendTimeoutException extends NetworkException { + const SendTimeoutException({super.message}) : super(statusCode: null); + + @override + String get displayMessage => message ?? strings.errors.send_timeout; +} + +class NoInternetConnectionException extends NetworkException { + const NoInternetConnectionException({super.message}) + : super(statusCode: null); + + @override + String get displayMessage => message ?? strings.errors.no_internet; +} + +class UnknownNetworkException extends NetworkException { + const UnknownNetworkException({super.message, super.statusCode, super.error}); + + @override + String get displayMessage => message ?? strings.errors.unknown_network; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/auth_interceptor.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/auth_interceptor.dart new file mode 100644 index 0000000..5ae76ff --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/auth_interceptor.dart @@ -0,0 +1,93 @@ +import 'dart:async'; + +import 'package:core/core.dart'; +import 'package:dio/dio.dart'; +import 'package:network/src/auth/auth_token_provider.dart'; + +/// Adds session credentials and retries an authenticated request at most once. +class AuthInterceptor extends Interceptor { + AuthInterceptor( + this._authTokenProvider, { + required Dio dio, + required Logger logger, + }) : _dio = dio, + _logger = logger; + + final AuthTokenProvider _authTokenProvider; + final Dio _dio; + final Logger _logger; + Future? _refreshing; + static const _managed = 'nonstop.auth.managed'; + static const _retried = 'nonstop.auth.retried'; + + @override + void onRequest( + RequestOptions options, + RequestInterceptorHandler handler, + ) async { + try { + final origin = Uri.parse(options.baseUrl); + if (!origin.hasScheme || options.uri.origin != origin.origin) { + handler.next(options); + return; + } + if (options.headers.keys.any( + (key) => key.toLowerCase() == 'authorization', + )) { + handler.next(options); + return; + } + final token = await _authTokenProvider.getValidToken(); + if (token != null) { + options.headers['Authorization'] = 'Bearer $token'; + options.extra[_managed] = true; + } + handler.next(options); + } catch (error) { + _logger.e('Unable to obtain an authentication token', error); + handler.next(options); + } + } + + Future _refresh() async { + if (_refreshing != null) return _refreshing; + final pending = _authTokenProvider.refreshToken(); + _refreshing = pending; + try { + return await pending; + } finally { + _refreshing = null; + } + } + + @override + void onError(DioException err, ErrorInterceptorHandler handler) async { + final request = err.requestOptions; + if (err.response?.statusCode != 401 || + request.extra[_managed] != true || + request.extra[_retried] == true || + request.data is Stream) { + handler.next(err); + return; + } + try { + final token = await _refresh(); + if (token != null) { + final response = await _dio.fetch( + request.copyWith( + headers: {...request.headers, 'Authorization': 'Bearer $token'}, + extra: {...request.extra, _retried: true}, + data: request.data is FormData + ? (request.data as FormData).clone() + : request.data, + ), + ); + handler.resolve(response); + return; + } + } catch (refreshError) { + _logger.e('Authentication retry failed', refreshError); + } + handler.next(err); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/index.dart new file mode 100644 index 0000000..075b202 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/index.dart @@ -0,0 +1,2 @@ +export 'auth_interceptor.dart'; +export 'logging_interceptor.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/logging_interceptor.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/logging_interceptor.dart new file mode 100644 index 0000000..87c9289 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/interceptors/logging_interceptor.dart @@ -0,0 +1,33 @@ +import 'package:core/core.dart'; +import 'package:dio/dio.dart'; + +class LoggingInterceptor extends Interceptor { + LoggingInterceptor({required Logger logger}) : _logger = logger; + + final Logger _logger; + + @override + void onRequest(RequestOptions options, RequestInterceptorHandler handler) { + // Credentials and personal data can occur in headers, query strings and + // bodies. Log only the HTTP method and path by default. + _logger.d('Request: ${options.method} ${options.uri.path}'); + super.onRequest(options, handler); + } + + @override + void onResponse(Response response, ResponseInterceptorHandler handler) { + _logger.d( + 'Response: ${response.statusCode} ${response.requestOptions.uri.path}', + ); + super.onResponse(response, handler); + } + + @override + void onError(DioException err, ErrorInterceptorHandler handler) { + _logger.e( + 'Network error: ${err.type.name} ${err.response?.statusCode} ' + '${err.requestOptions.uri.path}', + ); + super.onError(err, handler); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/index.dart new file mode 100644 index 0000000..87c17f7 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/index.dart @@ -0,0 +1 @@ +export 'network_response.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.dart new file mode 100644 index 0000000..cb65ffd --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.dart @@ -0,0 +1,102 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'network_response.g.dart'; + +abstract class NetworkResponse { + const NetworkResponse({ + required this.statusCode, + required this.success, + this.message, + required this.timestamp, + this.headers, + }); + + final int statusCode; + final bool success; + final String? message; + final String timestamp; + final Map>? headers; + + bool get isSuccess => success && statusCode >= 200 && statusCode < 300; +} + +@JsonSerializable(genericArgumentFactories: true) +class SuccessResponse extends NetworkResponse { + final T data; + final Pagination? pagination; + + const SuccessResponse({ + required super.statusCode, + required super.success, + required this.data, + super.message, + required super.timestamp, + this.pagination, + super.headers, + }); + + factory SuccessResponse.fromJson( + Map json, + T Function(Object? json) fromJsonT, + ) => _$SuccessResponseFromJson(json, fromJsonT); + + Map toJson(Object Function(T value) toJsonT) => + _$SuccessResponseToJson(this, toJsonT); +} + +@JsonSerializable() +class ErrorResponse extends NetworkResponse { + final ErrorDetails error; + + const ErrorResponse({ + required super.statusCode, + required super.success, + required this.error, + required super.timestamp, + super.message, + super.headers, + }); + + factory ErrorResponse.fromJson(Map json) => + _$ErrorResponseFromJson(json); + + Map toJson() => _$ErrorResponseToJson(this); +} + +@JsonSerializable() +class ErrorDetails { + const ErrorDetails({required this.code, required this.message, this.details}); + + final String code; + final String message; + final Map? details; + + factory ErrorDetails.fromJson(Map json) => + _$ErrorDetailsFromJson(json); + + Map toJson() => _$ErrorDetailsToJson(this); +} + +@JsonSerializable() +class Pagination { + const Pagination({ + required this.page, + required this.limit, + required this.total, + required this.totalPages, + required this.hasNextPage, + required this.hasPreviousPage, + }); + + final int page; + final int limit; + final int total; + final int totalPages; + final bool hasNextPage; + final bool hasPreviousPage; + + factory Pagination.fromJson(Map json) => + _$PaginationFromJson(json); + + Map toJson() => _$PaginationToJson(this); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.g.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.g.dart new file mode 100644 index 0000000..7445c78 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/models/network_response.g.dart @@ -0,0 +1,93 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'network_response.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +SuccessResponse _$SuccessResponseFromJson( + Map json, + T Function(Object? json) fromJsonT, +) => SuccessResponse( + statusCode: (json['statusCode'] as num).toInt(), + success: json['success'] as bool, + data: fromJsonT(json['data']), + message: json['message'] as String?, + timestamp: json['timestamp'] as String, + pagination: json['pagination'] == null + ? null + : Pagination.fromJson(json['pagination'] as Map), + headers: (json['headers'] as Map?)?.map( + (k, e) => + MapEntry(k, (e as List).map((e) => e as String).toList()), + ), +); + +Map _$SuccessResponseToJson( + SuccessResponse instance, + Object? Function(T value) toJsonT, +) => { + 'statusCode': instance.statusCode, + 'success': instance.success, + 'message': instance.message, + 'timestamp': instance.timestamp, + 'headers': instance.headers, + 'data': toJsonT(instance.data), + 'pagination': instance.pagination, +}; + +ErrorResponse _$ErrorResponseFromJson(Map json) => + ErrorResponse( + statusCode: (json['statusCode'] as num).toInt(), + success: json['success'] as bool, + error: ErrorDetails.fromJson(json['error'] as Map), + timestamp: json['timestamp'] as String, + message: json['message'] as String?, + headers: (json['headers'] as Map?)?.map( + (k, e) => + MapEntry(k, (e as List).map((e) => e as String).toList()), + ), + ); + +Map _$ErrorResponseToJson(ErrorResponse instance) => + { + 'statusCode': instance.statusCode, + 'success': instance.success, + 'message': instance.message, + 'timestamp': instance.timestamp, + 'headers': instance.headers, + 'error': instance.error, + }; + +ErrorDetails _$ErrorDetailsFromJson(Map json) => ErrorDetails( + code: json['code'] as String, + message: json['message'] as String, + details: json['details'] as Map?, +); + +Map _$ErrorDetailsToJson(ErrorDetails instance) => + { + 'code': instance.code, + 'message': instance.message, + 'details': instance.details, + }; + +Pagination _$PaginationFromJson(Map json) => Pagination( + page: (json['page'] as num).toInt(), + limit: (json['limit'] as num).toInt(), + total: (json['total'] as num).toInt(), + totalPages: (json['totalPages'] as num).toInt(), + hasNextPage: json['hasNextPage'] as bool, + hasPreviousPage: json['hasPreviousPage'] as bool, +); + +Map _$PaginationToJson(Pagination instance) => + { + 'page': instance.page, + 'limit': instance.limit, + 'total': instance.total, + 'totalPages': instance.totalPages, + 'hasNextPage': instance.hasNextPage, + 'hasPreviousPage': instance.hasPreviousPage, + }; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/error_message_extension.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/error_message_extension.dart new file mode 100644 index 0000000..a715c62 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/error_message_extension.dart @@ -0,0 +1,97 @@ +import 'package:core/core.dart'; +import 'package:flutter/foundation.dart'; +import 'package:localization/localization.dart'; +import 'package:network/network.dart'; + +extension ErrorMessageExtension on Object? { + String message() { + return switch (this) { + NetworkException error => error.displayMessage, + CoreException error => error.message, + FormatException _ => strings.errors.format_exception_message( + ErrorCodes.formatException, + debugMessage, + ), + Error error => error.message(), + _ => strings.errors.default_error_message, + }; + } + + String get debugMessage { + if (kDebugMode) { + return '\n${toString()}\ntype: $runtimeType'; + } + return ''; + } +} + +// Simple creative error messages with codes +extension ErrorMessageOnError on Error { + String message() { + return switch (this) { + TypeError _ => strings.errors.type_error_message( + ErrorCodes.typeError, + debugMessage, + ), + IndexError _ => strings.errors.index_error_message( + ErrorCodes.indexError, + debugMessage, + ), + RangeError _ => strings.errors.range_error_message( + ErrorCodes.rangeError, + debugMessage, + ), + ArgumentError _ => strings.errors.argument_error_message( + ErrorCodes.argumentError, + debugMessage, + ), + StateError _ => strings.errors.state_error_message( + ErrorCodes.stateError, + debugMessage, + ), + UnimplementedError _ => strings.errors.unimplemented_error_message( + ErrorCodes.unimplementedError, + debugMessage, + ), + UnsupportedError _ => strings.errors.unsupported_error_message( + ErrorCodes.unsupportedError, + debugMessage, + ), + ConcurrentModificationError _ => + strings.errors.concurrent_modification_error_message( + ErrorCodes.concurrentModificationError, + debugMessage, + ), + OutOfMemoryError _ => strings.errors.out_of_memory_error_message( + ErrorCodes.outOfMemoryError, + debugMessage, + ), + StackOverflowError _ => strings.errors.stack_overflow_error_message( + ErrorCodes.stackOverflowError, + debugMessage, + ), + _ => strings.errors.unknown_error_message( + ErrorCodes.unknownError, + debugMessage, + ), + }; + } +} + +sealed class ErrorCodes { + static const String typeError = "E001"; + static const String argumentError = "E002"; + static const String rangeError = "E003"; + static const String indexError = "E004"; + static const String stateError = "E005"; + static const String unsupportedError = "E006"; + static const String unimplementedError = "E007"; + static const String concurrentModificationError = "E008"; + static const String outOfMemoryError = "E009"; + static const String stackOverflowError = "E010"; + static const String formatException = "E011"; + static const String unknownError = "E999"; + static const String networkException = "E100"; + static const String coreException = "E101"; + static const String defaultError = "E000"; +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/index.dart new file mode 100644 index 0000000..76768c9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/extensions/index.dart @@ -0,0 +1 @@ +export 'error_message_extension.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/index.dart new file mode 100644 index 0000000..49893a1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/lib/src/utils/index.dart @@ -0,0 +1 @@ +export 'extensions/index.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/network/pubspec.yaml new file mode 100644 index 0000000..4588e17 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/pubspec.yaml @@ -0,0 +1,32 @@ +name: network +description: "HTTP layer for Nonstop Example: Dio client, interceptors, typed responses and error mapping." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + dio: ^5.7.0 + json_annotation: ^4.9.0 + core: + path: ../core + localization: + path: ../localization + di: + path: ../di + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + build_runner: ^2.4.15 + json_serializable: ^6.9.5 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/test/dio_network_client_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/test/dio_network_client_test.dart new file mode 100644 index 0000000..99b6374 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/test/dio_network_client_test.dart @@ -0,0 +1,532 @@ +import 'dart:convert'; +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:core/core.dart'; +import 'package:dio/dio.dart'; +import 'package:di/di.dart'; +import 'package:network/network.dart' as network; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network/network.dart'; + +class _Logger implements Logger { + final messages = []; + @override + Object get logger => this; + @override + void d(String message) => messages.add(message); + @override + void i(String message) => messages.add(message); + @override + void w(String message) => messages.add(message); + @override + void e(String message, [Object? error, StackTrace? stackTrace]) => + messages.add(message); +} + +class _Adapter implements HttpClientAdapter { + Object? body; + int status = 200; + final statuses = []; + bool closed = false; + Object? failure; + final requests = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + if (failure != null) throw failure!; + return ResponseBody.fromString( + jsonEncode(body), + statuses.isEmpty ? status : statuses.removeAt(0), + headers: { + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) => closed = true; +} + +class _Tokens implements AuthTokenProvider { + int refreshes = 0; + String? refreshed = 'new-token'; + bool failRefresh = false; + bool failRead = false; + @override + Future getValidToken() async { + if (failRead) throw StateError('token unavailable'); + return 'old-token'; + } + + @override + Future refreshToken() async { + refreshes++; + if (failRefresh) throw StateError('refresh failed'); + return refreshed; + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _DelayedTokens extends _Tokens { + final pending = Completer(); + @override + Future refreshToken() { + refreshes++; + return pending.future; + } +} + +class _CustomConfig implements NetworkConfig { + @override + String get baseUrl => 'https://example.test'; + @override + Duration get connectTimeout => const Duration(seconds: 5); + @override + Duration get receiveTimeout => const Duration(seconds: 5); + @override + Duration get sendTimeout => const Duration(seconds: 5); + @override + Map get defaultHeaders => const {'X-App': 'custom'}; + @override + bool get enableLogging => false; + @override + AuthTokenProvider? get authTokenProvider => null; +} + +void main() { + late _Adapter adapter; + late _Logger logger; + late DioNetworkClient client; + + setUp(() { + adapter = _Adapter(); + logger = _Logger(); + client = DioNetworkClient( + DefaultNetworkConfig(baseUrl: 'https://example.test'), + logger: logger, + dio: Dio()..httpClientAdapter = adapter, + ); + }); + tearDown(() => client.dispose()); + + test('concurrent unauthorized requests share one token refresh', () async { + final tokens = _DelayedTokens(); + adapter.statuses.addAll([401, 401, 200, 200]); + final authenticated = DioNetworkClient( + DefaultNetworkConfig( + baseUrl: 'https://example.test', + authTokenProvider: tokens, + ), + logger: logger, + dio: Dio()..httpClientAdapter = adapter, + ); + addTearDown(authenticated.dispose); + final first = authenticated.get( + '/first', + fromJsonT: (json) => json, + ); + final second = authenticated.get( + '/second', + fromJsonT: (json) => json, + ); + await pumpEventQueue(); + expect(tokens.refreshes, 1); + tokens.pending.complete('new-token'); + final results = await Future.wait([first, second]); + expect(results.every((r) => r.isSuccess), isTrue); + expect(adapter.requests, hasLength(4)); + }); + + test( + 'multipart retries clone consumed bodies; streams are never replayed', + () async { + final tokens = _Tokens(); + final authenticated = DioNetworkClient( + DefaultNetworkConfig( + baseUrl: 'https://example.test', + authTokenProvider: tokens, + ), + logger: logger, + dio: Dio()..httpClientAdapter = adapter, + ); + addTearDown(authenticated.dispose); + adapter.statuses.addAll([401, 200]); + final form = FormData.fromMap({'field': 'value'}); + expect( + (await authenticated.post( + '/file', + data: form, + fromJsonT: (json) => json, + )).isSuccess, + isTrue, + ); + expect(adapter.requests.last.data, isNot(same(form))); + adapter.status = 401; + await expectLater( + authenticated.post( + '/stream', + data: Stream.value([1, 2]), + fromJsonT: (json) => json, + ), + throwsA(isA()), + ); + expect(tokens.refreshes, 1); + }, + ); + + test('API payload cannot override HTTP status or response headers', () async { + adapter.body = { + 'success': true, + 'timestamp': 'now', + 'data': 1, + 'statusCode': 500, + 'headers': { + 'fake': ['value'], + }, + }; + final response = await client.get( + '/value', + fromJsonT: (json) => json as int, + ); + expect(response.statusCode, 200); + expect(response.headers, isNot(contains('fake'))); + }); + + for (final (status, expected) in <(int, Type)>[ + (400, BadRequestException), + (403, ForbiddenException), + (404, NotFoundException), + (409, ConflictException), + (422, UnprocessableEntityException), + (500, InternalServerException), + (502, InternalServerException), + (503, InternalServerException), + (504, InternalServerException), + (418, UnknownNetworkException), + ]) { + test( + 'HTTP $status maps to $expected and preserves API error details', + () async { + adapter.status = status; + adapter.body = { + 'success': false, + 'timestamp': '2026-01-01', + 'error': {'code': 'FAIL', 'message': 'Request rejected'}, + }; + await expectLater( + client.get('/request', fromJsonT: (json) => json), + throwsA( + predicate( + (e) => + e.runtimeType == expected && e.message == 'Request rejected', + ), + ), + ); + }, + ); + } + + test('every transport failure maps to a domain exception', () async { + for (final (type, error, expected) in <(DioExceptionType, Object?, Type)>[ + (DioExceptionType.connectionTimeout, null, ConnectionTimeoutException), + (DioExceptionType.receiveTimeout, null, ReceiveTimeoutException), + (DioExceptionType.sendTimeout, null, SendTimeoutException), + ( + DioExceptionType.connectionError, + const SocketException('offline'), + NoInternetConnectionException, + ), + (DioExceptionType.connectionError, null, UnknownNetworkException), + (DioExceptionType.cancel, null, UnknownNetworkException), + ]) { + adapter.failure = DioException( + requestOptions: RequestOptions(path: '/request'), + type: type, + error: error, + ); + await expectLater( + client.get('/request', fromJsonT: (json) => json), + throwsA(predicate((e) => e.runtimeType == expected)), + ); + } + }); + + test( + 'write verbs consistently propagate transport errors and malformed envelopes do not hide HTTP failures', + () async { + adapter.status = 500; + adapter.body = {'success': false, 'error': 'invalid shape'}; + for (final operation in [ + () => client.post('/request', fromJsonT: (j) => j), + () => client.put('/request', fromJsonT: (j) => j), + () => client.patch('/request', fromJsonT: (j) => j), + () => client.delete('/request', fromJsonT: (j) => j), + ]) { + await expectLater(operation(), throwsA(isA())); + } + }, + ); + + test( + 'auth tokens stay on the configured origin and provider failures do not crash requests', + () async { + final tokens = _Tokens(); + final transport = Dio()..httpClientAdapter = adapter; + final authenticated = DioNetworkClient( + DefaultNetworkConfig( + baseUrl: 'https://example.test', + authTokenProvider: tokens, + ), + logger: logger, + dio: transport, + ); + addTearDown(authenticated.dispose); + await authenticated.get( + 'https://external.test/image', + fromJsonT: (j) => j, + ); + expect(adapter.requests.last.headers, isNot(contains('Authorization'))); + tokens.failRead = true; + await authenticated.get('/image', fromJsonT: (j) => j); + expect(adapter.requests.last.headers, isNot(contains('Authorization'))); + }, + ); + + test( + 'module respects explicit disable, injected credentials and unconfigured auth', + () async { + addTearDown(di.reset); + Future sendsCredentials( + NetworkConfig config, { + bool enabled = true, + }) async { + final dio = Dio()..httpClientAdapter = adapter; + await network.registerNetworkWithDI( + config, + useAuthentication: enabled, + dio: dio, + ); + expect(di.get(), same(config)); + await di.get().get('/me', fromJsonT: (j) => j); + return adapter.requests.last.headers.containsKey('Authorization'); + } + + for (final supplied in [false, true]) { + for (final enabled in [false, true]) { + await di.reset(); + di.register(logger); + final config = DefaultNetworkConfig( + baseUrl: 'https://example.test', + authTokenProvider: supplied ? _Tokens() : null, + ); + expect( + await sendsCredentials(config, enabled: enabled), + supplied && enabled, + ); + } + } + await di.reset(); + di.register(logger); + di.register(_Tokens()); + final custom = _CustomConfig(); + expect(await sendsCredentials(custom), isTrue); + expect(custom.authTokenProvider, isNull); + await di.reset(); + di.register(logger); + await network.init( + config: const DefaultNetworkConfig(baseUrl: 'https://example.test'), + ); + expect(di.has(), isTrue); + expect( + logger.messages, + contains('Network client registered without authentication'), + ); + }, + ); + + test('plain JSON uses the supplied decoder', () async { + adapter.body = {'count': 7}; + final response = await client.get( + '/count', + fromJsonT: (json) => (json as Map)['count'] as int, + ); + expect(response.isSuccess, isTrue); + expect(client.handleResponse(response), 7); + expect(client.handleSuccessResponse(response).data, 7); + }); + + test('API errors in HTTP 200 stay errors', () async { + adapter.body = { + 'success': false, + 'timestamp': '2026-01-01', + 'message': 'Cannot save', + 'error': {'code': 'INVALID', 'message': 'Invalid input'}, + }; + final response = await client.post( + '/save', + fromJsonT: (json) => json as String, + ); + expect(response, isA>()); + expect(response.isSuccess, isFalse); + expect((response as ErrorResponse).error.code, 'INVALID'); + expect( + () => client.handleResponse(response), + throwsA(isA()), + ); + }); + + test('envelope success decodes data and retains metadata', () async { + adapter.body = { + 'success': true, + 'timestamp': '2026-01-01', + 'data': {'count': 3}, + }; + final response = await client.get( + '/count', + fromJsonT: (json) => (json as Map)['count'] as int, + ); + expect(client.handleResponse(response), 3); + expect(response.timestamp, '2026-01-01'); + }); + + test('invalid payload becomes a parse error', () async { + adapter.body = 'invalid'; + final response = await client.get( + '/count', + fromJsonT: (json) => json as int, + ); + expect(response, isA>()); + expect((response as ErrorResponse).error.code, 'PARSE_ERROR'); + }); + + for (final method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) { + test('$method forwards query and headers and decodes response', () async { + adapter.body = 8; + final request = switch (method) { + 'POST' => client.post, + 'PUT' => client.put, + 'PATCH' => client.patch, + 'DELETE' => client.delete, + _ => client.get, + }; + final response = await request( + '/items', + queryParameters: {'page': 2}, + headers: {'X-Request': 'test'}, + fromJsonT: (json) => json as int, + ); + expect(client.handleResponse(response), 8); + expect(adapter.requests.single.method, method); + expect(adapter.requests.single.queryParameters, {'page': 2}); + expect(adapter.requests.single.headers['X-Request'], 'test'); + }); + } + + test('unauthorized HTTP responses throw a typed exception', () async { + adapter.status = 401; + adapter.body = {'message': 'Unauthorized'}; + await expectLater( + client.get('/private', fromJsonT: (json) => json as int), + throwsA(isA()), + ); + }); + + test('logs do not contain credentials, query values or payloads', () async { + adapter.body = {'secret': 'response-secret'}; + await client.post( + '/items', + headers: {'Authorization': 'Bearer header-secret'}, + queryParameters: {'token': 'query-secret'}, + data: {'password': 'body-secret'}, + fromJsonT: (json) => json, + ); + expect(logger.messages.join('\n'), isNot(contains('secret'))); + }); + + test('dispose closes the transport', () { + client.dispose(); + expect(adapter.closed, isTrue); + }); + + group('authentication retries', () { + late _Tokens tokens; + setUp(() { + client.dispose(); + adapter = _Adapter()..body = 9; + tokens = _Tokens(); + client = DioNetworkClient( + DefaultNetworkConfig( + baseUrl: 'https://example.test', + authTokenProvider: tokens, + ), + logger: logger, + dio: Dio()..httpClientAdapter = adapter, + ); + }); + + test('uses the configured transport and refreshes once', () async { + adapter.statuses.addAll([401, 200]); + final response = await client.get( + '/items', + fromJsonT: (json) => json as int, + ); + expect(client.handleResponse(response), 9); + expect(adapter.requests, hasLength(2)); + expect( + adapter.requests.last.headers['Authorization'], + 'Bearer new-token', + ); + expect(tokens.refreshes, 1); + }); + + test('a repeated 401 does not loop', () async { + adapter.status = 401; + await expectLater( + client.get('/items', fromJsonT: (json) => json as int), + throwsA(isA()), + ); + expect(adapter.requests, hasLength(2)); + expect(tokens.refreshes, 1); + }); + + test('caller authorization is respected case-insensitively', () async { + adapter.status = 401; + await expectLater( + client.get( + '/items', + headers: {'authorization': 'custom'}, + fromJsonT: (json) => json as int, + ), + throwsA(isA()), + ); + expect(adapter.requests, hasLength(1)); + expect(adapter.requests.single.headers['authorization'], 'custom'); + expect(tokens.refreshes, 0); + }); + + for (final fails in [true, false]) { + test( + 'unavailable refreshed token preserves the original error ($fails)', + () async { + tokens.failRefresh = fails; + tokens.refreshed = null; + adapter.status = 401; + await expectLater( + client.get('/items', fromJsonT: (json) => json as int), + throwsA(isA()), + ); + expect(adapter.requests, hasLength(1)); + }, + ); + } + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/test/models_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/test/models_test.dart new file mode 100644 index 0000000..51ac7a9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/test/models_test.dart @@ -0,0 +1,141 @@ +import 'package:core/core.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network/network.dart'; + +class _BaseError extends NetworkException {} + +class _OtherError extends Error {} + +class _Urls extends ApiUrlConfig { + _Urls() : super(pathPrefix: '/v1'); +} + +class _Api extends NetworkApi<_Urls> { + _Api() : super(urlConfig: _Urls()); + @override + Map get headers => {}; +} + +void main() { + test('network failures provide readable localized messages and statuses', () { + final errors = [ + _BaseError(), + const BadRequestException(), + const UnauthorizedException(), + const ForbiddenException(), + const NotFoundException(), + const ConflictException(), + const UnprocessableEntityException(), + const InternalServerException(), + const ConnectionTimeoutException(), + const ReceiveTimeoutException(), + const SendTimeoutException(), + const NoInternetConnectionException(), + const UnknownNetworkException(), + ]; + for (final error in errors) { + expect(error.displayMessage, isNotEmpty); + expect(error.toString(), contains(error.displayMessage)); + expect((error as Object).message(), error.displayMessage); + } + expect( + const UnauthorizedException(message: 'Custom').displayMessage, + 'Custom', + ); + expect(const UnauthorizedException().statusCode, 401); + // Timeouts never produced an HTTP response, so none carries a status. + for (final timeout in const [ + ConnectionTimeoutException(), + ReceiveTimeoutException(), + SendTimeoutException(), + ]) { + expect(timeout.statusCode, isNull); + } + final api = _Api(); + expect(api.urlConfig.pathPrefix, '/v1'); + expect(api.headers, isEmpty); + }); + + test('application errors map to readable messages with diagnostic codes', () { + TypeError? typeError; + try { + final dynamic value = 'not a number'; + value as int; + } on TypeError catch (error) { + typeError = error; + } + final errors = [ + CoreException(message: 'Core error'), + const FormatException('invalid'), + typeError, + IndexError.withLength(2, 1), + RangeError('range'), + ArgumentError('arg'), + StateError('state'), + UnimplementedError(), + UnsupportedError('unsupported'), + ConcurrentModificationError(), + const OutOfMemoryError(), + const StackOverflowError(), + _OtherError(), + null, + ]; + for (final error in errors) { + expect(error.message(), isNotEmpty); + } + expect( + (CoreException(message: 'Core error') as Object).message(), + 'Core error', + ); + expect( + (StateError('state') as Error).message(), + contains(ErrorCodes.stateError), + ); + }); + + test('success, error and pagination metadata round-trip JSON', () { + const pagination = Pagination( + page: 1, + limit: 10, + total: 20, + totalPages: 2, + hasNextPage: true, + hasPreviousPage: false, + ); + const success = SuccessResponse( + statusCode: 200, + success: true, + data: 3, + timestamp: '2026', + pagination: pagination, + headers: { + 'x': ['y'], + }, + ); + final json = success.toJson((value) => value); + // toJson intentionally retains nested objects until JSON encoding. + json['pagination'] = pagination.toJson(); + final decoded = SuccessResponse.fromJson( + json, + (value) => value as int, + ); + expect(decoded.data, 3); + expect(decoded.pagination!.hasNextPage, isTrue); + expect(decoded.isSuccess, isTrue); + const details = ErrorDetails( + code: 'INVALID', + message: 'Invalid', + details: {'field': 'email'}, + ); + const error = ErrorResponse( + statusCode: 400, + success: false, + error: details, + timestamp: '2026', + ); + final errorJson = error.toJson()..['error'] = details.toJson(); + expect(ErrorResponse.fromJson(errorJson).error.code, 'INVALID'); + expect(ErrorDetails.fromJson(details.toJson()).details, {'field': 'email'}); + expect(error.isSuccess, isFalse); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/test/network_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/test/network_test.dart new file mode 100644 index 0000000..b7e0d4e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/test/network_test.dart @@ -0,0 +1,15 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:network/network.dart'; + +void main() { + test('DefaultNetworkConfig creates instance with provided values', () { + const config = DefaultNetworkConfig( + baseUrl: 'https://api.example.com', + enableLogging: true, + ); + + expect(config.baseUrl, 'https://api.example.com'); + expect(config.enableLogging, true); + expect(config.connectTimeout, const Duration(seconds: 30)); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/network/test/response_contract_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/network/test/response_contract_test.dart new file mode 100644 index 0000000..41c4da6 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/network/test/response_contract_test.dart @@ -0,0 +1,79 @@ +import 'package:core/core.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:network/network.dart'; + +class _Dio extends Mock implements Dio {} + +class _Logger extends Mock implements Logger {} + +class _UnknownResponse extends NetworkResponse { + const _UnknownResponse() + : super(statusCode: 202, success: false, timestamp: 'now'); +} + +void main() { + setUpAll(() => registerFallbackValue(Options())); + test( + 'unexpected transport failures are normalized at the client boundary', + () async { + final dio = _Dio(); + when(() => dio.interceptors).thenReturn(Interceptors()); + when( + () => dio.get(any(), options: any(named: 'options')), + ).thenThrow(StateError('transport')); + final client = DioNetworkClient( + const DefaultNetworkConfig(baseUrl: 'https://example.test'), + logger: _Logger(), + dio: dio, + ); + addTearDown(client.dispose); + await expectLater( + client.get('/request', fromJsonT: (json) => json), + throwsA(isA()), + ); + }, + ); + + test( + 'response handlers preserve nullable successes and reject unsupported or failed envelopes', + () { + final client = DioNetworkClient( + const DefaultNetworkConfig(baseUrl: 'https://example.test'), + logger: _Logger(), + ); + addTearDown(client.dispose); + const success = SuccessResponse( + statusCode: 204, + success: true, + data: null, + timestamp: 'now', + ); + expect(client.handleResponse(success), isNull); + expect(client.handleSuccessResponse(success), same(success)); + const error = ErrorResponse( + statusCode: 200, + success: false, + timestamp: 'now', + error: ErrorDetails(code: 'INVALID', message: 'Rejected'), + ); + expect( + () => client.handleSuccessResponse(error), + throwsA(isA()), + ); + expect( + () => client.handleResponse(error), + throwsA(isA()), + ); + expect( + () => client.handleResponse(const _UnknownResponse()), + throwsA(isA()), + ); + expect( + () => client.handleSuccessResponse(const _UnknownResponse()), + throwsA(isA()), + ); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/notifications/CLAUDE.md new file mode 100644 index 0000000..d7a9f02 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/CLAUDE.md @@ -0,0 +1,72 @@ +# Nonstop Example: `packages/notifications` + +Owns Firebase Cloud Messaging subscriptions, permission requests, the FCM token +lifecycle (fetch, backend registration, refresh), a persisted installation ID +and badge clearing. It does not own presentation or navigation: toasts and +routing are `NotificationConfig` callbacks from the app. Layer 3: depends on +`core`, `di`, `network`. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +| Symbol | Kind | +|---|---| +| `NotificationClient` / `FirebaseNotificationClient` | `abstract interface class` / FCM implementation: `init`, `requestPermissions`, `getFCMToken`, `handleForegroundNotification(message)`, `handleNotificationOpened(message)`, `clearBadge`, `unregisterDevice`, `fcmToken`, `deviceId`, `dispose` | +| `init({config, messaging})`, `registerNotificationWithDI` | Registers config, `DeviceInfo`, managers and `NotificationClient` (with `dispose`) | +| `NotificationConfig` / `DefaultNotificationConfig` | `onForeground(title, body)`, `onOpenRoute(route)` | +| `NotificationTokenManager` / `FirebaseTokenManager(logger:, networkClient:, deviceInfo:, firebaseMessaging:)` | `getFCMToken`, `registerToken` (returns device ID), `unRegisterToken(deviceId)`, `handleTokenRefresh` | +| `NotificationPermissionManager` / `FirebasePermissionManager(logger:, firebaseMessaging:)` | `requestPermissions({provisional})` | +| `DeviceInfo` / `DeviceInfoImpl`, `InstallationIdStore` / `SharedPreferencesInstallationIdStore` | Installation ID + device label | +| `DeviceTokenRequest` | Backend registration DTO (`json_serializable`) | +| `NotificationException` | Extends `CoreException`; thrown by `FirebasePermissionManager` | +| `handleBackgroundNotification` | Top-level `@pragma('vm:entry-point')` background handler (intentionally a no-op) | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/notifications.dart` | Barrel and `init` | +| `lib/src/di/notification_di.dart` | Composition edge: resolves `Logger`/`NetworkClient` once and injects them into every service | +| `lib/src/client/` | Contract, `FirebaseNotificationClient`, background handler | +| `lib/src/services/` | Token manager (backend calls), permission manager | +| `lib/src/device_info/` | `DeviceInfo`, installation ID store | +| `lib/src/models/` | Token DTO; `device_token_models.g.dart` is generated | +| `lib/src/config/`, `lib/src/exceptions/` | Config callbacks, `NotificationException` | + +## Rules + +- **Subscription ownership.** Only `FirebaseNotificationClient` listens to `onMessage`, `onMessageOpenedApp` and `onTokenRefresh`. `init()` is idempotent and concurrent calls share one future; a startup failure cancels all subscriptions and rethrows so `init()` can be retried. `dispose()` cancels them and blocks late startup work; `init()` after dispose throws `StateError`. +- **Permission denied** means no subscriptions and no token; a later `init()` asks again. +- **Route safety.** `handleNotificationOpened(message)` (initial message and `onMessageOpenedApp` alike) forwards `data['route']` only if it is a `String` starting with `/` and not `//`. Anything else is ignored. +- **Contained failures.** Callback, stream, badge and token-registration errors are logged, never thrown. A failed registration clears `fcmToken`/`deviceId` and returns null. +- **Backend rejection is a failure.** `FirebaseTokenManager` passes responses through `handleSuccessResponse`, so an `ErrorResponse` throws. +- **Privacy.** Token logs say "obtained"/"registered", never the token. The installation ID is 16 random bytes (`Random.secure`) in `SharedPreferences` key `nonstop.installation_id`; no hardware identifiers. +- **Background isolate** has no DI or navigation: keep `handleBackgroundNotification` self-contained. +- **Sign-out.** `unregisterDevice()` deletes this device's backend registration and clears `deviceId`; no-op if never registered. Backend errors propagate; the app's `AppRouter.signOut` logs them and still signs out. +- **Injected (constructor, never `di.get` inside services):** `FirebaseMessaging`, `Logger`, `NetworkClient`, `DeviceInfo`, managers, and optional streams/badge/background-registration functions on the client; `DeviceInfoPlugin`, `InstallationIdStore`, `createId` on `DeviceInfoImpl`. + +## Common changes + +- **Handle a new payload key or route rule:** edit `handleNotificationOpened` in `firebase_notification_client.dart`; add cases to the rejected-data loop in `test/client_test.dart` ("foreground, opened, initial and token-refresh events reach their owners"). +- **Change the device-token endpoint or payload:** edit `notification_token_manager.dart` and `device_token_models.dart` (`DeviceTokenRequest`), run `dart run melos run generate`, update "registers metadata, refreshes and unregisters" in `test/services_test.dart`. +- **React to a notification in the app:** pass a new callback through `NotificationConfig` from `apps/nonstop_example/lib/bootstrap.dart`; do not import app code here. + +## Tests + +| File | Covers | +|---|---| +| `test/client_test.dart` | Single init, denial/retry, event routing, route filtering, contained failures, `unregisterDevice`, failed-startup cleanup, dispose | +| `test/services_test.dart` | `init` composition and failure, permission status mapping, token manager calls and backend rejection, DTO JSON | +| `test/device_info_test.dart` | ID persistence and concurrency, storage failure/retry, device name fallback | + +Doubles: mocktail `FirebaseMessaging`, `NotificationTokenManager`, `NotificationPermissionManager`, `NetworkClient`, `DeviceInfo`; broadcast `StreamController`s for FCM streams; `_Store` for `InstallationIdStore`; `SharedPreferences.setMockInitialValues`. + +`dart run melos exec --scope=notifications -- flutter test`; `dart run melos run coverage` must stay 100%. + +## Gotchas + +- `init` needs `Logger` and `NetworkClient` in `di` first (`registerNotificationWithDI` resolves them); call `network.init` before it, as bootstrap does. +- Backend endpoints required: `POST /device-tokens/me` and `DELETE /device-tokens/me/{deviceId}` on the configured `baseUrl`. +- `device_token_models.g.dart` is generated: `dart run melos run generate`. +- The client's `init()` is run by `NotificationLifecycle` in the app after the first frame, not by the package `init`. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/README.md b/packages/nonstop_cli/example/nonstop_example/packages/notifications/README.md new file mode 100644 index 0000000..be59021 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/README.md @@ -0,0 +1,69 @@ +# notifications + +Firebase Cloud Messaging for Nonstop Example: permission requests, message +routing, badge clearing and device-token registration with your backend. + +## Initialise + +Firebase must be initialised, and a `Logger` and a `NetworkClient` must be +registered (the network module does that). + +```dart +import 'package:notifications/notifications.dart' as notifications; + +await notifications.init( + config: notifications.NotificationConfig( + onForeground: (title, body) => Toast.notification(title: title, body: body), + onOpenRoute: (route) => router.go(route), + ), +); +``` + +`init` registers `NotificationClient`, `NotificationTokenManager`, +`NotificationPermissionManager`, `DeviceInfo` and `NotificationConfig`. Nothing +talks to the device until `NotificationClient.init()` runs (the app's +`NotificationLifecycle` widget calls it after the first frame). It: + +1. requests permission (stops quietly if denied; call `init()` again to retry), +2. listens for foreground, opened and token-refresh events, +3. handles the message that launched the app, if any, +4. fetches the FCM token and registers it with the backend, +5. clears the app badge where supported. + +## Configure + +| `NotificationConfig` field | Called with | +| --- | --- | +| `onForeground` | title and body of a message received while the app is open | +| `onOpenRoute` | the `route` data field of a tapped notification | + +Background messages are handled by `handleBackgroundNotification`, which is a +no-op: it runs in a separate isolate without DI or navigation. + +## Backend contract + +| Call | Request | +| --- | --- | +| register (on start and token refresh) | `POST /device-tokens/me` with `fcmToken`, `deviceId`, `deviceName`, `deviceType` | +| `NotificationClient.unregisterDevice()` | `DELETE /device-tokens/me/{deviceId}` | + +Call `unregisterDevice()` on sign-out. `dispose()` only cancels subscriptions; +it does not unregister the device. + +## Errors + +- Startup failures in `NotificationClient.init()` cancel subscriptions and are + rethrown; the call can be retried. +- Permission errors surface as `NotificationException`. +- Token, presentation, navigation and badge failures after startup are logged + and contained. +- `unregisterDevice()` propagates backend failures so the caller can decide + whether sign-out continues. + +## Privacy rules + +- `deviceId` is a random installation id kept in shared preferences, not a + hardware identifier. +- FCM tokens are never written to the log. +- Notifications can open only local app paths (`/...`); absolute URLs and + `//host` routes are ignored. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/notifications.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/notifications.dart new file mode 100644 index 0000000..e9d95d9 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/notifications.dart @@ -0,0 +1,31 @@ +library; + +import 'dart:async'; + +import 'package:core/core.dart'; +import 'package:di/di.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:notifications/src/config/index.dart'; +import 'package:notifications/src/di/index.dart'; + +export 'src/client/index.dart'; +export 'src/config/index.dart'; +export 'src/device_info/index.dart'; +export 'src/exceptions/index.dart'; +export 'src/models/index.dart'; +export 'src/services/index.dart'; + +/// Initialize the notifications module with dependency injection +Future init({ + NotificationConfig config = const DefaultNotificationConfig(), + FirebaseMessaging? messaging, +}) async { + final logger = di.get(); + try { + await registerNotificationWithDI(config, messaging: messaging); + logger.i('Notifications module initialized'); + } catch (e, s) { + logger.e('Failed to initialize notifications module', e, s); + rethrow; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/firebase_notification_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/firebase_notification_client.dart new file mode 100644 index 0000000..ceaeb3e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/firebase_notification_client.dart @@ -0,0 +1,211 @@ +import 'dart:async'; + +import 'package:app_badge_plus/app_badge_plus.dart'; +import 'package:core/logger/logger.dart'; +import 'package:firebase_messaging/firebase_messaging.dart' + hide NotificationSettings; +import 'package:notifications/notifications.dart'; + +/// Owns messaging subscriptions; presentation is supplied by the app. +class FirebaseNotificationClient implements NotificationClient { + FirebaseNotificationClient({ + required this.config, + required Logger logger, + required NotificationTokenManager tokenManager, + required NotificationPermissionManager permissionManager, + required FirebaseMessaging messaging, + Stream? foregroundMessages, + Stream? openedMessages, + Future Function()? supportsBadge, + Future Function(int)? updateBadge, + void Function(Future Function(RemoteMessage))? registerBackground, + }) : _logger = logger, + _tokenManager = tokenManager, + _permissionManager = permissionManager, + _messaging = messaging, + _foregroundMessages = foregroundMessages ?? FirebaseMessaging.onMessage, + _openedMessages = openedMessages ?? FirebaseMessaging.onMessageOpenedApp, + _supportsBadge = supportsBadge ?? AppBadgePlus.isSupported, + _updateBadge = updateBadge ?? AppBadgePlus.updateBadge, + _registerBackground = + registerBackground ?? FirebaseMessaging.onBackgroundMessage; + + final NotificationConfig config; + final Logger _logger; + final NotificationTokenManager _tokenManager; + final NotificationPermissionManager _permissionManager; + final FirebaseMessaging _messaging; + final Stream _foregroundMessages; + final Stream _openedMessages; + final Future Function() _supportsBadge; + final Future Function(int) _updateBadge; + final void Function(Future Function(RemoteMessage)) _registerBackground; + bool _isGranted = false; + bool _initialized = false; + bool _disposed = false; + Future? _initializing; + String? _fcmToken; + String? _deviceId; + StreamSubscription? _foregroundSubscription; + StreamSubscription? _openedSubscription; + StreamSubscription? _tokenSubscription; + + @override + Future init() { + if (_disposed) { + return Future.error(StateError('Notification client is disposed')); + } + if (_initialized) return Future.value(); + return _initializing ??= _initialize().whenComplete( + () => _initializing = null, + ); + } + + Future _initialize() async { + try { + _isGranted = await requestPermissions(); + if (_disposed || !_isGranted) return; + _registerBackground(handleBackgroundNotification); + _foregroundSubscription = _foregroundMessages.listen( + (message) => unawaited(handleForegroundNotification(message)), + onError: (Object error) => + _logger.e('Foreground notification stream failed', error), + ); + _openedSubscription = _openedMessages.listen( + (message) => unawaited(handleNotificationOpened(message)), + onError: (Object error) => + _logger.e('Opened notification stream failed', error), + ); + _tokenSubscription = _messaging.onTokenRefresh.listen( + (token) async { + try { + await _tokenManager.handleTokenRefresh(token); + if (!_disposed) _fcmToken = token; + } catch (error, stack) { + _logger.e('Notification token refresh failed', error, stack); + } + }, + onError: (Object error) => + _logger.e('Notification token stream failed', error), + ); + final initial = await _messaging.getInitialMessage(); + if (_disposed) return; + if (initial != null) { + await handleNotificationOpened(initial); + } + await getFCMToken(); + await clearBadge(); + if (!_disposed) _initialized = true; + } catch (error, stack) { + await _cancelSubscriptions(); + _logger.e('Notification initialization failed', error, stack); + rethrow; + } + } + + @override + Future requestPermissions({bool provisional = false}) => + _permissionManager.requestPermissions(provisional: provisional); + + @override + Future clearBadge() async { + try { + if (_disposed || !_isGranted || !await _supportsBadge()) return; + if (!_disposed) await _updateBadge(0); + } catch (error, stack) { + _logger.e('Notification badge clearing failed', error, stack); + } + } + + @override + Future getFCMToken() async { + if (_disposed) return null; + try { + final token = await _tokenManager.getFCMToken(); + if (_disposed) return null; + final device = token == null + ? null + : await _tokenManager.registerToken(token); + if (_disposed) return null; + _fcmToken = token; + _deviceId = device; + return token; + } catch (error, stack) { + _fcmToken = null; + _deviceId = null; + _logger.e('Notification token registration failed', error, stack); + return null; + } + } + + @override + Future handleForegroundNotification(RemoteMessage message) async { + if (_disposed) return; + try { + final notification = message.notification; + final title = notification?.title; + final body = notification?.body; + if (title != null && body != null) { + await config.onForeground?.call(title, body); + } + } catch (error, stack) { + _logger.e('Foreground notification presentation failed', error, stack); + } + } + + @override + Future handleNotificationOpened(RemoteMessage message) async { + if (_disposed) return; + try { + final route = message.data['route']; + // Notifications may navigate only to local app paths. + if (route is! String || + !route.startsWith('/') || + route.startsWith('//')) { + return; + } + await config.onOpenRoute?.call(route); + } catch (error, stack) { + _logger.e('Notification navigation failed', error, stack); + } + } + + @override + Future unregisterDevice() async { + final deviceId = _deviceId; + if (_disposed || deviceId == null) return; + await _tokenManager.unRegisterToken(deviceId); + _deviceId = null; + } + + @override + String? get fcmToken => _fcmToken; + @override + String? get deviceId => _deviceId; + + Future _cancelSubscriptions() async { + await _foregroundSubscription?.cancel(); + await _openedSubscription?.cancel(); + await _tokenSubscription?.cancel(); + _foregroundSubscription = null; + _openedSubscription = null; + _tokenSubscription = null; + } + + @override + Future dispose() async { + _disposed = true; + _initialized = false; + _isGranted = false; + _fcmToken = null; + _deviceId = null; + await _cancelSubscriptions(); + } +} + +/// Intentionally a no-op. FCM runs this in a separate background isolate where +/// app DI, the logger and navigation do not exist, and the OS already shows +/// notification payloads. Add isolate-safe work here (e.g. persisting data +/// messages) if your app needs it. +@pragma('vm:entry-point') +Future handleBackgroundNotification(RemoteMessage message) async {} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/index.dart new file mode 100644 index 0000000..d7fab81 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/index.dart @@ -0,0 +1,2 @@ +export 'firebase_notification_client.dart'; +export 'notification_client.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/notification_client.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/notification_client.dart new file mode 100644 index 0000000..1b65f93 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/client/notification_client.dart @@ -0,0 +1,28 @@ +import 'package:firebase_messaging/firebase_messaging.dart' + hide NotificationSettings; + +/// Messaging, permission and device-registration contract used by the app. +abstract interface class NotificationClient { + Future init(); + + Future requestPermissions({bool provisional = false}); + + Future getFCMToken(); + + Future handleForegroundNotification(RemoteMessage message); + + Future handleNotificationOpened(RemoteMessage message); + + Future clearBadge(); + + /// Removes this device's token registration from the backend, for example + /// on sign-out. Does nothing when the device was never registered. Backend + /// failures propagate so the caller decides whether sign-out continues. + Future unregisterDevice(); + + String? get fcmToken; + + String? get deviceId; + + Future dispose(); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/index.dart new file mode 100644 index 0000000..8ca3673 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/index.dart @@ -0,0 +1 @@ +export 'notification_config.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/notification_config.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/notification_config.dart new file mode 100644 index 0000000..550f726 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/config/notification_config.dart @@ -0,0 +1,12 @@ +import 'dart:async'; + +class NotificationConfig { + const NotificationConfig({this.onForeground, this.onOpenRoute}); + + final FutureOr Function(String title, String body)? onForeground; + final FutureOr Function(String route)? onOpenRoute; +} + +class DefaultNotificationConfig extends NotificationConfig { + const DefaultNotificationConfig({super.onForeground, super.onOpenRoute}); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info.dart new file mode 100644 index 0000000..2ac0dac --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info.dart @@ -0,0 +1,10 @@ +abstract interface class DeviceInfo { + Future generateDeviceId(); + + Future getDeviceName(); +} + +abstract interface class InstallationIdStore { + Future read(); + Future write(String id); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info_impl.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info_impl.dart new file mode 100644 index 0000000..cd27a78 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/device_info_impl.dart @@ -0,0 +1,87 @@ +import 'dart:math'; + +import 'package:core/logger/logger.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/foundation.dart'; +import 'package:notifications/src/device_info/device_info.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Persists a random installation identifier, independent of hardware models. +class SharedPreferencesInstallationIdStore implements InstallationIdStore { + SharedPreferencesInstallationIdStore({SharedPreferences? preferences}) + : _provided = preferences; + final SharedPreferences? _provided; + Future get _preferences async => + _provided ?? await SharedPreferences.getInstance(); + static const _key = 'nonstop.installation_id'; + + @override + Future read() async => (await _preferences).getString(_key); + + @override + Future write(String id) async { + final saved = await (await _preferences).setString(_key, id); + if (!saved) throw StateError('Could not persist installation ID'); + } +} + +/// Supplies installation identity and a human-readable device label. +class DeviceInfoImpl implements DeviceInfo { + DeviceInfoImpl({ + required Logger logger, + DeviceInfoPlugin? deviceInfoPlugin, + InstallationIdStore? store, + String Function()? createId, + }) : _logger = logger, + _plugin = deviceInfoPlugin ?? DeviceInfoPlugin(), + _store = store ?? SharedPreferencesInstallationIdStore(), + _createId = createId ?? _randomId; + + final Logger _logger; + final DeviceInfoPlugin _plugin; + final InstallationIdStore _store; + final String Function() _createId; + Future? _id; + + static String _randomId() { + final random = Random.secure(); + return List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + } + + @override + Future generateDeviceId() async { + if (_id != null) return _id!; + final pending = _loadId(); + _id = pending; + try { + return await pending; + } catch (error) { + _id = null; + _logger.w('Installation ID storage failed: $error'); + rethrow; + } + } + + Future _loadId() async { + final existing = await _store.read(); + if (existing != null && existing.isNotEmpty) return existing; + final id = _createId(); + await _store.write(id); + return id; + } + + @override + Future getDeviceName() async { + try { + final data = (await _plugin.deviceInfo).data; + final name = data['name'] ?? data['model'] ?? data['computerName']; + if (name is String && name.isNotEmpty) return name; + } catch (error) { + _logger.w('Device name unavailable: $error'); + } + return kIsWeb ? 'Web browser' : defaultTargetPlatform.name; + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/index.dart new file mode 100644 index 0000000..2bdcc90 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/device_info/index.dart @@ -0,0 +1,2 @@ +export 'device_info.dart'; +export 'device_info_impl.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/index.dart new file mode 100644 index 0000000..44acbaa --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/index.dart @@ -0,0 +1 @@ +export 'notification_di.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/notification_di.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/notification_di.dart new file mode 100644 index 0000000..65c8db4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/di/notification_di.dart @@ -0,0 +1,46 @@ +import 'package:di/di.dart'; +import 'package:core/core.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:network/network.dart'; +import 'package:notifications/src/client/index.dart'; +import 'package:notifications/src/config/index.dart'; +import 'package:notifications/src/device_info/index.dart'; +import 'package:notifications/src/services/notification_permission_manager.dart'; +import 'package:notifications/src/services/notification_token_manager.dart'; + +/// Register notification services with dependency injection +Future registerNotificationWithDI( + NotificationConfig config, { + FirebaseMessaging? messaging, +}) async { + // Composition edge: resolve collaborators once, then inject them. + final selectedMessaging = messaging ?? FirebaseMessaging.instance; + final logger = di.get(); + final networkClient = di.get(); + final deviceInfo = DeviceInfoImpl(logger: logger); + final tokenManager = FirebaseTokenManager( + logger: logger, + networkClient: networkClient, + deviceInfo: deviceInfo, + firebaseMessaging: selectedMessaging, + ); + final permissionManager = FirebasePermissionManager( + logger: logger, + firebaseMessaging: selectedMessaging, + ); + + di.register(config); + di.register(deviceInfo); + di.register(tokenManager); + di.register(permissionManager); + di.register( + FirebaseNotificationClient( + config: config, + logger: logger, + messaging: selectedMessaging, + tokenManager: tokenManager, + permissionManager: permissionManager, + ), + dispose: (client) => client.dispose(), + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/index.dart new file mode 100644 index 0000000..27be259 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/index.dart @@ -0,0 +1 @@ +export 'notification_exceptions.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/notification_exceptions.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/notification_exceptions.dart new file mode 100644 index 0000000..603caf4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/exceptions/notification_exceptions.dart @@ -0,0 +1,5 @@ +import 'package:core/core.dart'; + +class NotificationException extends CoreException { + NotificationException({required super.message}); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.dart new file mode 100644 index 0000000..34a35d5 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.dart @@ -0,0 +1,23 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'device_token_models.g.dart'; + +@JsonSerializable() +class DeviceTokenRequest { + final String fcmToken; + final String deviceId; + final String deviceName; + final String deviceType; + + const DeviceTokenRequest({ + required this.fcmToken, + required this.deviceId, + required this.deviceName, + required this.deviceType, + }); + + factory DeviceTokenRequest.fromJson(Map json) => + _$DeviceTokenRequestFromJson(json); + + Map toJson() => _$DeviceTokenRequestToJson(this); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.g.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.g.dart new file mode 100644 index 0000000..7e69fbe --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/device_token_models.g.dart @@ -0,0 +1,23 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'device_token_models.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +DeviceTokenRequest _$DeviceTokenRequestFromJson(Map json) => + DeviceTokenRequest( + fcmToken: json['fcmToken'] as String, + deviceId: json['deviceId'] as String, + deviceName: json['deviceName'] as String, + deviceType: json['deviceType'] as String, + ); + +Map _$DeviceTokenRequestToJson(DeviceTokenRequest instance) => + { + 'fcmToken': instance.fcmToken, + 'deviceId': instance.deviceId, + 'deviceName': instance.deviceName, + 'deviceType': instance.deviceType, + }; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/index.dart new file mode 100644 index 0000000..c8ac690 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/models/index.dart @@ -0,0 +1 @@ +export 'device_token_models.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/index.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/index.dart new file mode 100644 index 0000000..78c2c15 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/index.dart @@ -0,0 +1,2 @@ +export 'notification_permission_manager.dart'; +export 'notification_token_manager.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_permission_manager.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_permission_manager.dart new file mode 100644 index 0000000..f2278c8 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_permission_manager.dart @@ -0,0 +1,46 @@ +import 'package:core/logger/logger.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:network/network.dart'; +import 'package:notifications/src/exceptions/notification_exceptions.dart'; + +abstract interface class NotificationPermissionManager { + Future requestPermissions({bool provisional = false}); +} + +class FirebasePermissionManager implements NotificationPermissionManager { + static const String _tag = 'FirebasePermissionManager'; + + final Logger _logger; + final FirebaseMessaging _firebaseMessaging; + + FirebasePermissionManager({ + required Logger logger, + required FirebaseMessaging firebaseMessaging, + }) : _logger = logger, + _firebaseMessaging = firebaseMessaging; + + @override + Future requestPermissions({bool provisional = false}) async { + try { + _logger.i('$_tag: Requesting notification permissions'); + final authSettings = await _firebaseMessaging.requestPermission( + provisional: provisional, + ); + + final isGranted = + authSettings.authorizationStatus == AuthorizationStatus.authorized || + authSettings.authorizationStatus == AuthorizationStatus.provisional; + + _logger.i( + '$_tag: Notification permissions requested ' + 'with status: ${authSettings.authorizationStatus}, ' + 'granted: $isGranted', + ); + + return isGranted; + } catch (e, s) { + _logger.e('$_tag: Error requesting permissions', e, s); + throw NotificationException(message: e.message()); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_token_manager.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_token_manager.dart new file mode 100644 index 0000000..c026c20 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/lib/src/services/notification_token_manager.dart @@ -0,0 +1,104 @@ +import 'package:flutter/foundation.dart'; + +import 'package:core/logger/logger.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:network/network.dart'; +import 'package:notifications/notifications.dart'; + +abstract interface class NotificationTokenManager { + Future getFCMToken(); + + Future registerToken(String fcmToken); + + Future unRegisterToken(String deviceId); + + Future handleTokenRefresh(String newToken); +} + +class FirebaseTokenManager implements NotificationTokenManager { + static const String _tag = 'FirebaseTokenManager'; + + final Logger _logger; + final NetworkClient _networkClient; + final DeviceInfo _deviceInfo; + final FirebaseMessaging _firebaseMessaging; + + FirebaseTokenManager({ + required Logger logger, + required NetworkClient networkClient, + required DeviceInfo deviceInfo, + required FirebaseMessaging firebaseMessaging, + }) : _logger = logger, + _networkClient = networkClient, + _deviceInfo = deviceInfo, + _firebaseMessaging = firebaseMessaging; + + @override + Future getFCMToken() async { + try { + final token = await _firebaseMessaging.getToken(); + if (token != null) { + _logger.i('$_tag: FCM Token obtained successfully'); + } else { + _logger.w('$_tag: Failed to obtain FCM token'); + } + return token; + } catch (e, s) { + _logger.e('$_tag: Error getting FCM token', e, s); + rethrow; + } + } + + @override + Future registerToken(String fcmToken) async { + try { + _logger.i('$_tag: Registering FCM token with backend'); + + final deviceId = await _deviceInfo.generateDeviceId(); + final deviceName = await _deviceInfo.getDeviceName(); + final deviceType = kIsWeb ? 'web' : defaultTargetPlatform.name; + + final request = DeviceTokenRequest( + fcmToken: fcmToken, + deviceId: deviceId, + deviceName: deviceName, + deviceType: deviceType, + ); + + final response = await _networkClient.post>( + '/device-tokens/me', + data: request.toJson(), + fromJsonT: (json) => json as Map, + ); + _networkClient.handleSuccessResponse(response); + _logger.i('$_tag: FCM token registered successfully'); + return deviceId; + } catch (e, s) { + _logger.e('$_tag: Error registering FCM token', e, s); + rethrow; + } + } + + @override + Future unRegisterToken(String deviceId) async { + try { + _logger.i('$_tag: Removing FCM token from backend'); + + final response = await _networkClient.delete>( + '/device-tokens/me/$deviceId', + fromJsonT: (json) => json as Map, + ); + _networkClient.handleSuccessResponse(response); + _logger.i('$_tag: FCM token removed successfully'); + } catch (e, s) { + _logger.e('$_tag: Error removing FCM token', e, s); + rethrow; + } + } + + @override + Future handleTokenRefresh(String newToken) async { + _logger.i('$_tag: FCM token refreshed'); + await registerToken(newToken); + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/notifications/pubspec.yaml new file mode 100644 index 0000000..d15d504 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/pubspec.yaml @@ -0,0 +1,36 @@ +name: notifications +description: "Firebase Cloud Messaging, permissions and device-token management for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + shared_preferences: ^2.5.3 + flutter: + sdk: flutter + app_badge_plus: ^1.1.2 + device_info_plus: ^13.2.0 + firebase_messaging: ^16.7.0 + json_annotation: ^4.9.0 + core: + path: ../core + di: + path: ../di + network: + path: ../network + +dev_dependencies: + mocktail: ^1.0.4 + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + build_runner: ^2.4.15 + json_serializable: ^6.9.5 + +flutter: + uses-material-design: true + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/client_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/client_test.dart new file mode 100644 index 0000000..19c5471 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/client_test.dart @@ -0,0 +1,253 @@ +import 'dart:async'; + +import 'package:core/core.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:notifications/notifications.dart'; + +class _Logger extends Mock implements Logger {} + +class _Messaging extends Mock implements FirebaseMessaging {} + +class _Tokens extends Mock implements NotificationTokenManager {} + +class _Permission extends Mock implements NotificationPermissionManager {} + +void main() { + late _Logger logger; + late _Messaging messaging; + late _Tokens tokens; + late _Permission permission; + late StreamController foreground; + late StreamController opened; + late StreamController refreshed; + late FirebaseNotificationClient client; + late List routes; + late List notifications; + late List badges; + late bool supported; + late bool callbackError; + late Future Function(RemoteMessage) background; + + setUp(() { + logger = _Logger(); + messaging = _Messaging(); + tokens = _Tokens(); + permission = _Permission(); + foreground = StreamController.broadcast(); + opened = StreamController.broadcast(); + refreshed = StreamController.broadcast(); + routes = []; + notifications = []; + badges = []; + supported = true; + callbackError = false; + when( + () => + permission.requestPermissions(provisional: any(named: 'provisional')), + ).thenAnswer((_) async => true); + when(() => messaging.onTokenRefresh).thenAnswer((_) => refreshed.stream); + when(messaging.getInitialMessage).thenAnswer((_) async => null); + when(tokens.getFCMToken).thenAnswer((_) async => 'token'); + when(() => tokens.registerToken(any())).thenAnswer((_) async => 'device'); + when(() => tokens.handleTokenRefresh(any())).thenAnswer((_) async {}); + client = FirebaseNotificationClient( + config: NotificationConfig( + onForeground: (title, body) { + if (callbackError) throw StateError('presentation'); + notifications.add('$title: $body'); + }, + onOpenRoute: (route) { + if (callbackError) throw StateError('navigation'); + routes.add(route); + }, + ), + logger: logger, + tokenManager: tokens, + permissionManager: permission, + messaging: messaging, + foregroundMessages: foreground.stream, + openedMessages: opened.stream, + supportsBadge: () async => supported, + updateBadge: (value) async { + if (callbackError) throw StateError('badge'); + badges.add(value); + }, + registerBackground: (handler) { + background = handler; + }, + ); + }); + tearDown(() async { + await client.dispose(); + await foreground.close(); + await opened.close(); + await refreshed.close(); + }); + + test( + 'concurrent initialization creates one subscription and registers a token', + () async { + await Future.wait([client.init(), client.init()]); + await client.init(); + verify(() => permission.requestPermissions(provisional: false)).called(1); + expect(client.fcmToken, 'token'); + expect(client.deviceId, 'device'); + expect(badges, [0]); + await background(const RemoteMessage(messageId: 'background')); + await client.requestPermissions(provisional: true); + verify(() => permission.requestPermissions(provisional: true)).called(1); + }, + ); + + test( + 'permission denial can be retried and unsupported badges are skipped', + () async { + when( + () => permission.requestPermissions(provisional: false), + ).thenAnswer((_) async => false); + await client.init(); + await client.clearBadge(); + expect(foreground.hasListener, isFalse); + expect(badges, isEmpty); + when( + () => permission.requestPermissions(provisional: false), + ).thenAnswer((_) async => true); + supported = false; + await client.init(); + expect(foreground.hasListener, isTrue); + expect(badges, isEmpty); + }, + ); + + test( + 'foreground, opened, initial and token-refresh events reach their owners', + () async { + when(messaging.getInitialMessage).thenAnswer( + (_) async => const RemoteMessage(data: {'route': '/initial'}), + ); + await client.init(); + foreground.add( + const RemoteMessage( + notification: RemoteNotification(title: 'Title', body: 'Body'), + ), + ); + opened.add(const RemoteMessage(data: {'route': '/opened'})); + refreshed.add('new-token'); + await pumpEventQueue(); + expect(routes, ['/initial', '/opened']); + expect(notifications, ['Title: Body']); + expect(client.fcmToken, 'new-token'); + verify(() => tokens.handleTokenRefresh('new-token')).called(1); + for (final data in [ + {}, + {'route': ''}, + {'route': 1}, + {'route': 'https://outside.test'}, + {'route': '//outside.test'}, + ]) { + await client.handleNotificationOpened(RemoteMessage(data: data)); + } + await client.handleForegroundNotification(const RemoteMessage()); + expect(routes, hasLength(2)); + expect(notifications, hasLength(1)); + }, + ); + + test( + 'stream, presentation, navigation and badge failures are contained', + () async { + await client.init(); + callbackError = true; + when( + () => tokens.handleTokenRefresh(any()), + ).thenThrow(StateError('refresh')); + foreground.addError(StateError('foreground')); + opened.addError(StateError('opened')); + refreshed.addError(StateError('tokens')); + refreshed.add('new-token'); + await client.handleForegroundNotification( + const RemoteMessage( + notification: RemoteNotification(title: 'T', body: 'B'), + ), + ); + await client.handleNotificationOpened( + const RemoteMessage(data: {'route': '/home'}), + ); + await client.clearBadge(); + await pumpEventQueue(); + expect(client.fcmToken, 'token'); + expect(routes, isEmpty); + expect(notifications, isEmpty); + }, + ); + + test( + 'registration failures clear cached state and a null token does not register', + () async { + when(tokens.getFCMToken).thenAnswer((_) async => null); + expect(await client.getFCMToken(), isNull); + verifyNever(() => tokens.registerToken(any())); + when(tokens.getFCMToken).thenAnswer((_) async => 'token'); + when(() => tokens.registerToken(any())).thenThrow(StateError('backend')); + expect(await client.getFCMToken(), isNull); + expect(client.fcmToken, isNull); + expect(client.deviceId, isNull); + }, + ); + + test( + 'unregisterDevice removes only a registered device and surfaces failures', + () async { + when(() => tokens.unRegisterToken(any())).thenAnswer((_) async {}); + await client.unregisterDevice(); + verifyNever(() => tokens.unRegisterToken(any())); + await client.init(); + await client.unregisterDevice(); + verify(() => tokens.unRegisterToken('device')).called(1); + expect(client.deviceId, isNull); + await client.unregisterDevice(); + verifyNever(() => tokens.unRegisterToken(any())); + await client.getFCMToken(); + when( + () => tokens.unRegisterToken(any()), + ).thenThrow(StateError('backend')); + await expectLater(client.unregisterDevice(), throwsStateError); + expect(client.deviceId, 'device'); + await client.dispose(); + await client.unregisterDevice(); + }, + ); + + test('failed startup cancels subscriptions and can be retried', () async { + when(messaging.getInitialMessage).thenThrow(StateError('startup')); + await expectLater(client.init(), throwsStateError); + expect(foreground.hasListener, isFalse); + // Retry before subscribing again is supported by real broadcast FCM streams; + // a denied permission also demonstrates that the failed future was cleared. + when( + () => permission.requestPermissions(provisional: false), + ).thenAnswer((_) async => false); + await client.init(); + }); + + test('dispose closes listeners and prevents late startup work', () async { + final initial = Completer(); + when(messaging.getInitialMessage).thenAnswer((_) => initial.future); + final startup = client.init(); + await pumpEventQueue(); + await client.dispose(); + initial.complete(const RemoteMessage(data: {'route': '/late'})); + await startup; + expect(foreground.hasListener, isFalse); + expect(await client.getFCMToken(), isNull); + await client.handleForegroundNotification(const RemoteMessage()); + await client.handleNotificationOpened( + const RemoteMessage(data: {'route': '/late'}), + ); + await client.clearBadge(); + expect(routes, isEmpty); + await expectLater(client.init(), throwsStateError); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/device_info_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/device_info_test.dart new file mode 100644 index 0000000..e3c93ab --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/device_info_test.dart @@ -0,0 +1,104 @@ +import 'package:core/core.dart'; +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:notifications/notifications.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _Logger extends Mock implements Logger {} + +class _Plugin extends Mock implements DeviceInfoPlugin {} + +class _Info extends Mock implements BaseDeviceInfo {} + +class _Preferences extends Mock implements SharedPreferences {} + +class _Store implements InstallationIdStore { + String? value; + bool fail = false; + int writes = 0; + @override + Future read() async => value; + @override + Future write(String id) async { + if (fail) throw StateError('disk unavailable'); + writes++; + value = id; + } +} + +void main() { + test('storage rejects unsuccessful preference writes', () async { + final preferences = _Preferences(); + when( + () => preferences.setString(any(), any()), + ).thenAnswer((_) async => false); + final store = SharedPreferencesInstallationIdStore( + preferences: preferences, + ); + await expectLater(store.write('id'), throwsStateError); + }); + test( + 'concurrent requests persist one ID and new instances reuse it', + () async { + final store = _Store(); + var generated = 0; + final device = DeviceInfoImpl( + logger: _Logger(), + store: store, + createId: () => 'id-${++generated}', + ); + expect( + await Future.wait([ + device.generateDeviceId(), + device.generateDeviceId(), + ]), + ['id-1', 'id-1'], + ); + expect(store.writes, 1); + final second = DeviceInfoImpl(logger: _Logger(), store: store); + expect(await second.generateDeviceId(), 'id-1'); + }, + ); + + test('storage failures propagate and can be retried', () async { + final store = _Store()..fail = true; + final device = DeviceInfoImpl( + logger: _Logger(), + store: store, + createId: () => 'id', + ); + await expectLater(device.generateDeviceId(), throwsStateError); + store.fail = false; + expect(await device.generateDeviceId(), 'id'); + }); + + test( + 'default storage persists random IDs without hardware fingerprinting', + () async { + SharedPreferences.setMockInitialValues({}); + final first = await DeviceInfoImpl(logger: _Logger()).generateDeviceId(); + expect(first, matches(RegExp(r'^[0-9a-f]{32}$'))); + expect(await DeviceInfoImpl(logger: _Logger()).generateDeviceId(), first); + }, + ); + + test( + 'device names use plugin metadata and fall back when unavailable', + () async { + final plugin = _Plugin(); + final info = _Info(); + when(() => plugin.deviceInfo).thenAnswer((_) async => info); + final device = DeviceInfoImpl( + logger: _Logger(), + deviceInfoPlugin: plugin, + ); + when(() => info.data).thenReturn({'model': 'Test phone'}); + expect(await device.getDeviceName(), 'Test phone'); + when(() => info.data).thenReturn({}); + expect(await device.getDeviceName(), isNotEmpty); + when(() => plugin.deviceInfo).thenThrow(StateError('unavailable')); + expect(await device.getDeviceName(), isNotEmpty); + }, + ); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/services_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/services_test.dart new file mode 100644 index 0000000..b3881b1 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/notifications/test/services_test.dart @@ -0,0 +1,202 @@ +import 'package:core/core.dart'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:network/network.dart'; +import 'package:notifications/notifications.dart'; +import 'package:notifications/notifications.dart' as notifications; +import 'package:di/di.dart'; + +class _Logger extends Mock implements Logger {} + +class _Messaging extends Mock implements FirebaseMessaging {} + +class _Settings extends Mock implements NotificationSettings {} + +class _Network extends Mock implements NetworkClient {} + +class _Device extends Mock implements DeviceInfo {} + +void main() { + late _Logger logger; + late _Messaging messaging; + setUp(() { + logger = _Logger(); + messaging = _Messaging(); + }); + tearDown(di.reset); + + test('module registration failures are surfaced to startup', () async { + di.register(logger); + await expectLater( + notifications.init(messaging: messaging), + throwsA(anything), + ); + }); + + test( + 'module composition registers swappable contracts without device calls', + () async { + di.register(logger); + di.register(_Network()); + await notifications.init(messaging: messaging); + expect(di.has(), isTrue); + expect(di.has(), isTrue); + expect(di.has(), isTrue); + expect(di.has(), isTrue); + }, + ); + + for (final status in AuthorizationStatus.values) { + test( + 'permission status $status is mapped correctly and provisional forwarded', + () async { + final settings = _Settings(); + when(() => settings.authorizationStatus).thenReturn(status); + when( + () => messaging.requestPermission(provisional: true), + ).thenAnswer((_) async => settings); + final manager = FirebasePermissionManager( + logger: logger, + firebaseMessaging: messaging, + ); + expect( + await manager.requestPermissions(provisional: true), + status == AuthorizationStatus.authorized || + status == AuthorizationStatus.provisional, + ); + }, + ); + } + + test( + 'permission errors are reported through the notification contract', + () async { + when( + () => messaging.requestPermission(provisional: false), + ).thenThrow(StateError('unavailable')); + final manager = FirebasePermissionManager( + logger: logger, + firebaseMessaging: messaging, + ); + await expectLater( + manager.requestPermissions(), + throwsA(isA()), + ); + }, + ); + + group('token manager', () { + late _Network network; + late _Device device; + late FirebaseTokenManager manager; + const success = SuccessResponse>( + statusCode: 200, + success: true, + data: {}, + timestamp: '2026-01-01', + ); + setUp(() { + network = _Network(); + device = _Device(); + manager = FirebaseTokenManager( + logger: logger, + networkClient: network, + deviceInfo: device, + firebaseMessaging: messaging, + ); + registerFallbackValue((Object? json) => json as Map); + when(device.generateDeviceId).thenAnswer((_) async => 'install-1'); + when(device.getDeviceName).thenAnswer((_) async => 'Test device'); + when( + () => network.post>( + any(), + data: any(named: 'data'), + fromJsonT: any(named: 'fromJsonT'), + ), + ).thenAnswer((call) async { + final decode = + call.namedArguments[#fromJsonT] + as Map Function(Object?); + expect(decode({'ok': true}), {'ok': true}); + return success; + }); + when( + () => network.delete>( + any(), + fromJsonT: any(named: 'fromJsonT'), + ), + ).thenAnswer((call) async { + final decode = + call.namedArguments[#fromJsonT] + as Map Function(Object?); + expect(decode({'ok': true}), {'ok': true}); + return success; + }); + when( + () => network.handleSuccessResponse>(success), + ).thenReturn(success); + }); + + test('returns nullable FCM tokens and propagates SDK failures', () async { + when(() => messaging.getToken()).thenAnswer((_) async => 'token'); + expect(await manager.getFCMToken(), 'token'); + when(() => messaging.getToken()).thenAnswer((_) async => null); + expect(await manager.getFCMToken(), isNull); + when(() => messaging.getToken()).thenThrow(StateError('offline')); + await expectLater(manager.getFCMToken(), throwsStateError); + }); + + test('registers metadata, refreshes and unregisters', () async { + expect(await manager.registerToken('token'), 'install-1'); + final data = + verify( + () => network.post>( + '/device-tokens/me', + data: captureAny(named: 'data'), + fromJsonT: any(named: 'fromJsonT'), + ), + ).captured.single + as Map; + expect(data['fcmToken'], 'token'); + expect(data['deviceId'], 'install-1'); + expect(data['deviceName'], 'Test device'); + await manager.handleTokenRefresh('next-token'); + await manager.unRegisterToken('install-1'); + verify( + () => network.handleSuccessResponse>(success), + ).called(3); + }); + + test( + 'application-level backend rejection cannot be reported as success', + () async { + when( + () => network.handleSuccessResponse>(success), + ).thenThrow(UnauthorizedException()); + await expectLater( + manager.registerToken('token'), + throwsA(isA()), + ); + await expectLater( + manager.unRegisterToken('install-1'), + throwsA(isA()), + ); + }, + ); + }); + + test('token request models round-trip JSON', () { + const request = DeviceTokenRequest( + fcmToken: 'token', + deviceId: 'id', + deviceName: 'phone', + deviceType: 'ios', + ); + expect( + DeviceTokenRequest.fromJson(request.toJson()).toJson(), + request.toJson(), + ); + expect(const DefaultNotificationConfig(), isA()); + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/utils/CLAUDE.md new file mode 100644 index 0000000..3fe8f38 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/CLAUDE.md @@ -0,0 +1,53 @@ +# Nonstop Example: `packages/utils` + +Pure, dependency-light formatting extensions on `double`, `num`, `int` and +`DateTime` (layer 0). It owns stateless value-to-string helpers only: no DI +registration, no `init()`, no widgets, no I/O, no workspace dependencies. + +Read the root `CLAUDE.md` and `packages/CLAUDE.md` first. + +## Public API + +Exported from `package:utils/utils.dart`. + +| Symbol | Member | Output | +|---|---|---| +| `DoubleFormatting` on `double` | `format({decimalPlaces = 1})` | `NumberFormat('#.#...')`; drops a trailing `.0` (`2.0` -> `2`) | +| | `asScore()` | `format(decimalPlaces: 1)` | +| `NumFormatting` on `num` | `compact()` | `NumberFormat.compact()` in the default `intl` locale (`1250` -> `1.25K` in `en`) | +| `IntTimeFormatting` on `int` | `asTime({sec, min, hr})` | Seconds -> `59 sec`, `1 min`, `1 min 1 sec`, `1 hr`, `1 hr 1 min`; unit labels overridable | +| `DateTimeFormatting` on `DateTime` | `formatRelative({now, justNow, yesterday, minutesAgo, hoursAgo, daysAgo})` | `Just now`, `Nm ago`, `Nh ago`, `Yesterday`, `Nd ago`, else `DateFormat.yMd()` in the default locale; every label overridable | + +## Layout + +| Path | Responsibility | +|---|---| +| `lib/utils.dart` | Barrel | +| `lib/src/number_formatter.dart` | `DoubleFormatting`, `NumFormatting`, `IntTimeFormatting` | +| `lib/src/date_time_formatter.dart` | `DateTimeFormatting` | + +## Rules + +- Only dependency is `intl` (plus the Flutter SDK). Keep it that way; a helper that needs `core`, `di` or an SDK belongs in that package. +- Extensions are pure functions of their receiver and arguments. Time-dependent code takes an optional clock value (`formatRelative({now})`) so tests are deterministic. +- Add a new topic as a new file under `lib/src/` exported from `lib/utils.dart`, rather than growing an unrelated one. +- Any user-visible word is a parameter with an English default; callers pass `strings.*` values. Never import `localization` here. +- Display dates for UI already have `core`'s `DateTimeConverter`; do not duplicate those formats here. + +## Common changes + +- **Add a formatter:** add a method to the matching extension (or a new extension in `lib/src/.dart`, exported from `lib/utils.dart`), and add boundary cases to `test/formatters_test.dart`. +- **Change a threshold in `asTime` / `formatRelative`:** update the boundary tables in the existing tests first; they enumerate every branch. + +## Tests + +`test/formatters_test.dart` covers decimal formatting, `asScore`, `compact` (including a `de` locale via `Intl.withLocale`), all `asTime` boundaries (0, 59, 60, 61, 3599, 3600, 3660) plus custom labels, and every `formatRelative` branch with an injected `now`, one real-clock call and custom labels. Pattern: `Map` tables iterated in a loop. + +Run: `dart run melos exec --scope=utils -- flutter test`. `dart run melos run coverage` must stay 100%. + +## Gotchas + +- Label defaults (`sec`, `min`, `hr`, `Just now`, `Yesterday`, `Nm ago`) are English; for user-facing copy pass localized labels from the call site. +- `compact()`, `format()` and the `formatRelative` date fallback follow the default `intl` locale (`Intl.defaultLocale`). +- `formatRelative` treats future dates as `Just now` (negative difference is `< 1` minute). +- The app's `pubspec.yaml` depends on `utils`, but no Dart code in `apps/` or `features/` imports it yet. diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/date_time_formatter.dart b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/date_time_formatter.dart new file mode 100644 index 0000000..5b8f23a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/date_time_formatter.dart @@ -0,0 +1,37 @@ +import 'package:intl/intl.dart'; + +String _minutesAgo(int minutes) => '${minutes}m ago'; +String _hoursAgo(int hours) => '${hours}h ago'; +String _daysAgo(int days) => '${days}d ago'; + +extension DateTimeFormatting on DateTime { + /// Formats this time relative to [now]: `Just now`, `5m ago`, `3h ago`, + /// `Yesterday`, `2d ago`, then a short date in the default intl locale. + /// + /// Labels default to English; pass localized ones (utils stays free of the + /// localization package). + String formatRelative({ + DateTime? now, + String justNow = 'Just now', + String yesterday = 'Yesterday', + String Function(int minutes) minutesAgo = _minutesAgo, + String Function(int hours) hoursAgo = _hoursAgo, + String Function(int days) daysAgo = _daysAgo, + }) { + final difference = (now ?? DateTime.now()).difference(this); + + if (difference.inMinutes < 1) { + return justNow; + } else if (difference.inMinutes < 60) { + return minutesAgo(difference.inMinutes); + } else if (difference.inHours < 24) { + return hoursAgo(difference.inHours); + } else if (difference.inDays == 1) { + return yesterday; + } else if (difference.inDays < 7) { + return daysAgo(difference.inDays); + } else { + return DateFormat.yMd().format(this); + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/number_formatter.dart b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/number_formatter.dart new file mode 100644 index 0000000..2a378ac --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/src/number_formatter.dart @@ -0,0 +1,45 @@ +import 'package:intl/intl.dart'; + +/// Extension for formatting decimal numbers with clean, professional display +extension DoubleFormatting on double { + /// Formats decimal values, removing unnecessary .0 for whole numbers + String format({int decimalPlaces = 1}) { + final formatter = NumberFormat('#.${'#' * decimalPlaces}'); + return formatter.format(this); + } + + /// Formats score values with clean decimal handling + String asScore() => format(decimalPlaces: 1); +} + +/// Extension for formatting any numeric value +extension NumFormatting on num { + /// Formats large numbers with the default locale's compact suffixes. + String compact() => NumberFormat.compact().format(this); +} + +/// Extension for formatting time duration from seconds +extension IntTimeFormatting on int { + /// Formats seconds as `1 sec`, `1 min 1 sec` or `1 hr 1 min`. + /// + /// Unit labels default to English abbreviations; pass localized ones. + String asTime({String sec = 'sec', String min = 'min', String hr = 'hr'}) { + if (this < 60) { + return '$this $sec'; + } else if (this < 3600) { + final minutes = this ~/ 60; + final remainingSeconds = this % 60; + if (remainingSeconds == 0) { + return '$minutes $min'; + } + return '$minutes $min $remainingSeconds $sec'; + } else { + final hours = this ~/ 3600; + final remainingMinutes = (this % 3600) ~/ 60; + if (remainingMinutes == 0) { + return '$hours $hr'; + } + return '$hours $hr $remainingMinutes $min'; + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/utils.dart b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/utils.dart new file mode 100644 index 0000000..a8ee40a --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/lib/utils.dart @@ -0,0 +1,4 @@ +library; + +export 'src/date_time_formatter.dart'; +export 'src/number_formatter.dart'; diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/packages/utils/pubspec.yaml new file mode 100644 index 0000000..ebb24d4 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/pubspec.yaml @@ -0,0 +1,22 @@ +name: utils +description: "Shared, dependency-light helpers for Nonstop Example." +version: 0.1.0 +publish_to: 'none' + +environment: + sdk: ^3.8.0 + flutter: ">=3.47.5" + +dependencies: + flutter: + sdk: flutter + intl: ^0.20.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + +flutter: + +resolution: workspace diff --git a/packages/nonstop_cli/example/nonstop_example/packages/utils/test/formatters_test.dart b/packages/nonstop_cli/example/nonstop_example/packages/utils/test/formatters_test.dart new file mode 100644 index 0000000..c6d8097 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/packages/utils/test/formatters_test.dart @@ -0,0 +1,66 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:intl/intl.dart'; +import 'package:utils/utils.dart'; + +void main() { + test('formats decimals and compact numbers', () { + expect(2.0.format(), '2'); + expect(2.125.format(decimalPlaces: 2), '2.13'); + expect(2.25.asScore(), '2.3'); + expect(1250.compact(), '1.25K'); + Intl.withLocale('de', () => expect(1250.compact(), '1250')); + }); + + test('formats duration boundaries', () { + for (final entry in { + 0: '0 sec', + 59: '59 sec', + 60: '1 min', + 61: '1 min 1 sec', + 3599: '59 min 59 sec', + 3600: '1 hr', + 3660: '1 hr 1 min', + }.entries) { + expect(entry.key.asTime(), entry.value); + } + expect(3661.asTime(sec: 's', min: 'm', hr: 'h'), '1 h 1 m'); + expect(61.asTime(sec: 's', min: 'm', hr: 'h'), '1 m 1 s'); + }); + + test('relative time has deterministic minute, hour and date boundaries', () { + final now = DateTime(2026, 1, 15, 12); + for (final entry in { + Duration.zero: 'Just now', + const Duration(minutes: 1): '1m ago', + const Duration(hours: 1): '1h ago', + const Duration(days: 1): 'Yesterday', + const Duration(days: 3): '3d ago', + const Duration(days: 7): '1/8/2026', + }.entries) { + expect(now.subtract(entry.key).formatRelative(now: now), entry.value); + } + expect(DateTime.now().formatRelative(), 'Just now'); + String label(int n) => 'vor $n'; + for (final entry in { + Duration.zero: 'Gerade eben', + const Duration(minutes: 2): 'vor 2', + const Duration(hours: 2): 'vor 2', + const Duration(days: 1): 'Gestern', + const Duration(days: 2): 'vor 2', + }.entries) { + expect( + now + .subtract(entry.key) + .formatRelative( + now: now, + justNow: 'Gerade eben', + yesterday: 'Gestern', + minutesAgo: label, + hoursAgo: label, + daysAgo: label, + ), + entry.value, + ); + } + }); +} diff --git a/packages/nonstop_cli/example/nonstop_example/plugins/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/plugins/CLAUDE.md new file mode 100644 index 0000000..5a14216 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/plugins/CLAUDE.md @@ -0,0 +1,26 @@ +# Nonstop Example: `plugins/` + +Native platform integrations (method/event channels, FFI). Read the root +`CLAUDE.md` first. Create one with: + +```sh +nonstop create my_plugin --template plugin -o plugins +``` + +`nonstop create` registers it in the workspace. It also adds a starter `CLAUDE.md`; +fill it in like every other member (see the `melos-workspace` skill). A plugin that renders UI +follows the `design-system` skill. + +## Rules + +- Check pub.dev for a maintained plugin before writing one. +- A plugin depends on nothing in `apps/`, `features/` or `packages/`. +- Expose a Dart contract; keep channel names, argument maps and platform + exceptions private to the plugin. Convert `PlatformException` into typed + exceptions at the boundary. +- Every platform the plugin declares in `pubspec.yaml` must be implemented or + throw `UnimplementedError` with a clear message. +- Native code follows the platform's conventions (Kotlin for Android, Swift for + iOS). Do not block the platform main thread. +- Tests mock the channel with `TestDefaultBinaryMessengerBinding`; native code + gets its own platform tests when it has logic. diff --git a/packages/nonstop_cli/example/nonstop_example/plugins/README.md b/packages/nonstop_cli/example/nonstop_example/plugins/README.md new file mode 100644 index 0000000..8e79d28 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/plugins/README.md @@ -0,0 +1,7 @@ +# Plugins + +Platform channels and native integrations. + +```sh +nonstop create my_plugin --template plugin -o plugins +``` diff --git a/packages/nonstop_cli/example/nonstop_example/pubspec.yaml b/packages/nonstop_cli/example/nonstop_example/pubspec.yaml new file mode 100644 index 0000000..4d1e546 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/pubspec.yaml @@ -0,0 +1,100 @@ +name: nonstop_example_workspace +description: "Reference project generated by nonstop_cli." +publish_to: 'none' + +environment: + sdk: '>=3.8.0 <4.0.0' + +dev_dependencies: + flutter_lints: ^6.0.0 + melos: ^8.8.0 + path: ^1.9.1 + +workspace: + - apps/nonstop_example + - packages/core + - packages/design_system + - packages/di + - packages/localization + - packages/utils + - packages/network + - packages/notifications + - packages/analytics + - packages/crashlytics + - packages/feature_flags + - packages/developer + - features/auth + - features/dashboard + +melos: + scripts: + clean:flutter: + description: "Run flutter clean in all Flutter packages" + exec: + command: flutter clean + concurrency: 4 + packageFilters: + flutter: true + + lint: + description: "Check formatting and analyze all workspace code" + run: dart run tool/check.dart + + fix: + description: "Apply Dart automated fixes to all packages" + exec: + command: dart fix --apply + concurrency: 5 + packageFilters: + dirExists: lib + + fix:dry: + description: "Show Dart automated fixes without applying them" + exec: + command: dart fix --dry-run + concurrency: 5 + packageFilters: + dirExists: lib + + generate: + description: "Run build_runner in every package that needs codegen" + exec: + command: dart run build_runner build --delete-conflicting-outputs + concurrency: 1 + packageFilters: + dependsOn: build_runner + + generate:i69n: + description: "Regenerate localization strings from messages.i69n.yaml" + exec: + command: | + dart run build_runner build --delete-conflicting-outputs && + dart format lib/messages.i69n.dart + concurrency: 1 + packageFilters: + scope: "localization" + + test: + description: "Run all tests (Dart and Flutter)" + run: dart run melos run test:select --no-select + + coverage: + description: "Run every test and require 100% handwritten line coverage" + run: dart run tool/coverage.dart + + test:select: + description: "Run tests in Flutter packages" + exec: + command: flutter test --coverage + concurrency: 5 + failFast: true + packageFilters: + dirExists: test + + ############################################################################### + # IDE CONFIGURATION + ############################################################################### + ide: + intellij: + enabled: true + moduleNamePrefix: '' diff --git a/packages/nonstop_cli/example/nonstop_example/tool/check.dart b/packages/nonstop_cli/example/nonstop_example/tool/check.dart new file mode 100644 index 0000000..d84f40e --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/tool/check.dart @@ -0,0 +1,55 @@ +import 'dart:io'; +import 'package:path/path.dart' as p; + +/// Portable, non-mutating format and analyzer checks from the workspace root. +Future main() async { + final sources = []; + void collect(Directory directory) { + if (!directory.existsSync()) { + return; + } + for (final entry in directory.listSync(followLinks: false)) { + if (entry is Directory) { + if (![ + 'build', + '.dart_tool', + '.symlinks', + ].contains(p.basename(entry.path))) { + collect(entry); + } + } else if (entry is File && + entry.path.endsWith('.dart') && + !RegExp(r'\.(g|freezed|i69n)\.dart$').hasMatch(entry.path)) { + sources.add(entry.path); + } + } + } + + collect(Directory('tool')); + for (final area in ['apps', 'features', 'packages', 'plugins']) { + final directory = Directory(area); + if (!directory.existsSync()) { + continue; + } + for (final package in directory.listSync().whereType()) { + collect(Directory(p.join(package.path, 'lib'))); + collect(Directory(p.join(package.path, 'test'))); + } + } + sources.sort(); + for (final arguments in [ + ['format', '--output=none', '--set-exit-if-changed', ...sources], + ['analyze', '--fatal-infos', ...sources], + ]) { + final process = await Process.start( + 'dart', + arguments, + mode: ProcessStartMode.inheritStdio, + ); + final result = await process.exitCode; + if (result != 0) { + exitCode = result; + return; + } + } +} diff --git a/packages/nonstop_cli/example/nonstop_example/tool/coverage.dart b/packages/nonstop_cli/example/nonstop_example/tool/coverage.dart new file mode 100644 index 0000000..40f7a62 --- /dev/null +++ b/packages/nonstop_cli/example/nonstop_example/tool/coverage.dart @@ -0,0 +1,165 @@ +import 'dart:io'; +import 'package:path/path.dart' as p; + +/// Run from the workspace root: dart run tool/coverage.dart [--report-only]. +/// Only compiler-generated serializers/translations are excluded. +Future main(List args) async { + final root = Directory(Directory.current.resolveSymbolicLinksSync()); + final merged = >{}; + var failed = false; + final reportOnly = args.contains('--report-only'); + final names = []; + for (final area in ['apps', 'features', 'packages', 'plugins']) { + final directory = Directory('${root.path}/$area'); + if (!directory.existsSync()) continue; + for (final package in directory.listSync().whereType()) { + final manifest = File('${package.path}/pubspec.yaml'); + if (manifest.existsSync()) { + final name = RegExp( + r'^name:\s*(\S+)', + multiLine: true, + ).firstMatch(manifest.readAsStringSync())!.group(1)!; + names.add(RegExp.escape(name)); + } + } + } + final coveragePackages = '^(${names.join('|')})\$'; + for (final area in ['apps', 'features', 'packages', 'plugins']) { + final directory = Directory('${root.path}/$area'); + if (!directory.existsSync()) continue; + final packages = directory.listSync().whereType().toList() + ..sort((a, b) => a.path.compareTo(b.path)); + for (final package in packages) { + final manifest = File('${package.path}/pubspec.yaml'); + if (!manifest.existsSync()) continue; + final name = RegExp( + r'^name:\s*(\S+)', + multiLine: true, + ).firstMatch(manifest.readAsStringSync())!.group(1)!; + final testDirectory = Directory('${package.path}/test'); + if (!testDirectory.existsSync() || + !testDirectory + .listSync(recursive: true) + .whereType() + .any((f) => f.path.endsWith('_test.dart'))) { + stderr.writeln('$area/$name: missing tests'); + failed = true; + continue; + } + final report = File('${package.path}/coverage/lcov.info'); + if (!reportOnly) { + final imports = File( + '${testDirectory.path}/coverage_imports_test.dart', + ); + if (imports.existsSync()) { + throw StateError('Refusing to overwrite ${imports.path}'); + } + final sources = + Directory('${package.path}/lib') + .listSync(recursive: true) + .whereType() + .where((f) => f.path.endsWith('.dart')) + .where( + (f) => !RegExp(r'\.(g|freezed|i69n)\.dart$').hasMatch(f.path), + ) + .where( + (f) => !RegExp( + r'^part of ', + multiLine: true, + ).hasMatch(f.readAsStringSync()), + ) + .toList() + ..sort((a, b) => a.path.compareTo(b.path)); + imports.writeAsStringSync( + [ + '// Generated temporarily by tool/coverage.dart.', + '// ignore_for_file: unused_import', + for (final source in sources) + "import 'package:$name/${p.relative(source.path, from: p.join(package.path, 'lib')).replaceAll(r'\', '/')}';", + "import 'package:flutter_test/flutter_test.dart';", + 'void main() { TestWidgetsFlutterBinding.ensureInitialized(); }', + ].join('\n'), + ); + try { + if (report.existsSync()) report.deleteSync(); + final process = await Process.start( + 'flutter', + ['test', '--coverage', '--coverage-package=$coveragePackages'], + workingDirectory: package.path, + mode: ProcessStartMode.inheritStdio, + ); + if (await process.exitCode != 0) failed = true; + } finally { + imports.deleteSync(); + } + } + if (!report.existsSync()) { + stderr.writeln('$area/$name: missing coverage report'); + failed = true; + continue; + } + String? source; + for (final line in report.readAsLinesSync()) { + if (line.startsWith('SF:')) { + final path = line.substring(3); + var absolute = p.normalize( + p.isAbsolute(path) ? path : p.join(package.path, path), + ); + // VM reports may use /var while the workspace resolves to /private/var + // on macOS (or another symlink on Linux). Merge the same real source. + final sourceFile = File(absolute); + if (sourceFile.existsSync()) { + absolute = sourceFile.resolveSymbolicLinksSync(); + } + source = p.isWithin(root.path, absolute) + ? p.relative(absolute, from: root.path).replaceAll(r'\', '/') + : null; + if (source != null && + !RegExp( + r'^(apps|features|packages|plugins)/[^/]+/lib/', + ).hasMatch(source)) { + source = null; + } + if (source != null && + RegExp(r'\.(g|freezed|i69n)\.dart$').hasMatch(source)) { + source = null; + } + } else if (line.startsWith('DA:') && source != null) { + final fields = line.substring(3).split(','); + final number = int.parse(fields[0]); + final hits = int.parse(fields[1]); + final lines = merged.putIfAbsent(source, () => {}); + lines[number] = (lines[number] ?? 0) + hits; + } + } + } + } + var covered = 0; + var total = 0; + final output = StringBuffer(); + for (final source in merged.keys.toList()..sort()) { + final lines = merged[source]!; + final missing = + lines.entries.where((e) => e.value == 0).map((e) => e.key).toList() + ..sort(); + covered += lines.length - missing.length; + total += lines.length; + output.writeln('SF:$source'); + for (final line in lines.keys.toList()..sort()) { + output.writeln('DA:$line,${lines[line]}'); + } + output.writeln('LF:${lines.length}'); + output.writeln('LH:${lines.length - missing.length}'); + output.writeln('end_of_record'); + if (missing.isNotEmpty) { + stdout.writeln('$source: uncovered lines ${missing.join(", ")}'); + } + } + Directory('coverage').createSync(recursive: true); + File('coverage/lcov.info').writeAsStringSync(output.toString()); + stdout.writeln( + 'Coverage: $covered/$total executable lines ' + '(${total == 0 ? "0.00" : (100 * covered / total).toStringAsFixed(2)}%)', + ); + if (failed || total == 0 || covered != total) exitCode = 1; +} diff --git a/packages/nonstop_cli/tool/generate_example.sh b/packages/nonstop_cli/tool/generate_example.sh new file mode 100644 index 0000000..c0bfd2b --- /dev/null +++ b/packages/nonstop_cli/tool/generate_example.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Regenerates example/nonstop_example from the current bricks with every module +# enabled. The output is committed: it is the reviewable snapshot of what +# `nonstop create` produces. Never hand-edit it; change the brick and rerun. +# +# Usage (from anywhere): bash packages/nonstop_cli/tool/generate_example.sh +set -euo pipefail + +cli="$(cd "$(dirname "$0")/.." && pwd)" +repo="$(cd "$cli/../.." && pwd)" +name=nonstop_example + +(cd "$repo" && dart run tools/update_nonstop_cli_bundles.dart) + +rm -rf "$cli/example/$name" +cd "$cli" +dart run bin/nonstop.dart create "$name" \ + --defaults --network --auth --firestore --notifications --analytics \ + --crashlytics --feature-flags --developer --dashboard \ + --org io.nonstop \ + --description "Reference project generated by nonstop_cli." \ + --output-directory example diff --git a/pubspec.yaml b/pubspec.yaml index d3aa391..948b5b2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -58,7 +58,7 @@ melos: # and build artifacts; untracked source is included during development. run: | git ls-files -z --cached --others --exclude-standard -- '*.dart' \ - ':(exclude)**/__brick__/**' ':(exclude)**/coverage/**' ':(exclude)**/build/**' \ + ':(exclude)**/__brick__/**' ':(exclude)packages/nonstop_cli/example/nonstop_example/**' ':(exclude)**/coverage/**' ':(exclude)**/build/**' \ | xargs -0 dart format --output=none --set-exit-if-changed && dart analyze --fatal-infos . fix: @@ -78,6 +78,9 @@ melos: run: dart run tools/update_nonstop_cli_version.dart update_nonstop_cli_bundles: run: dart run tools/update_nonstop_cli_bundles.dart + generate:nonstop_example: + description: "Regenerate packages/nonstop_cli/example/nonstop_example from the current bricks" + run: bash packages/nonstop_cli/tool/generate_example.sh sync:readme: description: "Sync README sections across all packages" run: dart run tools/readme_sync/readme_sync.dart From ebcd18bf6af8954109c5318a222d0a92a96c66f7 Mon Sep 17 00:00:00 2001 From: Ajay Kumar Date: Tue, 29 Sep 2026 16:09:34 +0530 Subject: [PATCH 4/5] docs(nonstop_cli): always list Environment constants in core CLAUDE.md `useEmulators` and `baseUrl` exist in every generated project, so the core package doc now lists both regardless of which modules were selected. Co-Authored-By: Claude Opus 5.5 --- .../__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md | 2 +- .../nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md | 2 +- .../commands/create/flutter_project_with_mono_repo_bundle.dart | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md index d78e39e..d4259a0 100644 --- a/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md +++ b/packages/nonstop_cli/bricks/flutter_project_with_mono_repo/__brick__/{{ name.snakeCase() }}/packages/core/CLAUDE.md @@ -18,7 +18,7 @@ Exported from `package:core/core.dart` unless noted. | `Logger` | `abstract interface class` | `d`, `i`, `w`, `e(message, [error, stackTrace])`, `Object get logger` (raw backend) | | `registerLoggerWithDI()` | function | `di.register(TalkerLoggerImpl(TalkerFlutter.init()))` | | `TalkerLoggerImpl` | implementation | Not in the barrel; import `package:core/logger/talker_logger_impl.dart` | -| `Environment` | constants | {{#emulators}}`useEmulators` (`USE_EMULATORS`){{#network}}, {{/network}}{{/emulators}}{{#network}}`baseUrl` (`BASE_URL`){{/network}}{{^emulators}}{{^network}}Build-time `--dart-define` values{{/network}}{{/emulators}} | +| `Environment` | constants | `useEmulators` (`USE_EMULATORS`), `baseUrl` (`BASE_URL`, default `https://api.example.com`) | | `CoreRoutes`, `Keys`, `Defaults` | constants | Shell paths, query/extra keys, `defaultPageSize` | | `CoreRouter` | `abstract interface class` | `List get routes`; feature/package routers `implements` it | | `CoreBlocObserver`, `CoreRouteObserver` | observers | Optional `logger:`; fall back to `di.get()` | diff --git a/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md b/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md index 399b47e..7f60e61 100644 --- a/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md +++ b/packages/nonstop_cli/example/nonstop_example/packages/core/CLAUDE.md @@ -18,7 +18,7 @@ Exported from `package:core/core.dart` unless noted. | `Logger` | `abstract interface class` | `d`, `i`, `w`, `e(message, [error, stackTrace])`, `Object get logger` (raw backend) | | `registerLoggerWithDI()` | function | `di.register(TalkerLoggerImpl(TalkerFlutter.init()))` | | `TalkerLoggerImpl` | implementation | Not in the barrel; import `package:core/logger/talker_logger_impl.dart` | -| `Environment` | constants | `useEmulators` (`USE_EMULATORS`), `baseUrl` (`BASE_URL`) | +| `Environment` | constants | `useEmulators` (`USE_EMULATORS`), `baseUrl` (`BASE_URL`, default `https://api.example.com`) | | `CoreRoutes`, `Keys`, `Defaults` | constants | Shell paths, query/extra keys, `defaultPageSize` | | `CoreRouter` | `abstract interface class` | `List get routes`; feature/package routers `implements` it | | `CoreBlocObserver`, `CoreRouteObserver` | observers | Optional `logger:`; fall back to `di.get()` | diff --git a/packages/nonstop_cli/lib/commands/create/flutter_project_with_mono_repo_bundle.dart b/packages/nonstop_cli/lib/commands/create/flutter_project_with_mono_repo_bundle.dart index ffdf006..5eb6845 100644 --- a/packages/nonstop_cli/lib/commands/create/flutter_project_with_mono_repo_bundle.dart +++ b/packages/nonstop_cli/lib/commands/create/flutter_project_with_mono_repo_bundle.dart @@ -469,7 +469,7 @@ final flutterProjectWithMonoRepoBundle = MasonBundle.fromJson({ { "path": "{{ name.snakeCase() }}/packages/core/CLAUDE.md", "data": - "IyB7e25hbWUudGl0bGVDYXNlKCl9fTogYHBhY2thZ2VzL2NvcmVgCgpDcm9zcy1jdXR0aW5nIGZvdW5kYXRpb24gKGxheWVyIDEpOiB0aGUgYExvZ2dlcmAgY29udHJhY3QgYW5kIGl0cyBUYWxrZXIKaW1wbGVtZW50YXRpb24sIGJ1aWxkLXRpbWUgYEVudmlyb25tZW50YCwgc2hhcmVkIHJvdXRlL3F1ZXJ5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[PATCH 5/5] test(nonstop_cli): cover workspace joining from templates and malformed pubspecs The coverage gate flagged two lines: the templates' "added to the workspace" log and the lookup skipping an unparsable pubspec on the way up. Co-Authored-By: Claude Opus 5.5 --- .../src/commands/create_behavior_test.dart | 23 +++++++++++++++++++ .../test/src/utils/workspace_test.dart | 9 ++++++++ 2 files changed, 32 insertions(+) diff --git a/packages/nonstop_cli/test/src/commands/create_behavior_test.dart b/packages/nonstop_cli/test/src/commands/create_behavior_test.dart index f753504..985a3b8 100644 --- a/packages/nonstop_cli/test/src/commands/create_behavior_test.dart +++ b/packages/nonstop_cli/test/src/commands/create_behavior_test.dart @@ -61,6 +61,29 @@ void main() { } }); + test('member templates join the enclosing workspace; mono does not', + () async { + final root = Directory.systemTemp.createTempSync('join_workspace_'); + addTearDown(() => root.deleteSync(recursive: true)); + File('${root.path}/pubspec.yaml') + .writeAsStringSync('name: w\nworkspace:\n - packages/core\n'); + final logger = _Logger(); + final templates = CreateCommand(logger: logger).templates; + for (final (index, template) in templates.indexed) { + final member = Directory('${root.path}/packages/m$index') + ..createSync(recursive: true); + File('${member.path}/pubspec.yaml').writeAsStringSync('name: m$index\n'); + await template.onGenerateComplete(logger, member); + } + final workspace = File('${root.path}/pubspec.yaml').readAsStringSync(); + expect(workspace, isNot(contains('packages/m0'))); + for (final index in [1, 2, 3]) { + expect(workspace, contains('packages/m$index')); + } + verify(() => logger.info(any(that: contains('to the workspace in')))) + .called(3); + }); + test('all templates show output directory and getting-started instructions', () async { final logger = _Logger(); diff --git a/packages/nonstop_cli/test/src/utils/workspace_test.dart b/packages/nonstop_cli/test/src/utils/workspace_test.dart index 0d160e9..190c7a3 100644 --- a/packages/nonstop_cli/test/src/utils/workspace_test.dart +++ b/packages/nonstop_cli/test/src/utils/workspace_test.dart @@ -60,6 +60,15 @@ void main() { expect(member.readAsStringSync(), 'name: a\n'); }); + test('skips a malformed pubspec on the way up', () { + final rootPubspec = write('pubspec.yaml', 'name: w\nworkspace:\n - a\n'); + write('group/pubspec.yaml', 'name: [unterminated\n'); + final member = write('group/b/pubspec.yaml', 'name: b\n'); + + expect(registerWorkspaceMember(member.parent)?.path, rootPubspec.path); + expect(rootPubspec.readAsStringSync(), contains('group/b')); + }); + test('does nothing without a member pubspec', () { write('pubspec.yaml', 'name: w\nworkspace:\n - a\n'); final member = Directory(p.join(root.path, 'b'))..createSync();