diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 48cd0da45..81b783438 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -68,7 +68,7 @@ jobs: dart pub global activate -spath packages/cli dart pub global activate melos melos bootstrap - melos cache-source + melos cache-source --no-select dart pub get --directory=packages/isolate_exec_test_packages/test_package --offline dart pub get --directory=packages/runtime_test_packages/application --offline dart pub get --directory=packages/runtime_test_packages/dependency --offline diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index d6ad7bc81..71bc4249a 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -72,7 +72,7 @@ jobs: dart pub global activate -spath packages/cli dart pub global activate melos melos bootstrap - melos cache-source + melos cache-source --no-select dart pub get --directory=packages/isolate_exec_test_packages/test_package --offline dart pub get --directory=packages/runtime_test_packages/application --offline dart pub get --directory=packages/runtime_test_packages/dependency --offline diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index fb09e4c23..f6122f94f 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -75,7 +75,7 @@ jobs: dart pub global activate -spath packages/cli dart pub global activate melos dart pub global run melos:melos bootstrap - dart pub global run melos:melos cache-source-win + dart pub global run melos:melos cache-source-win --no-select dart pub get --directory=packages/isolate_exec_test_packages/test_package --offline dart pub get --directory=packages/runtime_test_packages/application --offline dart pub get --directory=packages/runtime_test_packages/dependency --offline diff --git a/melos.yaml b/melos.yaml index ba058c7f9..0c08db4a9 100644 --- a/melos.yaml +++ b/melos.yaml @@ -13,7 +13,7 @@ command: linkToCommits: true scripts: test-unit: - run: melos exec -c1 --fail-fast --ignore "*common*" --ignore "*application*" --ignore "*dependency*" -- "dart test" + run: melos exec -c1 --fail-fast --ignore "*common*" --ignore "*application*" --ignore "*dependency*" -- "dart test -r failures-only" packageFilters: noPrivate: true test-with-coverage: diff --git a/packages/cli/example/main.dart b/packages/cli/example/main.dart index fd0d1d412..20358e4ba 100644 --- a/packages/cli/example/main.dart +++ b/packages/cli/example/main.dart @@ -24,8 +24,8 @@ Future main() async { } class App extends ApplicationChannel { - ManagedContext? context; - AuthServer? authServer; + late ManagedContext context; + late final AuthServer authServer; @override Future prepare() async { @@ -61,7 +61,7 @@ class UserController extends ResourceController { UserController(this.context, this.authServer); final ManagedContext? context; - final AuthServer? authServer; + final AuthServer authServer; @Operation.get() Future getUsers() async { @@ -90,7 +90,7 @@ class UserController extends ResourceController { } final salt = generateRandomSalt(); - final hashedPassword = authServer!.hashPassword(user.password!, salt); + final hashedPassword = authServer.hashPassword(user.password!, salt); final query = Query(context!) ..values = user @@ -99,7 +99,7 @@ class UserController extends ResourceController { ..values.email = user.username; final u = await query.insert(); - final token = await authServer!.authenticate( + final token = await authServer.authenticate( u.username, query.values.password, request!.authorization!.credentials!.username, diff --git a/packages/cli/lib/src/command.dart b/packages/cli/lib/src/command.dart index 0fd0ef2b3..d8d5134fb 100644 --- a/packages/cli/lib/src/command.dart +++ b/packages/cli/lib/src/command.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:async'; import 'dart:io'; import 'dart:mirrors'; diff --git a/packages/cli/lib/src/commands/auth_add_client.dart b/packages/cli/lib/src/commands/auth_add_client.dart index 9255912d3..38ed58eda 100644 --- a/packages/cli/lib/src/commands/auth_add_client.dart +++ b/packages/cli/lib/src/commands/auth_add_client.dart @@ -95,7 +95,7 @@ class CLIAuthAddClient extends CLICommand context = ManagedContext(dataModel, persistentStore); final credentials = generateAPICredentialPair( - clientID, + clientID!, secret, redirectURI: redirectUri, hashLength: hashLength, diff --git a/packages/cli/lib/src/commands/auth_scope.dart b/packages/cli/lib/src/commands/auth_scope.dart index 0b272fd16..52aaffd91 100644 --- a/packages/cli/lib/src/commands/auth_scope.dart +++ b/packages/cli/lib/src/commands/auth_scope.dart @@ -49,7 +49,7 @@ class CLIAuthScopeClient extends CLICommand ); final query = Query(context) - ..where((o) => o.id).equalTo(clientID) + ..where((o) => o.id).equalTo(clientID!) ..values.allowedScope = scopingClient.allowedScopes?.map((s) => s.toString()).join(" "); diff --git a/packages/cli/lib/src/commands/db_upgrade.dart b/packages/cli/lib/src/commands/db_upgrade.dart index 825c5a095..979b6fa05 100644 --- a/packages/cli/lib/src/commands/db_upgrade.dart +++ b/packages/cli/lib/src/commands/db_upgrade.dart @@ -117,7 +117,7 @@ class CLIDatabaseUpgrade extends CLICommand s.port, s.databaseName, s.timeZone, - useSSL: s.isSSLConnection, + sslMode: s.sslMode, ); } diff --git a/packages/cli/lib/src/migration_source.dart b/packages/cli/lib/src/migration_source.dart index cbc95fe19..813d5ba32 100644 --- a/packages/cli/lib/src/migration_source.dart +++ b/packages/cli/lib/src/migration_source.dart @@ -7,13 +7,13 @@ class MigrationSource { MigrationSource(this.source, this.uri, int nameStartIndex, int nameEndIndex) { originalName = source!.substring(nameStartIndex, nameEndIndex); name = "M${md5.convert(source!.codeUnits)}"; - source = source!.replaceRange(nameStartIndex, nameEndIndex, name!); + source = source!.replaceRange(nameStartIndex, nameEndIndex, name); } MigrationSource.fromMap(Map map) { - originalName = map["originalName"] as String?; + originalName = map["originalName"] as String; source = map["source"] as String?; - name = map["name"] as String?; + name = map["name"] as String; uri = map["uri"] as String?; } @@ -58,9 +58,9 @@ class MigrationSource { String? source; - String? originalName; + late final String originalName; - String? name; + late final String name; String? uri; diff --git a/packages/cli/lib/src/mixins/database_connecting.dart b/packages/cli/lib/src/mixins/database_connecting.dart index d2c23576d..19237450a 100644 --- a/packages/cli/lib/src/mixins/database_connecting.dart +++ b/packages/cli/lib/src/mixins/database_connecting.dart @@ -14,11 +14,17 @@ mixin CLIDatabaseConnectingCommand implements CLICommand, CLIProject { @Flag( "use-ssl", - help: "Whether or not the database connection should use SSL", + help: "DEPRECATED: Use ssl-mode instead", defaultsTo: false, ) bool get useSSL => decode("use-ssl"); + @Option("ssl-mode", + help: + "Whether or not the database connection should use SSL (disable/require/verifyFull)", + defaultsTo: "disable") + String get sslMode => decode("ssl-mode"); + @Option( "connect", abbr: "c", @@ -102,7 +108,7 @@ mixin CLIDatabaseConnectingCommand implements CLICommand, CLIProject { connectedDatabase.host, connectedDatabase.port, connectedDatabase.databaseName, - useSSL: useSSL, + sslMode: sslMode, ); } diff --git a/packages/cli/lib/src/scripts/run_upgrade.dart b/packages/cli/lib/src/scripts/run_upgrade.dart index 45dbb8112..5543b1290 100644 --- a/packages/cli/lib/src/scripts/run_upgrade.dart +++ b/packages/cli/lib/src/scripts/run_upgrade.dart @@ -49,7 +49,7 @@ class RunUpgradeExecutable extends Executable> { dbInfo.port, dbInfo.databaseName, timeZone: dbInfo.timeZone, - useSSL: dbInfo.useSSL, + sslMode: dbInfo.sslMode, ); } @@ -71,7 +71,7 @@ class RunUpgradeExecutable extends Executable> { }).toList(); try { - final updatedSchema = (await store.upgrade(inputSchema, instances))!; + final updatedSchema = (await store.upgrade(inputSchema, instances)); await store.close(); return updatedSchema.asMap(); @@ -129,7 +129,7 @@ class DBInfo { this.port, this.databaseName, this.timeZone, { - this.useSSL = false, + this.sslMode, }); DBInfo.fromMap(Map map) @@ -140,7 +140,7 @@ class DBInfo { port = map["port"] as int?, databaseName = map["databaseName"] as String?, timeZone = map["timeZone"] as String?, - useSSL = (map["useSSL"] ?? false) as bool; + sslMode = map["sslMode"] as String?; final String? flavor; final String? username; @@ -149,7 +149,7 @@ class DBInfo { final int? port; final String? databaseName; final String? timeZone; - final bool useSSL; + final String? sslMode; Map? asMap() { return { @@ -160,7 +160,7 @@ class DBInfo { "port": port, "databaseName": databaseName, "timeZone": timeZone, - "useSSL": useSSL + "sslMode": sslMode }; } } diff --git a/packages/cli/lib/src/scripts/schema_builder.dart b/packages/cli/lib/src/scripts/schema_builder.dart index bc130b15f..331887d3f 100644 --- a/packages/cli/lib/src/scripts/schema_builder.dart +++ b/packages/cli/lib/src/scripts/schema_builder.dart @@ -27,10 +27,10 @@ class SchemaBuilderExecutable extends Executable> { PostgreSQLPersistentStore.logger.level = Level.ALL; PostgreSQLPersistentStore.logger.onRecord.listen((r) => log(r.message)); try { - Schema? outputSchema = inputSchema; + Schema outputSchema = inputSchema; for (final source in sources) { final Migration instance = instanceOf( - source.name!, + source.name, positionalArguments: const [], namedArguments: const {}, constructorName: Symbol.empty, @@ -39,7 +39,7 @@ class SchemaBuilderExecutable extends Executable> { await instance.upgrade(); outputSchema = instance.currentSchema; } - return outputSchema!.asMap(); + return outputSchema.asMap(); } on SchemaException catch (e) { return { "error": diff --git a/packages/cli/pubspec.yaml b/packages/cli/pubspec.yaml index b4340373e..ceed4e54f 100644 --- a/packages/cli/pubspec.yaml +++ b/packages/cli/pubspec.yaml @@ -6,10 +6,10 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: - analyzer: ^6.4.1 + analyzer: ^6.5.0 args: ^2.4.2 collection: ^1.18.0 conduit_common: ^5.0.3 diff --git a/packages/cli/templates/db/pubspec.yaml b/packages/cli/templates/db/pubspec.yaml index c39e00faa..deef6ab03 100644 --- a/packages/cli/templates/db/pubspec.yaml +++ b/packages/cli/templates/db/pubspec.yaml @@ -5,7 +5,7 @@ homepage: https://github.com/conduit-dart/conduit-codable publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit: ^5.0.1 diff --git a/packages/cli/templates/db_and_auth/lib/channel.dart b/packages/cli/templates/db_and_auth/lib/channel.dart index 656ecadf2..67962046a 100644 --- a/packages/cli/templates/db_and_auth/lib/channel.dart +++ b/packages/cli/templates/db_and_auth/lib/channel.dart @@ -12,8 +12,8 @@ import 'package:wildfire/wildfire.dart'; class WildfireChannel extends ApplicationChannel implements AuthRedirectControllerDelegate { final HTMLRenderer htmlRenderer = HTMLRenderer(); - AuthServer? authServer; - ManagedContext? context; + late final authServer; + late ManagedContext context; /// Initialize services in this method. /// @@ -49,25 +49,25 @@ class WildfireChannel extends ApplicationChannel router .route("/auth/form") - .link(() => AuthRedirectController(authServer!, delegate: this)); + .link(() => AuthRedirectController(authServer, delegate: this)); /* Create an account */ router .route("/register") - .link(() => Authorizer.basic(authServer!))! - .link(() => RegisterController(context!, authServer!)); + .link(() => Authorizer.basic(authServer))! + .link(() => RegisterController(context!, authServer)); /* Gets profile for user with bearer token */ router .route("/me") - .link(() => Authorizer.bearer(authServer!))! + .link(() => Authorizer.bearer(authServer))! .link(() => IdentityController(context!)); /* Gets all users or one specific user by id */ router .route("/users/[:id]") - .link(() => Authorizer.bearer(authServer!))! - .link(() => UserController(context!, authServer!)); + .link(() => Authorizer.bearer(authServer))! + .link(() => UserController(context!, authServer)); return router; } @@ -94,7 +94,7 @@ class WildfireChannel extends ApplicationChannel AuthRedirectController forController, Uri requestUri, String? responseType, - String? clientID, + String clientID, String? state, String? scope) async { final map = { diff --git a/packages/cli/templates/db_and_auth/lib/controller/register_controller.dart b/packages/cli/templates/db_and_auth/lib/controller/register_controller.dart index b04a2cc89..44df16033 100644 --- a/packages/cli/templates/db_and_auth/lib/controller/register_controller.dart +++ b/packages/cli/templates/db_and_auth/lib/controller/register_controller.dart @@ -25,7 +25,7 @@ class RegisterController extends ResourceController { final token = await authServer.authenticate( user.username, user.password, - request?.authorization?.credentials?.username, + request!.authorization!.credentials!.username, request?.authorization?.credentials?.password); final response = AuthController.tokenResponse(token); diff --git a/packages/cli/templates/db_and_auth/pubspec.yaml b/packages/cli/templates/db_and_auth/pubspec.yaml index 2911dbd24..d1c031f1d 100644 --- a/packages/cli/templates/db_and_auth/pubspec.yaml +++ b/packages/cli/templates/db_and_auth/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit: ^5.0.1 diff --git a/packages/cli/templates/db_and_auth/test/harness/app.dart b/packages/cli/templates/db_and_auth/test/harness/app.dart index 0b724a747..fbc57935e 100644 --- a/packages/cli/templates/db_and_auth/test/harness/app.dart +++ b/packages/cli/templates/db_and_auth/test/harness/app.dart @@ -26,7 +26,7 @@ class Harness extends TestHarness ManagedContext? get context => channel?.context; @override - AuthServer? get authServer => channel?.authServer; + AuthServer get authServer => channel!.authServer; Agent? publicAgent; diff --git a/packages/cli/templates/default/pubspec.yaml b/packages/cli/templates/default/pubspec.yaml index ba5d65cf5..e9c880a2b 100644 --- a/packages/cli/templates/default/pubspec.yaml +++ b/packages/cli/templates/default/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.0.1 publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit: ^5.0.1 diff --git a/packages/cli/test/command_test.dart b/packages/cli/test/command_test.dart index 7837cfc86..6e718eadd 100644 --- a/packages/cli/test/command_test.dart +++ b/packages/cli/test/command_test.dart @@ -1,5 +1,7 @@ import 'package:conduit/src/command.dart'; import 'package:conduit/src/metadata.dart'; +import 'package:conduit_postgresql/conduit_postgresql.dart'; +import 'package:postgres/postgres.dart'; import 'package:test/test.dart'; void main() { @@ -153,7 +155,7 @@ void main() { final results = cmd.options.parse(args); cmd.process(results); - expect(cmd.useSSl, equals(true)); + expect(cmd.useSSL, equals(true)); }); test('Command bool conversion - negated ', () { @@ -164,7 +166,18 @@ void main() { final results = cmd.options.parse(args); cmd.process(results); - expect(cmd.useSSl, equals(false)); + expect(cmd.useSSL, equals(false)); + }); + + test('Enum checks on sslMode, correct value', () { + final cmd = TestCLICommand(); + + final args = ['--sslMode=require']; + + final results = cmd.options.parse(args); + cmd.process(results); + + expect(cmd.sslMode.toSslMode(), equals(SslMode.require)); }); } @@ -208,10 +221,13 @@ class TestCLICommand extends CLICommand { int get guaranteed => decodeOptional("guaranteed", orElse: () => 1)!; @Flag("useSSL", abbr: "u", help: "UseSSL.", negatable: true) - bool get useSSl => decode("useSSL"); + bool get useSSL => decode("useSSL"); + + @Flag("useSSLWithDefault", abbr: "d", help: "useSSLWithDefault.") + bool get useSSLWithDefault => decode("useSSLWithDefault"); - @Flag("useSSLWithDefault", abbr: "d", help: "useSSlWithDefault.") - bool get useSSlWithDefault => decode("useSSlWithDefault"); + @Option("sslMode") + String get sslMode => decode("sslMode"); @Option( "scopes", diff --git a/packages/cli/test/migration_execution_test.dart b/packages/cli/test/migration_execution_test.dart index 69bbaad02..a5099f4e3 100644 --- a/packages/cli/test/migration_execution_test.dart +++ b/packages/cli/test/migration_execution_test.dart @@ -20,7 +20,7 @@ String connectString = "postgres://${connectInfo.username}:${connectInfo.password}@${connectInfo.host}:${connectInfo.port}/${connectInfo.databaseName}"; void main() { - late PostgreSQLPersistentStore store; + PostgreSQLPersistentStore? store; setUpAll(() async { final t = @@ -54,10 +54,10 @@ void main() { await Future.wait( tables.map((t) { - return store.execute("DROP TABLE IF EXISTS $t"); - }), + return store?.execute("DROP TABLE IF EXISTS $t"); + }).nonNulls, ); - await store.close(); + await store?.close(); }); tearDownAll(DartProjectAgent.tearDownAll); @@ -69,12 +69,12 @@ void main() { test("Generate and execute initial schema makes workable DB", () async { expect(await runMigrationCases(["Case1"]), isZero); - final version = - await store.execute("SELECT versionNumber FROM _conduit_version_pgsql"); + final version = await store! + .execute("SELECT versionNumber FROM _conduit_version_pgsql"); expect(version, [ [1] ]); - expect(await columnsOfTable(store, "_testobject"), ["id", "foo"]); + expect(await columnsOfTable(store!, "_testobject"), ["id", "foo"]); }); test( @@ -82,7 +82,7 @@ void main() { () async { expect(await runMigrationCases(["Case2"]), isZero); - var versionRow = await store.execute( + var versionRow = await store!.execute( "SELECT versionNumber, dateOfUpgrade FROM _conduit_version_pgsql", ) as List>; expect(versionRow.first.first, 1); @@ -90,7 +90,7 @@ void main() { cli.clearOutput(); expect(await runMigrationCases(["Case2"]), isZero); - versionRow = await store.execute( + versionRow = await store!.execute( "SELECT versionNumber, dateOfUpgrade FROM _conduit_version_pgsql", ) as List; expect(versionRow.length, 1); @@ -102,45 +102,45 @@ void main() { test("Multiple migration files are ran", () async { expect(await runMigrationCases(["Case31", "Case32"]), isZero); - final version = - await store.execute("SELECT versionNumber FROM _conduit_version_pgsql"); + final version = await store! + .execute("SELECT versionNumber FROM _conduit_version_pgsql"); expect(version, [ [1], [2] ]); - expect(await columnsOfTable(store, "_testobject"), ["id", "foo"]); - expect(await columnsOfTable(store, "_foo"), ["id", "testobject_id"]); + expect(await columnsOfTable(store!, "_testobject"), ["id", "foo"]); + expect(await columnsOfTable(store!, "_foo"), ["id", "testobject_id"]); }); test("Only later migration files are ran if already at a version", () async { expect(await runMigrationCases(["Case41"]), isZero); - var version = - await store.execute("SELECT versionNumber FROM _conduit_version_pgsql"); + var version = await store! + .execute("SELECT versionNumber FROM _conduit_version_pgsql"); expect(version, [ [1] ]); cli.clearOutput(); - expect(await columnsOfTable(store, "_testobject"), ["id", "foo"]); - expect(await tableExists(store, "_foo"), isFalse); + expect(await columnsOfTable(store!, "_testobject"), ["id", "foo"]); + expect(await tableExists(store!, "_foo"), isFalse); expect(await runMigrationCases(["Case42"], fromVersion: 1), isZero); - version = - await store.execute("SELECT versionNumber FROM _conduit_version_pgsql"); + version = await store! + .execute("SELECT versionNumber FROM _conduit_version_pgsql"); expect(version, [ [1], [2] ]); - expect(await columnsOfTable(store, "_testobject"), ["id", "foo"]); - expect(await columnsOfTable(store, "_foo"), ["id", "testobject_id"]); + expect(await columnsOfTable(store!, "_testobject"), ["id", "foo"]); + expect(await columnsOfTable(store!, "_foo"), ["id", "testobject_id"]); }); test("If migration throws exception, rollback any changes", () async { expect(await runMigrationCases(["Case5"]), isNonZero); - expect(await tableExists(store, store.versionTable.name), isFalse); - expect(await tableExists(store, "_testobject"), isFalse); + expect(await tableExists(store!, store!.versionTable.name), isFalse); + expect(await tableExists(store!, "_testobject"), isFalse); }); test( @@ -164,9 +164,9 @@ void main() { ); expect(cli.output, contains('relation "_unknowntable" does not exist')); - expect(await tableExists(store, store.versionTable.name), isFalse); - expect(await tableExists(store, "_testobject"), isFalse); - expect(await tableExists(store, "_foo"), isFalse); + expect(await tableExists(store!, store!.versionTable.name), isFalse); + expect(await tableExists(store!, "_testobject"), isFalse); + expect(await tableExists(store!, "_foo"), isFalse); }, ); @@ -187,23 +187,23 @@ void main() { expect(cli.output, contains('relation "_unknowntable" does not exist')); - final version = await store + final version = await store! .execute("SELECT versionNumber FROM _conduit_version_pgsql"); expect(version, [ [1], ]); - expect(await tableExists(store, store.versionTable.name), isTrue); - expect(await tableExists(store, "_testobject"), isTrue); - expect(await tableExists(store, "_foo"), isFalse); + expect(await tableExists(store!, store!.versionTable.name), isTrue); + expect(await tableExists(store!, "_testobject"), isTrue); + expect(await tableExists(store!, "_foo"), isFalse); }, ); test("If seed fails, all schema changes are rolled back", () async { expect(await runMigrationCases(["Case7"]), isNonZero); - expect(await tableExists(store, store.versionTable.name), isFalse); - expect(await tableExists(store, "_testobject"), isFalse); + expect(await tableExists(store!, store!.versionTable.name), isFalse); + expect(await tableExists(store!, "_testobject"), isFalse); }); test( @@ -256,7 +256,7 @@ MigrationSource migrationSourceFromClassDeclaration(ClassDeclaration cu) { } List getOrderedTestMigrations( - List names, { + List names, { int fromVersion = 0, }) { final uri = Directory.current.uri @@ -279,7 +279,7 @@ List getOrderedTestMigrations( } Future runMigrationCases( - List migrationNames, { + List migrationNames, { int fromVersion = 0, StringSink? log, }) async { @@ -298,6 +298,8 @@ Future runMigrationCases( final String useSsl = Platform.environment["USE_SSL"] ?? ""; + print(useSsl); + final res = await cli.run("db", ["upgrade", useSsl, "--connect", connectString]); diff --git a/packages/cli/test/migration_test.dart b/packages/cli/test/migration_test.dart index 12faf60f5..3fb2c5682 100644 --- a/packages/cli/test/migration_test.dart +++ b/packages/cli/test/migration_test.dart @@ -73,7 +73,7 @@ void main() { ]), ); - expect(outSchema!.differenceFrom(schema).hasDifferences, false); + expect(outSchema.differenceFrom(schema).hasDifferences, false); final insertResults = await store.execute( "INSERT INTO tableToKeep (columnToEdit) VALUES ('1') RETURNING columnToEdit, addedColumn", diff --git a/packages/codable/lib/src/keyed_archive.dart b/packages/codable/lib/src/keyed_archive.dart index fd1109bd1..516747ccb 100644 --- a/packages/codable/lib/src/keyed_archive.dart +++ b/packages/codable/lib/src/keyed_archive.dart @@ -118,16 +118,18 @@ class KeyedArchive extends Object if (schema == null) { return; } - + if (_casted) return; + _casted = true; final caster = cast.Keyed(schema); _map = caster.cast(_map); if (_objectReference != null) { - // todo: can optimize this by only running it once _objectReference!._map = caster.cast(_objectReference!._map); } } + bool _casted = false; + /// store the [key]/[value] pair into the map @override void operator []=(covariant String key, dynamic value) { @@ -160,7 +162,7 @@ class KeyedArchive extends Object return out; } - dynamic _getValue(String? key) { + dynamic _getValue(String key) { if (_map.containsKey(key)) { return _map[key]; } @@ -319,7 +321,7 @@ class KeyedArchive extends Object /* encode */ - Map? _encodedObject(Coding? object) { + Map? _encodedObject(Coding? object) { if (object == null) { return null; } diff --git a/packages/codable/pubspec.yaml b/packages/codable/pubspec.yaml index 10508de43..d873ae12e 100644 --- a/packages/codable/pubspec.yaml +++ b/packages/codable/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: meta: ^1.3.0 diff --git a/packages/codable/test/decode_test.dart b/packages/codable/test/decode_test.dart index 0d5bb0897..58ec1a992 100644 --- a/packages/codable/test/decode_test.dart +++ b/packages/codable/test/decode_test.dart @@ -424,7 +424,7 @@ class Parent extends Coding { String? name; Child? child; List? children; - Map? childMap; + Map? childMap; List? things; @override diff --git a/packages/common/lib/src/openapi/documentable.dart b/packages/common/lib/src/openapi/documentable.dart index 2b634da8a..1246adcb3 100644 --- a/packages/common/lib/src/openapi/documentable.dart +++ b/packages/common/lib/src/openapi/documentable.dart @@ -184,7 +184,7 @@ class APIDocumentContext { .where((op) => op!.security != null) .expand((op) => op!.security!) .forEach((req) { - req!.requirements!.forEach((schemeName, scopes) { + req.requirements!.forEach((schemeName, scopes) { final scheme = document.components!.securitySchemes[schemeName]; if (scheme!.type == APISecuritySchemeType.oauth2) { for (final flow in scheme.flows!.values) { @@ -205,7 +205,7 @@ class APIDocumentContext { /// A collection of reusable OpenAPI objects. /// /// Components of type [T] may be registered and referenced through this object. -class APIComponentCollection { +class APIComponentCollection { APIComponentCollection._(this._typeName, this._componentMap); final String _typeName; @@ -257,7 +257,7 @@ class APIComponentCollection { /// If after [APIDocumentContext.finalize] is called and no object /// has been registered for [name], an error is thrown. T getObject(String name) { - final obj = _getInstanceOf()!; + final obj = _getInstanceOf(); obj.referenceURI = Uri(path: "/components/$_typeName/$name"); return obj; } @@ -271,7 +271,7 @@ class APIComponentCollection { /// for [type]. If after [APIDocumentContext.finalize] is called and no object /// has been registered for [type], an error is thrown. T getObjectWithType(Type type) { - final obj = _getInstanceOf()!; + final obj = _getInstanceOf(); obj.referenceURI = Uri(path: "/components/$_typeName/conduit-typeref:$type"); @@ -282,7 +282,7 @@ class APIComponentCollection { _resolutionMap.putIfAbsent(type, () => Completer.sync()); completer.future.then((refObject) { - obj.referenceURI = refObject!.referenceURI; + obj.referenceURI = refObject.referenceURI; }); } diff --git a/packages/common/pubspec.yaml b/packages/common/pubspec.yaml index fa1d874dd..7ef20e45e 100644 --- a/packages/common/pubspec.yaml +++ b/packages/common/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit_open_api: ^5.0.3 diff --git a/packages/config/pubspec.yaml b/packages/config/pubspec.yaml index 53e48a47f..037aa4e8a 100644 --- a/packages/config/pubspec.yaml +++ b/packages/config/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit_runtime: ^5.0.3 diff --git a/packages/core/lib/managed_auth.dart b/packages/core/lib/managed_auth.dart index 6ca9a647e..49b815b38 100644 --- a/packages/core/lib/managed_auth.dart +++ b/packages/core/lib/managed_auth.dart @@ -48,7 +48,7 @@ class ManagedAuthToken extends ManagedObject<_ManagedAuthToken> /// Instance from an [AuthToken]. ManagedAuthToken.fromToken(AuthToken t) : super() { final tokenResourceOwner = - entity.relationships!["resourceOwner"]!.destinationEntity.instanceOf(); + entity.relationships["resourceOwner"]!.destinationEntity.instanceOf(); tokenResourceOwner["id"] = t.resourceOwnerIdentifier; this ..accessToken = t.accessToken @@ -64,7 +64,7 @@ class ManagedAuthToken extends ManagedObject<_ManagedAuthToken> /// Instance from an [AuthCode]. ManagedAuthToken.fromCode(AuthCode code) : super() { final tokenResourceOwner = - entity.relationships!["resourceOwner"]!.destinationEntity.instanceOf(); + entity.relationships["resourceOwner"]!.destinationEntity.instanceOf(); tokenResourceOwner["id"] = code.resourceOwnerIdentifier; this @@ -86,7 +86,7 @@ class ManagedAuthToken extends ManagedObject<_ManagedAuthToken> ..type = type ..resourceOwnerIdentifier = resourceOwner.id ..scopes = scope?.split(" ").map((s) => AuthScope(s)).toList() - ..clientID = client.id; + ..clientID = client.id!; } /// As an [AuthCode]. @@ -98,7 +98,7 @@ class ManagedAuthToken extends ManagedObject<_ManagedAuthToken> ..issueDate = issueDate ..requestedScopes = scope?.split(" ").map((s) => AuthScope(s)).toList() ..expirationDate = expirationDate - ..clientID = client.id; + ..clientID = client.id!; } } @@ -186,7 +186,7 @@ class ManagedAuthClient extends ManagedObject<_ManagedAuthClient> final scopes = allowedScope?.split(" ").map((s) => AuthScope(s)).toList(); return AuthClient.withRedirectURI( - id, + id!, hashedSecret, salt, redirectURI, @@ -306,7 +306,7 @@ class ManagedAuthDelegate ManagedAuthDelegate(this.context, {this.tokenLimit = 40}); /// The [ManagedContext] this instance uses to store and retrieve values. - final ManagedContext? context; + final ManagedContext context; /// The number of tokens and authorization codes a user can have at a time. /// @@ -315,7 +315,7 @@ class ManagedAuthDelegate @override Future removeTokens(AuthServer server, int resourceOwnerID) { - final tokenQuery = Query(context!) + final tokenQuery = Query(context) ..where((o) => o.resourceOwner).identifiedBy(resourceOwnerID); return tokenQuery.delete(); @@ -333,7 +333,7 @@ class ManagedAuthDelegate ); } - final query = Query(context!); + final query = Query(context); if (byAccessToken != null) { query.where((o) => o.accessToken).equalTo(byAccessToken); } else if (byRefreshToken != null) { @@ -351,7 +351,7 @@ class ManagedAuthDelegate @override Future getResourceOwner(AuthServer server, String username) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.username).equalTo(username) ..returningProperties( (t) => [t.id, t.hashedPassword, t.salt, t.username], @@ -362,7 +362,7 @@ class ManagedAuthDelegate @override Future removeToken(AuthServer server, AuthCode grantedByCode) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.code).equalTo(grantedByCode.code); return query.delete(); @@ -375,7 +375,7 @@ class ManagedAuthDelegate AuthCode? issuedFrom, }) async { final storage = ManagedAuthToken.fromToken(token); - final query = Query(context!)..values = storage; + final query = Query(context)..values = storage; if (issuedFrom != null) { query.where((o) => o.code).equalTo(issuedFrom.code); @@ -403,7 +403,7 @@ class ManagedAuthDelegate DateTime? newIssueDate, DateTime? newExpirationDate, ) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.accessToken).equalTo(oldAccessToken) ..values.accessToken = newAccessToken ..values.issueDate = newIssueDate @@ -415,7 +415,7 @@ class ManagedAuthDelegate @override Future addCode(AuthServer server, AuthCode code) async { final storage = ManagedAuthToken.fromCode(code); - final query = Query(context!)..values = storage; + final query = Query(context)..values = storage; await query.insert(); @@ -424,7 +424,7 @@ class ManagedAuthDelegate @override Future getCode(AuthServer server, String code) async { - final query = Query(context!) + final query = Query(context) ..where((o) => o.code).equalTo(code); final storage = await query.fetchOne(); @@ -433,7 +433,7 @@ class ManagedAuthDelegate @override Future removeCode(AuthServer server, String? code) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.code).equalTo(code); return query.delete(); @@ -442,13 +442,13 @@ class ManagedAuthDelegate @override Future addClient(AuthServer server, AuthClient client) async { final storage = ManagedAuthClient.fromClient(client); - final query = Query(context!)..values = storage; + final query = Query(context)..values = storage; return query.insert(); } @override - Future getClient(AuthServer server, String? clientID) async { - final query = Query(context!) + Future getClient(AuthServer server, String clientID) async { + final query = Query(context) ..where((o) => o.id).equalTo(clientID); final storage = await query.fetchOne(); @@ -458,7 +458,7 @@ class ManagedAuthDelegate @override Future removeClient(AuthServer server, String clientID) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.id).equalTo(clientID); return query.delete(); @@ -473,7 +473,7 @@ class ManagedAuthDelegate /// There is rarely a need to invoke this method directly, as it is invoked each /// time a new token is issued. Future pruneTokens(dynamic resourceOwnerIdentifier) async { - final oldTokenQuery = Query(context!) + final oldTokenQuery = Query(context) ..where((o) => o.resourceOwner).identifiedBy(resourceOwnerIdentifier) ..sortBy((t) => t.expirationDate, QuerySortOrder.descending) ..offset = tokenLimit @@ -482,7 +482,7 @@ class ManagedAuthDelegate final results = await oldTokenQuery.fetch(); if (results.length == 1) { - final deleteQ = Query(context!) + final deleteQ = Query(context) ..where((o) => o.resourceOwner).identifiedBy(resourceOwnerIdentifier) ..where((o) => o.expirationDate) .lessThanEqualTo(results.first.expirationDate); diff --git a/packages/core/lib/src/application/application.dart b/packages/core/lib/src/application/application.dart index 13223cc1d..a430a80af 100644 --- a/packages/core/lib/src/application/application.dart +++ b/packages/core/lib/src/application/application.dart @@ -158,7 +158,7 @@ class Application { }); try { - await server.server!.close(force: true); + await server.server.close(force: true); } catch (e) { logger.severe(e); } diff --git a/packages/core/lib/src/application/application_server.dart b/packages/core/lib/src/application/application_server.dart index f3785de1b..0ef5c97f3 100644 --- a/packages/core/lib/src/application/application_server.dart +++ b/packages/core/lib/src/application/application_server.dart @@ -28,7 +28,7 @@ class ApplicationServer { ApplicationOptions options; /// The underlying [HttpServer]. - HttpServer? server; + late final HttpServer server; /// The instance of [ApplicationChannel] serving requests. late ApplicationChannel channel; @@ -98,9 +98,7 @@ class ApplicationServer { /// Closes this HTTP server and channel. Future close() async { logger.fine("ApplicationServer($identifier).close Closing HTTP listener"); - if (server != null) { - await server!.close(force: true); - } + await server.close(force: true); logger.fine("ApplicationServer($identifier).close Closing channel"); await channel.close(); @@ -113,10 +111,10 @@ class ApplicationServer { /// /// [ApplicationChannel.willStartReceivingRequests] is invoked after this opening has completed. Future didOpen() async { - server!.serverHeader = "conduit/$identifier"; + server.serverHeader = "conduit/$identifier"; logger.fine("ApplicationServer($identifier).didOpen start listening"); - server!.map((baseReq) => Request(baseReq)).listen(entryPoint.receive); + server.map((baseReq) => Request(baseReq)).listen(entryPoint.receive); channel.willStartReceivingRequests(); logger.info("Server conduit/$identifier started."); diff --git a/packages/core/lib/src/application/channel.dart b/packages/core/lib/src/application/channel.dart index d54a7d359..57c55ac21 100644 --- a/packages/core/lib/src/application/channel.dart +++ b/packages/core/lib/src/application/channel.dart @@ -190,7 +190,7 @@ abstract class ApplicationChannel implements APIComponentDocumenter { (RuntimeContext.current[runtimeType] as ChannelRuntime) .getDocumentableChannelComponents(this) .forEach((component) { - component!.documentComponents(registry); + component.documentComponents(registry); }); } } @@ -275,7 +275,7 @@ class ApplicationMessageHub extends Stream implements Sink { } abstract class ChannelRuntime { - Iterable getDocumentableChannelComponents( + Iterable getDocumentableChannelComponents( ApplicationChannel channel, ); diff --git a/packages/core/lib/src/application/isolate_supervisor.dart b/packages/core/lib/src/application/isolate_supervisor.dart index 34265155e..b37d93571 100644 --- a/packages/core/lib/src/application/isolate_supervisor.dart +++ b/packages/core/lib/src/application/isolate_supervisor.dart @@ -38,9 +38,9 @@ class ApplicationIsolateSupervisor { final List _pendingMessageQueue = []; - bool get _isLaunching => _launchCompleter != null; + bool get _isLaunching => !_launchCompleter.isCompleted; late SendPort _serverSendPort; - Completer? _launchCompleter; + late Completer _launchCompleter; Completer? _stopCompleter; static const String messageKeyStop = "_MessageStop"; @@ -58,7 +58,7 @@ class ApplicationIsolateSupervisor { ); isolate.resume(isolate.pauseCapability!); - return _launchCompleter!.future.timeout( + return _launchCompleter.future.timeout( startupTimeout, onTimeout: () { logger.fine( @@ -96,8 +96,7 @@ class ApplicationIsolateSupervisor { if (message is SendPort) { _serverSendPort = message; } else if (message == messageKeyListening) { - _launchCompleter!.complete(); - _launchCompleter = null; + _launchCompleter.complete(); logger.fine( "ApplicationIsolateSupervisor($identifier) isolate listening acknowledged", ); @@ -107,7 +106,7 @@ class ApplicationIsolateSupervisor { ); receivePort.close(); - _stopCompleter?.complete(); + _stopCompleter!.complete(); _stopCompleter = null; } else if (message is List) { logger.fine( @@ -141,7 +140,7 @@ class ApplicationIsolateSupervisor { void _handleIsolateException(dynamic error, StackTrace stacktrace) { if (_isLaunching) { final appException = ApplicationStartupException(error); - _launchCompleter!.completeError(appException, stacktrace); + _launchCompleter.completeError(appException, stacktrace); } else { logger.severe("Uncaught exception in isolate.", error, stacktrace); } diff --git a/packages/core/lib/src/auth/auth.dart b/packages/core/lib/src/auth/auth.dart index e6ad99cfb..6c4a745a4 100644 --- a/packages/core/lib/src/auth/auth.dart +++ b/packages/core/lib/src/auth/auth.dart @@ -46,7 +46,7 @@ String generateRandomSalt({int hashLength = 32}) { /// Note that [secret] is hashed with a randomly generated salt, and therefore cannot be retrieved /// later. The plain-text secret must be stored securely elsewhere. AuthClient generateAPICredentialPair( - String? clientID, + String clientID, String? secret, { String? redirectURI, int hashLength = 32, @@ -54,7 +54,7 @@ AuthClient generateAPICredentialPair( Hash? hashFunction, }) { if (secret == null) { - return AuthClient.withRedirectURI(clientID, null, null, redirectURI); + return AuthClient.public(clientID, redirectURI: redirectURI); } final salt = generateRandomSalt(hashLength: hashLength); diff --git a/packages/core/lib/src/auth/auth_code_controller.dart b/packages/core/lib/src/auth/auth_code_controller.dart index 1ad6fd8db..f6b2c3eec 100644 --- a/packages/core/lib/src/auth/auth_code_controller.dart +++ b/packages/core/lib/src/auth/auth_code_controller.dart @@ -27,11 +27,11 @@ abstract class AuthCodeControllerDelegate { /// /// /// If not null, [scope] should also be included as an additional form parameter. - Future render( + Future render( AuthCodeController forController, Uri requestUri, String? responseType, - String? clientID, + String clientID, String? state, String? scope, ); @@ -101,12 +101,16 @@ class AuthCodeController extends ResourceController { /// A space-delimited list of access scopes to be requested by the form submission on the returned page. @Bind.query("scope") String? scope, }) async { + if (clientID == null) { + return Response.badRequest(); + } + if (delegate == null) { return Response(405, {}, null); } final renderedPage = await delegate! - .render(this, request!.raw.uri, responseType, clientID, state, scope); + .render(this, request!.raw.uri, responseType, clientID!, state, scope); return Response.ok(renderedPage)..contentType = ContentType.html; } @@ -129,7 +133,7 @@ class AuthCodeController extends ResourceController { /// A space-delimited list of access scopes being requested. @Bind.query("scope") String? scope, }) async { - final client = await authServer.getClient(clientID); + final client = await authServer.getClient(clientID!); if (state == null) { return _redirectResponse( @@ -157,7 +161,7 @@ class AuthCodeController extends ResourceController { final authCode = await authServer.authenticateForCode( username, password, - clientID, + clientID!, requestedScopes: scopes, ); return _redirectResponse(client!.redirectURI, state, code: authCode.code); @@ -193,13 +197,13 @@ class AuthCodeController extends ResourceController { } @override - List documentOperationParameters( + List documentOperationParameters( APIDocumentContext context, Operation? operation, ) { final params = super.documentOperationParameters(context, operation)!; - params.where((p) => p!.name != "scope").forEach((p) { - p!.isRequired = true; + params.where((p) => p.name != "scope").forEach((p) { + p.isRequired = true; }); return params; } diff --git a/packages/core/lib/src/auth/auth_controller.dart b/packages/core/lib/src/auth/auth_controller.dart index 531a65c46..e42146aad 100644 --- a/packages/core/lib/src/auth/auth_controller.dart +++ b/packages/core/lib/src/auth/auth_controller.dart @@ -32,7 +32,7 @@ class AuthController extends ResourceController { } /// A reference to the [AuthServer] this controller uses to grant tokens. - final AuthServer? authServer; + final AuthServer authServer; /// Required basic authentication Authorization header containing client ID and secret for the authenticating client. /// @@ -79,7 +79,7 @@ class AuthController extends ResourceController { final scopes = scope?.split(" ").map((s) => AuthScope(s)).toList(); if (grantType == "password") { - final token = await authServer!.authenticate( + final token = await authServer.authenticate( username, password, basicRecord.username, @@ -89,7 +89,7 @@ class AuthController extends ResourceController { return AuthController.tokenResponse(token); } else if (grantType == "refresh_token") { - final token = await authServer!.refresh( + final token = await authServer.refresh( refreshToken, basicRecord.username, basicRecord.password, @@ -102,8 +102,8 @@ class AuthController extends ResourceController { return _responseForError(AuthRequestError.invalidRequest); } - final token = await authServer! - .exchange(authCode, basicRecord.username, basicRecord.password); + final token = await authServer.exchange( + authCode, basicRecord.username, basicRecord.password); return AuthController.tokenResponse(token); } else if (grantType == null) { @@ -148,12 +148,12 @@ class AuthController extends ResourceController { } @override - List documentOperationParameters( + List documentOperationParameters( APIDocumentContext context, Operation? operation, ) { final parameters = super.documentOperationParameters(context, operation)!; - parameters.removeWhere((p) => p!.name == HttpHeaders.authorizationHeader); + parameters.removeWhere((p) => p.name == HttpHeaders.authorizationHeader); return parameters; } @@ -186,11 +186,11 @@ class AuthController extends ResourceController { }); final relativeUri = Uri(path: route.substring(1)); - authServer!.documentedAuthorizationCodeFlow.tokenURL = relativeUri; - authServer!.documentedAuthorizationCodeFlow.refreshURL = relativeUri; + authServer.documentedAuthorizationCodeFlow.tokenURL = relativeUri; + authServer.documentedAuthorizationCodeFlow.refreshURL = relativeUri; - authServer!.documentedPasswordFlow.tokenURL = relativeUri; - authServer!.documentedPasswordFlow.refreshURL = relativeUri; + authServer.documentedPasswordFlow.tokenURL = relativeUri; + authServer.documentedPasswordFlow.refreshURL = relativeUri; return operations; } diff --git a/packages/core/lib/src/auth/auth_redirect_controller.dart b/packages/core/lib/src/auth/auth_redirect_controller.dart index 045a5f6c9..2d05d7a10 100644 --- a/packages/core/lib/src/auth/auth_redirect_controller.dart +++ b/packages/core/lib/src/auth/auth_redirect_controller.dart @@ -30,7 +30,7 @@ abstract class AuthRedirectControllerDelegate { AuthRedirectController forController, Uri requestUri, String? responseType, - String? clientID, + String clientID, String? state, String? scope, ); @@ -69,7 +69,7 @@ class AuthRedirectController extends ResourceController { )..contentType = ContentType.html; /// A reference to the [AuthServer] used to grant authorization codes and access tokens. - final AuthServer? authServer; + late final AuthServer authServer; /// When true, the controller allows for the Implicit Grant Flow final bool allowsImplicit; @@ -121,7 +121,7 @@ class AuthRedirectController extends ResourceController { } final renderedPage = await delegate! - .render(this, request!.raw.uri, responseType, clientID, state, scope); + .render(this, request!.raw.uri, responseType, clientID!, state, scope); if (renderedPage == null) { return Response.notFound(); } @@ -147,7 +147,11 @@ class AuthRedirectController extends ResourceController { /// A space-delimited list of access scopes being requested. @Bind.query("scope") String? scope, }) async { - final client = await authServer!.getClient(clientID); + if (clientID == null) { + return Response.badRequest(); + } + + final client = await authServer.getClient(clientID!); if (client?.redirectURI == null) { return Response.badRequest(); @@ -180,10 +184,10 @@ class AuthRedirectController extends ResourceController { ); } - final authCode = await authServer!.authenticateForCode( + final authCode = await authServer.authenticateForCode( username, password, - clientID, + clientID!, requestedScopes: scopes, ); return _redirectResponse( @@ -192,10 +196,10 @@ class AuthRedirectController extends ResourceController { code: authCode.code, ); } else if (responseType == "token") { - final token = await authServer!.authenticate( + final token = await authServer.authenticate( username, password, - clientID, + clientID!, null, requestedScopes: scopes, ); @@ -248,13 +252,13 @@ class AuthRedirectController extends ResourceController { } @override - List documentOperationParameters( + List documentOperationParameters( APIDocumentContext context, Operation? operation, ) { final params = super.documentOperationParameters(context, operation)!; - params.where((p) => p!.name != "scope").forEach((p) { - p!.isRequired = true; + params.where((p) => p.name != "scope").forEach((p) { + p.isRequired = true; }); return params; } @@ -304,8 +308,8 @@ class AuthRedirectController extends ResourceController { ) { final ops = super.documentOperations(context, route, path); final uri = Uri(path: route.substring(1)); - authServer!.documentedAuthorizationCodeFlow.authorizationURL = uri; - authServer!.documentedImplicitFlow.authorizationURL = uri; + authServer.documentedAuthorizationCodeFlow.authorizationURL = uri; + authServer.documentedImplicitFlow.authorizationURL = uri; return ops; } @@ -330,7 +334,7 @@ class AuthRedirectController extends ResourceController { } final queryParameters = - Map.from(redirectURI.queryParameters); + Map.from(redirectURI.queryParameters); String? fragment; if (responseType == "code") { diff --git a/packages/core/lib/src/auth/authorization_parser.dart b/packages/core/lib/src/auth/authorization_parser.dart index 031bad225..06e318a28 100644 --- a/packages/core/lib/src/auth/authorization_parser.dart +++ b/packages/core/lib/src/auth/authorization_parser.dart @@ -17,8 +17,8 @@ class AuthorizationBearerParser extends AuthorizationParser { /// /// If [authorizationHeader] is malformed or null, throws an [AuthorizationParserException]. @override - String? parse(String? authorizationHeader) { - if (authorizationHeader == null) { + String? parse(String authorizationHeader) { + if (authorizationHeader.isEmpty) { throw AuthorizationParserException( AuthorizationParserExceptionReason.missing, ); @@ -40,10 +40,10 @@ class AuthorizationBearerParser extends AuthorizationParser { /// See [AuthorizationBasicParser] for getting instances of this type. class AuthBasicCredentials { /// The username of a Basic Authorization header. - String? username; + late final String username; /// The password of a Basic Authorization header. - String? password; + late final String password; @override String toString() => "$username:$password"; diff --git a/packages/core/lib/src/auth/authorization_server.dart b/packages/core/lib/src/auth/authorization_server.dart index 661f231c9..f7d3c58c6 100644 --- a/packages/core/lib/src/auth/authorization_server.dart +++ b/packages/core/lib/src/auth/authorization_server.dart @@ -64,8 +64,8 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { this.delegate, { this.hashRounds = 1000, this.hashLength = 32, - Hash? hashFunction, - }) : hashFunction = hashFunction ?? sha256; + this.hashFunction = sha256, + }); /// The object responsible for carrying out the storage mechanisms of this instance. /// @@ -117,6 +117,12 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { /// /// [delegate] will store this client for future use. Future addClient(AuthClient client) async { + if (client.id.isEmpty) { + throw ArgumentError( + "A client must have an id.", + ); + } + if (client.redirectURI != null && client.hashedSecret == null) { throw ArgumentError( "A client with a redirectURI must have a client secret.", @@ -129,7 +135,7 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { /// Returns a [AuthClient] record for its [clientID]. /// /// Returns null if none exists. - Future getClient(String? clientID) async { + Future getClient(String clientID) async { return delegate.getClient(this, clientID); } @@ -137,8 +143,8 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { /// /// Removes cached occurrences of [AuthClient] for [clientID]. /// Asks [delegate] to remove an [AuthClient] by its ID via [AuthServerDelegate.removeClient]. - Future removeClient(String? clientID) async { - if (clientID == null) { + Future removeClient(String clientID) async { + if (clientID.isEmpty) { throw AuthServerException(AuthRequestError.invalidClient, null); } @@ -166,12 +172,12 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { Future authenticate( String? username, String? password, - String? clientID, + String clientID, String? clientSecret, { Duration expiration = const Duration(hours: 24), List? requestedScopes, }) async { - if (clientID == null) { + if (clientID.isEmpty) { throw AuthServerException(AuthRequestError.invalidClient, null); } @@ -240,7 +246,7 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { if (t == null || t.isExpired) { throw AuthServerException( AuthRequestError.invalidGrant, - AuthClient(t?.clientID, null, null), + AuthClient(t?.clientID ?? '', null, null), ); } @@ -268,11 +274,11 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { /// If not successful, it will throw an [AuthRequestError]. Future refresh( String? refreshToken, - String? clientID, + String clientID, String? clientSecret, { List? requestedScopes, }) async { - if (clientID == null) { + if (clientID.isEmpty) { throw AuthServerException(AuthRequestError.invalidClient, null); } @@ -356,11 +362,11 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { Future authenticateForCode( String? username, String? password, - String? clientID, { + String clientID, { int expirationInSeconds = 600, List? requestedScopes, }) async { - if (clientID == null) { + if (clientID.isEmpty) { throw AuthServerException(AuthRequestError.invalidClient, null); } @@ -407,11 +413,11 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { /// it will throw an appropriate [AuthRequestError]. Future exchange( String? authCodeString, - String? clientID, + String clientID, String? clientSecret, { int expirationInSeconds = 3600, }) async { - if (clientID == null) { + if (clientID.isEmpty) { throw AuthServerException(AuthRequestError.invalidClient, null); } @@ -561,7 +567,7 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { throw AuthServerException(AuthRequestError.invalidClient, client); } - if (client.hashedSecret != hashPassword(password!, client.salt!)) { + if (client.hashedSecret != hashPassword(password, client.salt!)) { throw AuthServerException(AuthRequestError.invalidClient, client); } @@ -607,7 +613,7 @@ class AuthServer implements AuthValidator, APIComponentDocumenter { AuthToken _generateToken( int? ownerID, - String? clientID, + String clientID, int expirationInSeconds, { bool allowRefresh = true, List? scopes, diff --git a/packages/core/lib/src/auth/exceptions.dart b/packages/core/lib/src/auth/exceptions.dart index ac51d8ef9..8f307a353 100644 --- a/packages/core/lib/src/auth/exceptions.dart +++ b/packages/core/lib/src/auth/exceptions.dart @@ -6,7 +6,7 @@ class AuthServerException implements Exception { /// Returns a string suitable to be included in a query string or JSON response body /// to indicate the error during processing an OAuth 2.0 request. - static String? errorString(AuthRequestError error) { + static String errorString(AuthRequestError error) { switch (error) { case AuthRequestError.invalidRequest: return "invalid_request"; @@ -39,7 +39,7 @@ class AuthServerException implements Exception { AuthRequestError reason; AuthClient? client; - String? get reasonString { + String get reasonString { return errorString(reason); } diff --git a/packages/core/lib/src/auth/objects.dart b/packages/core/lib/src/auth/objects.dart index cf6e12d7e..20abe7d3d 100644 --- a/packages/core/lib/src/auth/objects.dart +++ b/packages/core/lib/src/auth/objects.dart @@ -16,7 +16,7 @@ class AuthClient { /// If this client supports scopes, [allowedScopes] must contain a list of scopes that tokens may request when authorized /// by this client. AuthClient( - String? id, + String id, String? hashedSecret, String? salt, { List? allowedScopes, @@ -29,12 +29,13 @@ class AuthClient { ); /// Creates an instance of a public [AuthClient]. - AuthClient.public(String id, {List? allowedScopes}) + AuthClient.public(String id, + {List? allowedScopes, String? redirectURI}) : this.withRedirectURI( id, null, null, - null, + redirectURI, allowedScopes: allowedScopes, ); @@ -54,7 +55,7 @@ class AuthClient { List? _allowedScopes; /// The ID of the client. - String? id; + final String id; /// The hashed secret of the client. /// @@ -148,7 +149,7 @@ class AuthToken { int? resourceOwnerIdentifier; /// The client ID this token was issued from. - String? clientID; + late String clientID; /// Scopes this token has access to. List? scopes; @@ -190,7 +191,7 @@ class AuthCode { String? code; /// The client ID the authorization code was issued under. - String? clientID; + late String clientID; /// The identifier of the resource owner. /// @@ -234,7 +235,7 @@ class Authorization { }); /// The client ID the permission was granted under. - final String? clientID; + final String clientID; /// The identifier for the owner of the resource, if provided. /// @@ -374,7 +375,7 @@ class AuthScope { }); } - static final Map _cache = {}; + static final Map _cache = {}; final String _scopeString; diff --git a/packages/core/lib/src/auth/protocols.dart b/packages/core/lib/src/auth/protocols.dart index a856d5860..411503149 100644 --- a/packages/core/lib/src/auth/protocols.dart +++ b/packages/core/lib/src/auth/protocols.dart @@ -53,7 +53,7 @@ abstract class AuthServerDelegate { /// /// This method must return an instance of [AuthClient] if one exists for [clientID]. Otherwise, it must return null. /// [server] is the [AuthServer] requesting the [AuthClient]. - FutureOr getClient(AuthServer server, String? clientID); + FutureOr getClient(AuthServer server, String clientID); /// Removes an [AuthClient] for a client ID. /// @@ -74,7 +74,7 @@ abstract class AuthServerDelegate { /// If no match is found, return null. /// /// [server] is the [AuthServer] requesting the [AuthToken]. - FutureOr? getToken( + FutureOr getToken( AuthServer server, { String? byAccessToken, String? byRefreshToken, @@ -131,7 +131,7 @@ abstract class AuthServerDelegate { /// /// This must return an instance of [AuthCode] where [AuthCode.code] matches [code]. /// Return null if no matching code. - FutureOr? getCode(AuthServer server, String code); + FutureOr getCode(AuthServer server, String code); /// Must remove [AuthCode] identified by [code]. /// diff --git a/packages/core/lib/src/auth/validator.dart b/packages/core/lib/src/auth/validator.dart index f4550e5e8..c8baca557 100644 --- a/packages/core/lib/src/auth/validator.dart +++ b/packages/core/lib/src/auth/validator.dart @@ -22,7 +22,7 @@ mixin AuthValidator { /// If this method throws an [AuthServerException], an appropriate status code is sent for the details of the exception. /// /// If [requiredScope] is provided, a request's authorization must have at least that much scope to pass the [Authorizer]. - FutureOr? validate( + FutureOr validate( AuthorizationParser parser, T authorizationData, { List? requiredScope, diff --git a/packages/core/lib/src/db/managed/backing.dart b/packages/core/lib/src/db/managed/backing.dart index cd215a5cb..a4d62a392 100644 --- a/packages/core/lib/src/db/managed/backing.dart +++ b/packages/core/lib/src/db/managed/backing.dart @@ -37,8 +37,8 @@ class ManagedForeignKeyBuilderBacking extends ManagedBacking { ManagedEntity entity, ManagedBacking backing, ) { - if (backing.contents!.containsKey(entity.primaryKey)) { - contents[entity.primaryKey!] = backing.contents![entity.primaryKey]; + if (backing.contents.containsKey(entity.primaryKey)) { + contents[entity.primaryKey] = backing.contents[entity.primaryKey]; } } @@ -141,7 +141,7 @@ class ManagedAccessTrackingBacking extends ManagedBacking { KeyPath? workingKeyPath; @override - Map? get contents => null; + Map get contents => {}; @override dynamic valueForProperty(ManagedPropertyDescription property) { diff --git a/packages/core/lib/src/db/managed/context.dart b/packages/core/lib/src/db/managed/context.dart index 8187e4c4f..9cfcf7d0a 100644 --- a/packages/core/lib/src/db/managed/context.dart +++ b/packages/core/lib/src/db/managed/context.dart @@ -95,8 +95,8 @@ class ManagedContext implements APIComponentDocumenter { /// await q.insert(); /// ... /// }); - Future transaction( - Future Function(ManagedContext transaction) transactionBlock, + Future transaction( + Future Function(ManagedContext transaction) transactionBlock, ) { return persistentStore.transaction( ManagedContext.childOf(this), diff --git a/packages/core/lib/src/db/managed/data_model.dart b/packages/core/lib/src/db/managed/data_model.dart index a6dfd39b8..92360e561 100644 --- a/packages/core/lib/src/db/managed/data_model.dart +++ b/packages/core/lib/src/db/managed/data_model.dart @@ -30,10 +30,9 @@ class ManagedDataModel extends Object implements APIComponentDocumenter { ) .toList(); - final notFound = expectedRuntimes.where((e) => e == null).toList(); - if (notFound.isNotEmpty) { + if (expectedRuntimes.any((e) => e == null)) { throw ManagedDataModelError( - "Data model types were not found: ${notFound.map((e) => e!.entity.name).join(", ")}", + "Data model types were not found!", ); } diff --git a/packages/core/lib/src/db/managed/document.dart b/packages/core/lib/src/db/managed/document.dart index 51a48d94a..4fa22895c 100644 --- a/packages/core/lib/src/db/managed/document.dart +++ b/packages/core/lib/src/db/managed/document.dart @@ -37,7 +37,7 @@ class Document { /// /// When [data] is a [List], [keyOrIndex] must be a [int] and will return the object at the index /// in that list. - dynamic operator [](dynamic keyOrIndex) { + dynamic operator [](Object keyOrIndex) { return data[keyOrIndex]; } @@ -51,7 +51,7 @@ class Document { /// When [data] is a [List], [keyOrIndex] must be a [int] and will set [value] for the index /// [keyOrIndex]. This index must be within the length of [data]. For all other [List] operations, /// you may cast [data] to [List]. - void operator []=(dynamic keyOrIndex, dynamic value) { + void operator []=(Object keyOrIndex, dynamic value) { data[keyOrIndex] = value; } } diff --git a/packages/core/lib/src/db/managed/entity.dart b/packages/core/lib/src/db/managed/entity.dart index 8917b50aa..ff9a46e2b 100644 --- a/packages/core/lib/src/db/managed/entity.dart +++ b/packages/core/lib/src/db/managed/entity.dart @@ -58,7 +58,7 @@ class ManagedEntity implements APIComponentDocumenter { /// transient property declared in the instance type. /// The keys are the case-sensitive name of the attribute. Values that represent a relationship to another object /// are not stored in [attributes]. - late Map attributes; + late Map attributes; /// All relationship values of this entity. /// @@ -68,17 +68,15 @@ class ManagedEntity implements APIComponentDocumenter { /// for [ManagedRelationshipType.hasMany] or [ManagedRelationshipType.hasOne] properties, as those values are derived by the foreign key reference /// on the inverse relationship property. /// Keys are the case-sensitive name of the relationship. - Map? relationships; + late Map relationships; /// All properties (relationships and attributes) of this entity. /// /// The string key is the name of the property, case-sensitive. Values will be instances of either [ManagedAttributeDescription] /// or [ManagedRelationshipDescription]. This is the concatenation of [attributes] and [relationships]. - Map get properties { - final all = Map.from(attributes); - if (relationships != null) { - all.addAll(relationships!); - } + Map get properties { + final all = Map.from(attributes); + all.addAll(relationships); return all; } @@ -91,12 +89,12 @@ class ManagedEntity implements APIComponentDocumenter { /// a unique value for that property. /// /// This value is set by adding [Table] to the table definition of a [ManagedObject]. - List? uniquePropertySet; + List? uniquePropertySet; /// List of [ManagedValidator]s for attributes of this entity. /// /// All validators for all [attributes] in one, flat list. Order is undefined. - late List validators; + late List validators; /// The list of default property names of this object. /// @@ -117,7 +115,7 @@ class ManagedEntity implements APIComponentDocumenter { ); elements.addAll( - relationships!.values + relationships.values .where( (prop) => prop!.isIncludedInDefaultResultSet && @@ -133,7 +131,7 @@ class ManagedEntity implements APIComponentDocumenter { /// Name of primary key property. /// /// This is determined by the attribute with the [primaryKey] annotation. - String? primaryKey; + late String primaryKey; ManagedAttributeDescription? get primaryKeyAttribute { return attributes[primaryKey]; @@ -213,7 +211,7 @@ class ManagedEntity implements APIComponentDocumenter { final propertyName = elements.first!.name; final attribute = attributes[propertyName]; if (attribute == null) { - if (relationships!.containsKey(propertyName)) { + if (relationships.containsKey(propertyName)) { throw ArgumentError( "Invalid property selection. Property '$propertyName' on " "'$name' " @@ -258,7 +256,7 @@ class ManagedEntity implements APIComponentDocumenter { } final propertyName = elements.first!.name; - final desc = relationships![propertyName]; + final desc = relationships[propertyName]; if (desc == null) { throw ArgumentError( "Invalid property selection. Relationship named '$propertyName' on table '$tableName' is not a relationship.", @@ -273,7 +271,7 @@ class ManagedEntity implements APIComponentDocumenter { /// Invokes [identifyProperties] with [propertyIdentifier], and ensures that a single property /// on this entity was selected. Returns that property. KeyPath identifyProperty( - T Function(U? x) propertyIdentifier, + T Function(U x) propertyIdentifier, ) { final properties = identifyProperties(propertyIdentifier); if (properties.length != 1) { @@ -306,7 +304,7 @@ class ManagedEntity implements APIComponentDocumenter { final buffer = StringBuffer(); if (uniquePropertySet != null) { final propString = - uniquePropertySet!.map((s) => "'${s!.name}'").join(", "); + uniquePropertySet!.map((s) => "'${s.name}'").join(", "); buffer.writeln( "No two objects may have the same value for all of: $propString.", ); @@ -322,7 +320,7 @@ class ManagedEntity implements APIComponentDocumenter { } final schemaProperty = def!.documentSchemaObject(context); - schemaProperties[name!] = schemaProperty; + schemaProperties[name] = schemaProperty; }); return obj; @@ -344,7 +342,7 @@ class ManagedEntity implements APIComponentDocumenter { }); buf.writeln("Relationships:"); - relationships!.forEach((name, rel) { + relationships.forEach((name, rel) { buf.writeln("\t$rel"); }); diff --git a/packages/core/lib/src/db/managed/object.dart b/packages/core/lib/src/db/managed/object.dart index 703ec15b6..83be20eb4 100644 --- a/packages/core/lib/src/db/managed/object.dart +++ b/packages/core/lib/src/db/managed/object.dart @@ -32,12 +32,12 @@ abstract class ManagedBacking { /// Removes a property from this instance. /// /// Use this method to use any reference of a property from this instance. - void removeProperty(String? propertyName) { - contents!.remove(propertyName); + void removeProperty(String propertyName) { + contents.remove(propertyName); } /// A map of all set values of this instance. - Map? get contents; + Map get contents; } /// An object that represents a database row. @@ -66,12 +66,11 @@ abstract class ManagedBacking { /// See more documentation on defining a data model at http://conduit.io/docs/db/modeling_data/ abstract class ManagedObject extends Serializable { /// IMPROVEMENT: Cache of entity.properties to reduce property loading time - late Map properties = entity.properties; + late Map properties = entity.properties; /// Cache of entity.properties using ResponseKey name as key, in case no ResponseKey is set then default property name is used as key - late Map responseKeyProperties = { - for (final key in properties.keys) - if (key != null) mapKeyName(key): properties[key] + late Map responseKeyProperties = { + for (final key in properties.keys) mapKeyName(key): properties[key] }; late final bool modelFieldIncludeIfNull = properties.isEmpty || @@ -98,7 +97,7 @@ abstract class ManagedObject extends Serializable { ManagedBacking backing = ManagedValueBacking(); /// Retrieves a value by property name from [backing]. - dynamic operator [](String? propertyName) { + dynamic operator [](String propertyName) { final prop = properties[propertyName]; if (prop == null) { throw ArgumentError("Invalid property access for '${entity.name}'. " @@ -122,7 +121,7 @@ abstract class ManagedObject extends Serializable { /// Removes a property from [backing]. /// /// This will remove a value from the backing map. - void removePropertyFromBackingMap(String? propertyName) { + void removePropertyFromBackingMap(String propertyName) { backing.removeProperty(propertyName); } @@ -135,7 +134,7 @@ abstract class ManagedObject extends Serializable { /// Checks whether or not a property has been set in this instances' [backing]. bool hasValueForProperty(String propertyName) { - return backing.contents!.containsKey(propertyName); + return backing.contents.containsKey(propertyName); } /// Callback to modify an object prior to updating it with a [Query]. @@ -270,7 +269,7 @@ abstract class ManagedObject extends Serializable { Map asMap() { final outputMap = {}; - backing.contents!.forEach((k, v) { + backing.contents.forEach((k, v) { if (!_isPropertyPrivate(k)) { final property = properties[k]; final value = property!.convertToPrimitiveValue(v); diff --git a/packages/core/lib/src/db/managed/property_description.dart b/packages/core/lib/src/db/managed/property_description.dart index daaf6d407..d3dce88bf 100644 --- a/packages/core/lib/src/db/managed/property_description.dart +++ b/packages/core/lib/src/db/managed/property_description.dart @@ -22,7 +22,7 @@ abstract class ManagedPropertyDescription { bool nullable = false, bool includedInDefaultResultSet = true, this.autoincrement = false, - List validators = const [], + List validators = const [], this.responseModel, this.responseKey, }) : isUnique = unique, @@ -31,7 +31,7 @@ abstract class ManagedPropertyDescription { isIncludedInDefaultResultSet = includedInDefaultResultSet, _validators = validators { for (final v in _validators) { - v!.property = this; + v.property = this; } } @@ -84,9 +84,9 @@ abstract class ManagedPropertyDescription { } /// [ManagedValidator]s for this instance. - List get validators => _validators; + List get validators => _validators; - final List _validators; + final List _validators; final ResponseModel? responseModel; final ResponseKey? responseKey; @@ -274,7 +274,7 @@ class ManagedAttributeDescription extends ManagedPropertyDescription { // Add'l schema info prop.isNullable = isNullable; for (final v in validators) { - v!.definition.constrainSchemaObject(context, prop); + v.definition.constrainSchemaObject(context, prop); } if (isEnumeratedValue) { @@ -410,7 +410,7 @@ class ManagedRelationshipDescription extends ManagedPropertyDescription { super.indexed, super.nullable, super.includedInDefaultResultSet, - List super.validators = const [], + super.validators = const [], super.responseModel, super.responseKey, }); @@ -460,11 +460,11 @@ class ManagedRelationshipDescription extends ManagedPropertyDescription { final ManagedRelationshipType relationshipType; /// The name of the [ManagedRelationshipDescription] on [destinationEntity] that represents the inverse of this relationship. - final String? inverseKey; + final String inverseKey; /// The [ManagedRelationshipDescription] on [destinationEntity] that represents the inverse of this relationship. ManagedRelationshipDescription? get inverse => - destinationEntity.relationships![inverseKey]; + destinationEntity.relationships[inverseKey]; /// Whether or not this relationship is on the belonging side. bool get isBelongsTo => relationshipType == ManagedRelationshipType.belongsTo; @@ -487,10 +487,10 @@ class ManagedRelationshipDescription extends ManagedPropertyDescription { } else if (value is ManagedObject) { // If we're only fetching the foreign key, don't do a full asMap if (relationshipType == ManagedRelationshipType.belongsTo && - value.backing.contents!.length == 1 && - value.backing.contents!.containsKey(destinationEntity.primaryKey)) { - return { - destinationEntity.primaryKey!: value[destinationEntity.primaryKey] + value.backing.contents.length == 1 && + value.backing.contents.containsKey(destinationEntity.primaryKey)) { + return { + destinationEntity.primaryKey: value[destinationEntity.primaryKey] }; } diff --git a/packages/core/lib/src/db/managed/set.dart b/packages/core/lib/src/db/managed/set.dart index d1d55e3a1..21cdea9ab 100644 --- a/packages/core/lib/src/db/managed/set.dart +++ b/packages/core/lib/src/db/managed/set.dart @@ -36,7 +36,7 @@ class ManagedSet extends Object _innerValues = List.from(items); } - late List _innerValues; + late final List _innerValues; /// The number of elements in this set. @override diff --git a/packages/core/lib/src/db/managed/validation/managed.dart b/packages/core/lib/src/db/managed/validation/managed.dart index 7fe84fb90..bf4d4fc5f 100644 --- a/packages/core/lib/src/db/managed/validation/managed.dart +++ b/packages/core/lib/src/db/managed/validation/managed.dart @@ -22,7 +22,7 @@ class ManagedValidator { final context = ValidationContext(); for (final validator in object.entity.validators) { - context.property = validator!.property; + context.property = validator.property; context.event = event; context.state = validator.state; if (!validator.definition.runOnInsert && event == Validating.insert) { @@ -34,17 +34,17 @@ class ManagedValidator { } var contents = object.backing.contents; - String? key = validator.property!.name; + String key = validator.property!.name; if (validator.definition.type == ValidateType.present) { if (validator.property is ManagedRelationshipDescription) { final inner = object[validator.property!.name] as ManagedObject?; if (inner == null || - !inner.backing.contents!.containsKey(inner.entity.primaryKey)) { + !inner.backing.contents.containsKey(inner.entity.primaryKey)) { context.addError("key '${validator.property!.name}' is required " "for ${_getEventName(event)}s."); } - } else if (!contents!.containsKey(key)) { + } else if (!contents.containsKey(key)) { context.addError("key '${validator.property!.name}' is required " "for ${_getEventName(event)}s."); } @@ -55,7 +55,7 @@ class ManagedValidator { context.addError("key '${validator.property!.name}' is not allowed " "for ${_getEventName(event)}s."); } - } else if (contents!.containsKey(key)) { + } else if (contents.containsKey(key)) { context.addError("key '${validator.property!.name}' is not allowed " "for ${_getEventName(event)}s."); } @@ -63,14 +63,14 @@ class ManagedValidator { if (validator.property is ManagedRelationshipDescription) { final inner = object[validator.property!.name] as ManagedObject?; if (inner == null || - inner.backing.contents![inner.entity.primaryKey] == null) { + inner.backing.contents[inner.entity.primaryKey] == null) { continue; } contents = inner.backing.contents; key = inner.entity.primaryKey; } - final value = contents![key]; + final value = contents[key]; if (value != null) { validator.validate(context, value); } diff --git a/packages/core/lib/src/db/managed/validation/metadata.dart b/packages/core/lib/src/db/managed/validation/metadata.dart index 049419a94..1730ef414 100644 --- a/packages/core/lib/src/db/managed/validation/metadata.dart +++ b/packages/core/lib/src/db/managed/validation/metadata.dart @@ -324,7 +324,7 @@ class Validate { /// If compilation fails, throw a [ValidateCompilationError] with a message describing the issue. The entity /// and property will automatically be added to the error. dynamic compile( - ManagedType? typeBeingValidated, { + ManagedType typeBeingValidated, { Type? relationshipInverseType, }) { switch (type) { @@ -335,7 +335,7 @@ class Validate { case ValidateType.oneOf: { return _oneOfCompiler( - typeBeingValidated!, + typeBeingValidated, relationshipInverseType: relationshipInverseType, ); } @@ -631,10 +631,10 @@ class Validate { } dynamic _lengthCompiler( - ManagedType? typeBeingValidated, { + ManagedType typeBeingValidated, { Type? relationshipInverseType, }) { - if (typeBeingValidated?.kind != ManagedPropertyType.string) { + if (typeBeingValidated.kind != ManagedPropertyType.string) { throw ValidateCompilationError( "Validate.length is only valid for 'String' properties.", ); diff --git a/packages/core/lib/src/db/persistent_store/persistent_store.dart b/packages/core/lib/src/db/persistent_store/persistent_store.dart index 565bd13fd..5a2a5c09d 100644 --- a/packages/core/lib/src/db/persistent_store/persistent_store.dart +++ b/packages/core/lib/src/db/persistent_store/persistent_store.dart @@ -34,9 +34,9 @@ abstract class PersistentStore { PersistentStoreQueryReturnType? returnType, }); - Future transaction( + Future transaction( ManagedContext transactionContext, - Future Function(ManagedContext transaction) transactionBlock, + Future Function(ManagedContext transaction) transactionBlock, ); /// Closes the underlying database connection. @@ -92,7 +92,7 @@ abstract class PersistentStore { Future get schemaVersion; - Future upgrade( + Future upgrade( Schema fromSchema, List withMigrations, { bool temporary = false, diff --git a/packages/core/lib/src/db/query/mixin.dart b/packages/core/lib/src/db/query/mixin.dart index 1acbb1139..49670723f 100644 --- a/packages/core/lib/src/db/query/mixin.dart +++ b/packages/core/lib/src/db/query/mixin.dart @@ -29,8 +29,8 @@ mixin QueryMixin QuerySortPredicate? sortPredicate; QueryPage? pageDescriptor; - List? sortDescriptors; - Map? subQueries; + final List sortDescriptors = []; + final Map subQueries = {}; QueryMixin? _parentQuery; List> expressions = []; @@ -113,8 +113,7 @@ mixin QueryMixin ) { final attribute = entity.identifyAttribute(propertyIdentifier); - sortDescriptors ??= []; - sortDescriptors!.add(QuerySortDescriptor(attribute.name, order)); + sortDescriptors.add(QuerySortDescriptor(attribute.name, order)); } @override @@ -156,7 +155,7 @@ mixin QueryMixin Query _createSubquery( ManagedRelationshipDescription fromRelationship, ) { - if (subQueries?.containsKey(fromRelationship) ?? false) { + if (subQueries.containsKey(fromRelationship)) { throw StateError( "Invalid query. Cannot join same property more than once.", ); @@ -165,8 +164,8 @@ mixin QueryMixin // Ensure we don't cyclically join var parent = _parentQuery; while (parent != null) { - if (parent.subQueries!.containsKey(fromRelationship.inverse)) { - final validJoins = fromRelationship.entity.relationships!.values + if (parent.subQueries.containsKey(fromRelationship.inverse)) { + final validJoins = fromRelationship.entity.relationships.values .where((r) => !identical(r, fromRelationship)) .map((r) => "'${r!.name}'") .join(", "); @@ -183,11 +182,9 @@ mixin QueryMixin parent = parent._parentQuery; } - subQueries ??= {}; - final subquery = Query(context); (subquery as QueryMixin)._parentQuery = this; - subQueries![fromRelationship] = subquery; + subQueries[fromRelationship] = subquery; return subquery; } diff --git a/packages/core/lib/src/db/query/page.dart b/packages/core/lib/src/db/query/page.dart index f9281f670..e346766bb 100644 --- a/packages/core/lib/src/db/query/page.dart +++ b/packages/core/lib/src/db/query/page.dart @@ -25,7 +25,7 @@ class QueryPage { /// The property of the model object to page on. /// /// This property must have an inherent order, such as an [int] or [DateTime]. The database must be able to compare the values of this property using comparison operator '<' and '>'. - String? propertyName; + String propertyName; /// The point within an ordered set of result values in which rows will begin being fetched from. /// diff --git a/packages/core/lib/src/db/query/predicate.dart b/packages/core/lib/src/db/query/predicate.dart index 3bd6b1af3..b9296954f 100644 --- a/packages/core/lib/src/db/query/predicate.dart +++ b/packages/core/lib/src/db/query/predicate.dart @@ -36,20 +36,15 @@ class QueryPredicate { /// /// If [predicates] is null or empty, an empty predicate is returned. If [predicates] contains only /// one predicate, that predicate is returned. - factory QueryPredicate.and(Iterable? predicates) { - final predicateList = predicates - ?.where((p) => p?.format != null && p!.format.isNotEmpty) - .toList(); - if (predicateList == null) { - return QueryPredicate.empty(); - } + factory QueryPredicate.and(Iterable predicates) { + final predicateList = predicates.where((p) => p.format.isNotEmpty).toList(); if (predicateList.isEmpty) { return QueryPredicate.empty(); } if (predicateList.length == 1) { - return predicateList.first!; + return predicateList.first; } // If we have duplicate keys anywhere, we need to disambiguate them. @@ -57,13 +52,13 @@ class QueryPredicate { final allFormatStrings = []; final valueMap = {}; for (final predicate in predicateList) { - final duplicateKeys = predicate!.parameters.keys + final duplicateKeys = predicate.parameters.keys .where((k) => valueMap.keys.contains(k)) .toList(); if (duplicateKeys.isNotEmpty) { var fmt = predicate.format; - final Map dupeMap = {}; + final Map dupeMap = {}; for (final key in duplicateKeys) { final replacementKey = "$key$dupeCounter"; fmt = fmt.replaceAll("@$key", "@$replacementKey"); diff --git a/packages/core/lib/src/db/query/query.dart b/packages/core/lib/src/db/query/query.dart index 3cffcf6d1..acb7dbfc6 100644 --- a/packages/core/lib/src/db/query/query.dart +++ b/packages/core/lib/src/db/query/query.dart @@ -412,7 +412,7 @@ abstract class Query { /// var q = Query() /// ..where.id = whereEqualTo(1); /// var deletedCount = await q.delete(); - Future delete(); + Future delete(); } /// Order value for [Query.pageBy] and [Query.sortBy]. diff --git a/packages/core/lib/src/db/query/sort_descriptor.dart b/packages/core/lib/src/db/query/sort_descriptor.dart index 7cb1b3029..6e9ef893d 100644 --- a/packages/core/lib/src/db/query/sort_descriptor.dart +++ b/packages/core/lib/src/db/query/sort_descriptor.dart @@ -7,7 +7,7 @@ class QuerySortDescriptor { QuerySortDescriptor(this.key, this.order); /// The name of a property to sort by. - String? key; + String key; /// The order in which values should be sorted. /// diff --git a/packages/core/lib/src/db/schema/migration.dart b/packages/core/lib/src/db/schema/migration.dart index 0256c85fc..ec668a6de 100644 --- a/packages/core/lib/src/db/schema/migration.dart +++ b/packages/core/lib/src/db/schema/migration.dart @@ -22,7 +22,7 @@ abstract class Migration { /// /// During migration, this value will be modified as [SchemaBuilder] operations /// are executed. See [SchemaBuilder]. - Schema? get currentSchema => database.schema; + Schema get currentSchema => database.schema; /// The [PersistentStore] that represents the database being migrated. PersistentStore? get store => database.store; diff --git a/packages/core/lib/src/db/schema/schema.dart b/packages/core/lib/src/db/schema/schema.dart index 15890814c..48b0540c4 100644 --- a/packages/core/lib/src/db/schema/schema.dart +++ b/packages/core/lib/src/db/schema/schema.dart @@ -28,10 +28,9 @@ class Schema { } /// Creates a deep copy of [otherSchema]. - Schema.from(Schema? otherSchema) { + Schema.from(Schema otherSchema) { _tables = - otherSchema?.tables.map((table) => SchemaTable.from(table)).toList() ?? - []; + otherSchema.tables.map((table) => SchemaTable.from(table)).toList(); } /// Creates a instance of this type from [map]. @@ -51,14 +50,14 @@ class Schema { /// The tables in this database. /// /// Returns an immutable list of tables in this schema. - List get tables => List.unmodifiable(_tableStorage ?? []); + List get tables => List.unmodifiable(_tableStorage); // Do not set this directly. Use _tables= instead. - List? _tableStorage; + late List _tableStorage; set _tables(List tables) { _tableStorage = tables; - for (final t in _tableStorage!) { + for (final t in _tableStorage) { t.schema = this; } } @@ -86,19 +85,19 @@ class Schema { ); } - _tableStorage!.add(table); + _tableStorage.add(table); table.schema = this; } void replaceTable(SchemaTable existingTable, SchemaTable newTable) { - if (!_tableStorage!.contains(existingTable)) { + if (!_tableStorage.contains(existingTable)) { throw SchemaException( "Table ${existingTable.name} does not exist and cannot be replaced.", ); } - final index = _tableStorage!.indexOf(existingTable); - _tableStorage![index] = newTable; + final index = _tableStorage.indexOf(existingTable); + _tableStorage[index] = newTable; newTable.schema = this; existingTable.schema = null; } @@ -127,7 +126,7 @@ class Schema { throw SchemaException("Table ${table.name} does not exist in schema."); } table.schema = null; - _tableStorage!.remove(table); + _tableStorage.remove(table); } /// Returns a [SchemaTable] for [name]. diff --git a/packages/core/lib/src/db/schema/schema_builder.dart b/packages/core/lib/src/db/schema/schema_builder.dart index b0fc79dc8..c7bee6ad6 100644 --- a/packages/core/lib/src/db/schema/schema_builder.dart +++ b/packages/core/lib/src/db/schema/schema_builder.dart @@ -60,10 +60,10 @@ class SchemaBuilder { } /// The starting schema of this builder. - Schema? inputSchema; + late Schema inputSchema; /// The resulting schema of this builder as operations are applied to it. - Schema? schema; + late Schema schema; /// The persistent store to validate and construct operations. /// @@ -82,7 +82,7 @@ class SchemaBuilder { /// Validates and adds a table to [schema]. void createTable(SchemaTable table) { - schema!.addTable(table); + schema.addTable(table); if (store != null) { commands.addAll(store!.createTable(table, isTemporary: isTemporary)); @@ -93,12 +93,12 @@ class SchemaBuilder { /// Validates and renames a table in [schema]. void renameTable(String currentTableName, String newName) { - final table = schema!.tableForName(currentTableName); + final table = schema.tableForName(currentTableName); if (table == null) { throw SchemaException("Table $currentTableName does not exist."); } - schema!.renameTable(table, newName); + schema.renameTable(table, newName); if (store != null) { commands.addAll(store!.renameTable(table, newName)); } else { @@ -108,12 +108,12 @@ class SchemaBuilder { /// Validates and deletes a table in [schema]. void deleteTable(String tableName) { - final table = schema!.tableForName(tableName); + final table = schema.tableForName(tableName); if (table == null) { throw SchemaException("Table $tableName does not exist."); } - schema!.removeTable(table); + schema.removeTable(table); if (store != null) { commands.addAll(store!.deleteTable(table)); @@ -127,14 +127,14 @@ class SchemaBuilder { String tableName, void Function(SchemaTable targetTable) modify, ) { - final existingTable = schema!.tableForName(tableName); + final existingTable = schema.tableForName(tableName); if (existingTable == null) { throw SchemaException("Table $tableName does not exist."); } final newTable = SchemaTable.from(existingTable); modify(newTable); - schema!.replaceTable(existingTable, newTable); + schema.replaceTable(existingTable, newTable); final shouldAddUnique = existingTable.uniqueColumnSet == null && newTable.uniqueColumnSet != null; @@ -187,7 +187,7 @@ class SchemaBuilder { SchemaColumn column, { String? unencodedInitialValue, }) { - final table = schema!.tableForName(tableName); + final table = schema.tableForName(tableName); if (table == null) { throw SchemaException("Table $tableName does not exist."); } @@ -210,7 +210,7 @@ class SchemaBuilder { /// Validates and deletes a column in a table in [schema]. void deleteColumn(String tableName, String columnName) { - final table = schema!.tableForName(tableName); + final table = schema.tableForName(tableName); if (table == null) { throw SchemaException("Table $tableName does not exist."); } @@ -231,7 +231,7 @@ class SchemaBuilder { /// Validates and renames a column in a table in [schema]. void renameColumn(String tableName, String columnName, String newName) { - final table = schema!.tableForName(tableName); + final table = schema.tableForName(tableName); if (table == null) { throw SchemaException("Table $tableName does not exist."); } @@ -270,7 +270,7 @@ class SchemaBuilder { void Function(SchemaColumn targetColumn) modify, { String? unencodedInitialValue, }) { - final table = schema!.tableForName(tableName); + final table = schema.tableForName(tableName); if (table == null) { throw SchemaException("Table $tableName does not exist."); } diff --git a/packages/core/lib/src/db/schema/schema_table.dart b/packages/core/lib/src/db/schema/schema_table.dart index 8a38dc949..e0340238a 100644 --- a/packages/core/lib/src/db/schema/schema_table.dart +++ b/packages/core/lib/src/db/schema/schema_table.dart @@ -33,7 +33,7 @@ class SchemaTable { _columns = validProperties.map((p) => SchemaColumn.fromProperty(p!)).toList(); - uniqueColumnSet = entity.uniquePropertySet?.map((p) => p!.name).toList(); + uniqueColumnSet = entity.uniquePropertySet?.map((p) => p.name).toList(); } /// Creates a deep copy of [otherTable]. @@ -71,7 +71,7 @@ class SchemaTable { List? get uniqueColumnSet => _uniqueColumnSet != null ? List.unmodifiable(_uniqueColumnSet!) : null; - set uniqueColumnSet(List? columnNames) { + set uniqueColumnSet(List? columnNames) { if (columnNames != null) { _uniqueColumnSet = List.from(columnNames); _uniqueColumnSet?.sort((String a, String b) => a.compareTo(b)); diff --git a/packages/core/lib/src/http/body_decoder.dart b/packages/core/lib/src/http/body_decoder.dart index 14922068c..3f8050b1f 100644 --- a/packages/core/lib/src/http/body_decoder.dart +++ b/packages/core/lib/src/http/body_decoder.dart @@ -52,7 +52,7 @@ abstract class BodyDecoder { ); } - return (_decodedData as Object?).runtimeType; + return _decodedData.runtimeType; } /// The raw bytes of this request body. diff --git a/packages/core/lib/src/http/controller.dart b/packages/core/lib/src/http/controller.dart index b1c0aada7..96cee0129 100644 --- a/packages/core/lib/src/http/controller.dart +++ b/packages/core/lib/src/http/controller.dart @@ -104,7 +104,7 @@ abstract class Controller /// /// See [linkFunction] for a variant of this method that takes a closure instead of an object. @override - Linkable? link(Controller Function() instantiator) { + Linkable link(Controller Function() instantiator) { final instance = instantiator(); if (instance is Recyclable) { _nextController = _ControllerRecycler(instantiator, instance); @@ -112,7 +112,7 @@ abstract class Controller _nextController = instantiator(); } - return _nextController; + return _nextController!; } /// Links a function controller to the receiver to form a request channel. @@ -384,9 +384,9 @@ class _ControllerRecycler extends Controller { } @override - Linkable? link(Controller Function() instantiator) { + Linkable link(Controller Function() instantiator) { final c = super.link(instantiator); - nextInstanceToReceive?._nextController = c as Controller?; + nextInstanceToReceive?._nextController = c as Controller; return c; } diff --git a/packages/core/lib/src/http/cors_policy.dart b/packages/core/lib/src/http/cors_policy.dart index 0b872eb1e..749773ac0 100644 --- a/packages/core/lib/src/http/cors_policy.dart +++ b/packages/core/lib/src/http/cors_policy.dart @@ -83,7 +83,7 @@ class CORSPolicy { /// Whether or not to allow use of credentials, including Authorization and cookies. /// /// Defaults to true. In the specification (http://www.w3.org/TR/cors/), this is 'supports credentials'. - bool? allowCredentials; + late bool allowCredentials; /// Which response headers to expose to the client. /// @@ -121,7 +121,7 @@ class CORSPolicy { exposedResponseHeaders.join(", "); } - if (allowCredentials!) { + if (allowCredentials) { headers["Access-Control-Allow-Credentials"] = "true"; } @@ -188,7 +188,7 @@ class CORSPolicy { "Access-Control-Allow-Headers": allowedRequestHeaders.join(", ") }; - if (allowCredentials!) { + if (allowCredentials) { headers["Access-Control-Allow-Credentials"] = "true"; } diff --git a/packages/core/lib/src/http/request_path.dart b/packages/core/lib/src/http/request_path.dart index 0c8511ea5..bc5b3ceea 100644 --- a/packages/core/lib/src/http/request_path.dart +++ b/packages/core/lib/src/http/request_path.dart @@ -27,7 +27,7 @@ class RequestPath { if (segment.isVariable) { variables[segment.variableName.toString()] = requestSegment; - orderedVariableNames.add(segment.variableName); + orderedVariableNames.add(segment.variableName!); } else if (segment.isRemainingMatcher) { final remaining = []; remaining.add(requestIterator.current); @@ -51,7 +51,7 @@ class RequestPath { /// /users/2 /// This property will be {'id' : '2'}. /// - Map variables = {}; + Map variables = {}; /// A list of the segments in a matched path. /// @@ -73,7 +73,7 @@ class RequestPath { /// available for the specific request are in this list. For example, if a route has two path variables, /// but the incoming request this [RequestPath] represents only has one variable, only that one variable /// will appear in this property. - List orderedVariableNames = []; + List orderedVariableNames = []; /// The path of the requested URI. /// diff --git a/packages/core/lib/src/http/resource_controller.dart b/packages/core/lib/src/http/resource_controller.dart index 695561ead..d7a0217d1 100755 --- a/packages/core/lib/src/http/resource_controller.dart +++ b/packages/core/lib/src/http/resource_controller.dart @@ -89,7 +89,7 @@ abstract class ResourceController extends Controller /// These values are attached by a [Router] instance that precedes this [Controller]. Is null /// if no [Router] preceded the controller and is the empty map if there are no values. The keys /// are the case-sensitive name of the path variables as defined by [Router.route]. - Map? get pathVariables => request!.path.variables; + Map get pathVariables => request!.path.variables; /// Types of content this [ResourceController] will accept. /// @@ -135,7 +135,7 @@ abstract class ResourceController extends Controller } @override - FutureOr handle(Request request) async { + FutureOr handle(Request request) async { this.request = request; final preprocessedResult = await willProcessRequest(request); @@ -157,7 +157,7 @@ abstract class ResourceController extends Controller /// this method. When overriding this method, call the superclass' implementation and add the additional parameters /// to the returned list before returning the combined list. @mustCallSuper - List? documentOperationParameters( + List? documentOperationParameters( APIDocumentContext context, Operation? operation, ) { @@ -258,7 +258,7 @@ abstract class ResourceController extends Controller .toList(); } - Future _process() async { + Future _process() async { if (!request!.body.isEmpty) { if (!_requestContentTypeIsSupported(request)) { return Response(HttpStatus.unsupportedMediaType, null, null); @@ -386,10 +386,8 @@ abstract class ResourceController extends Controller /* bind and invoke */ _runtime!.applyRequestProperties(this, args); final response = await operation.invoker(this, args); - if (response != null) { - if (!response.hasExplicitlySetContentType) { - response.contentType = responseContentType; - } + if (!response.hasExplicitlySetContentType) { + response.contentType = responseContentType; } return response; diff --git a/packages/core/lib/src/http/resource_controller_interfaces.dart b/packages/core/lib/src/http/resource_controller_interfaces.dart index e7aa7efcc..39679c49f 100755 --- a/packages/core/lib/src/http/resource_controller_interfaces.dart +++ b/packages/core/lib/src/http/resource_controller_interfaces.dart @@ -30,7 +30,7 @@ abstract class ResourceControllerRuntime { abstract class ResourceControllerDocumenter { void documentComponents(ResourceController rc, APIDocumentContext context); - List documentOperationParameters( + List documentOperationParameters( ResourceController rc, APIDocumentContext context, Operation? operation, @@ -69,7 +69,7 @@ class ResourceControllerOperation { final List positionalParameters; final List namedParameters; - final Future Function( + final Future Function( ResourceController resourceController, ResourceControllerOperationInvocationArgs args, ) invoker; diff --git a/packages/core/lib/src/http/router.dart b/packages/core/lib/src/http/router.dart index c9f833866..66c1f40d5 100644 --- a/packages/core/lib/src/http/router.dart +++ b/packages/core/lib/src/http/router.dart @@ -89,7 +89,7 @@ class Router extends Controller { /// Routers override this method to throw an exception. Use [route] instead. @override - Linkable? link(Controller Function() generatorFunction) { + Linkable link(Controller Function() generatorFunction) { throw ArgumentError( "Invalid link. 'Router' cannot directly link to controllers. Use 'route'.", ); diff --git a/packages/core/lib/src/runtime/orm/entity_builder.dart b/packages/core/lib/src/runtime/orm/entity_builder.dart index eea2672a0..b3e5ffa2a 100644 --- a/packages/core/lib/src/runtime/orm/entity_builder.dart +++ b/packages/core/lib/src/runtime/orm/entity_builder.dart @@ -163,8 +163,10 @@ class EntityBuilder { entity.validators = []; entity.validators.addAll(attributes.values.expand((a) => a!.validators)); entity.validators.addAll(relationships.values.expand((a) => a!.validators)); - entity.uniquePropertySet = - uniquePropertySet?.map((key) => entity.properties[key]).toList(); + entity.uniquePropertySet = uniquePropertySet + ?.map((key) => entity.properties[key]) + .nonNulls + .toList(); } PropertyBuilder getInverseOf(PropertyBuilder foreignKey) { diff --git a/packages/core/lib/src/runtime/orm/property_builder.dart b/packages/core/lib/src/runtime/orm/property_builder.dart index 24fa8efab..8ce10c025 100644 --- a/packages/core/lib/src/runtime/orm/property_builder.dart +++ b/packages/core/lib/src/runtime/orm/property_builder.dart @@ -172,11 +172,7 @@ class PropertyBuilder { indexed: true, nullable: nullable, includedInDefaultResultSet: includeInDefaultResultSet, - validators: validators! - .map((v) => v.managedValidator) - .where((v) => v != null) - .cast() - .toList(), + validators: validators!.map((v) => v.managedValidator).toList(), responseModel: parent.responseModel, responseKey: responseKey, ); diff --git a/packages/core/lib/src/runtime/orm/validator_builder.dart b/packages/core/lib/src/runtime/orm/validator_builder.dart index 191230218..67f5d6787 100644 --- a/packages/core/lib/src/runtime/orm/validator_builder.dart +++ b/packages/core/lib/src/runtime/orm/validator_builder.dart @@ -12,9 +12,9 @@ class ValidatorBuilder { final PropertyBuilder property; final Validate metadata; dynamic _state; - ManagedValidator? _validator; + late ManagedValidator _validator; - ManagedValidator? get managedValidator => _validator; + ManagedValidator get managedValidator => _validator; void compile(final List entityBuilders) {} @@ -27,7 +27,7 @@ class ValidatorBuilder { } } Type? type; - PropertyBuilder? prop = property; + PropertyBuilder prop = property; if (property.isRelationship) { if (property.relationshipType != ManagedRelationshipType.belongsTo) { throw ManagedDataModelError( @@ -40,7 +40,7 @@ class ValidatorBuilder { } try { - _state = metadata.compile(prop.type, relationshipInverseType: type); + _state = metadata.compile(prop.type!, relationshipInverseType: type); } on ValidateCompilationError catch (e) { throw ManagedDataModelError( "Invalid '@Validate' on property '${property.parent.name}.${property.name}'. Reason: ${e.reason}", diff --git a/packages/core/lib/src/runtime/orm_impl.dart b/packages/core/lib/src/runtime/orm_impl.dart index 1f1382e2f..258181679 100644 --- a/packages/core/lib/src/runtime/orm_impl.dart +++ b/packages/core/lib/src/runtime/orm_impl.dart @@ -130,17 +130,16 @@ class ManagedEntityRuntimeImpl extends ManagedEntityRuntime return []; } - final type = element.variable.type; + final type = element.variable2!.type; final isSubclassOrInstanceOfValidate = - type.getDisplayString(withNullability: true) == "Validate" || + type.getDisplayString() == "Validate" || buildCtx.context.getSubclassesOf(Validate).any( (subclass) { return MirrorSystem.getName(subclass.simpleName) == - type.getDisplayString(withNullability: true); + type.getDisplayString(); }, ); - final isInstanceOfColumn = - type.getDisplayString(withNullability: true) == "Column"; + final isInstanceOfColumn = type.getDisplayString() == "Column"; if (isSubclassOrInstanceOfValidate) { importUris.add(annotation.element!.source!.uri); @@ -149,7 +148,7 @@ class ManagedEntityRuntimeImpl extends ManagedEntityRuntime final originatingLibrary = element.session! .getParsedLibraryByElement(element.library) as ParsedLibraryResult; final elementDeclaration = originatingLibrary - .getElementDeclaration(element.variable)! + .getElementDeclaration(element.variable2!)! .node as VariableDeclaration; return _getConstructorSourcesFromColumnArgList( @@ -439,22 +438,22 @@ return entity.symbolMap[Symbol(symbolName)]; final className = MirrorSystem.getName(instanceType.simpleName); final originalFileUri = instanceType.location!.sourceUri.toString(); final relationshipsStr = (await Future.wait( - entity.relationships!.keys.map((name) async { - return "'$name': ${await _getRelationshipInstantiator(ctx, entity.relationships![name]!, importUris: importUris)}"; + entity.relationships.keys.map((name) async { + return "'$name': ${await _getRelationshipInstantiator(ctx, entity.relationships[name]!, importUris: importUris)}"; }), )) .join(", "); final uniqueStr = entity.uniquePropertySet == null ? "null" - : "[${entity.uniquePropertySet!.map((u) => "'${u!.name}'").join(",")}].map((k) => entity.properties[k]).toList()"; + : "[${entity.uniquePropertySet!.map((u) => "'${u.name}'").join(",")}].map((k) => entity.properties[k]).nonNulls.toList()"; final entityConstructor = await _getEntityConstructor(ctx, importUris: importUris); // Need to import any relationships types and metadata types // todo: limit import of importUris to only show symbols required to replicate metadata - final directives = entity.relationships!.values.map((r) { + final directives = entity.relationships.values.map((r) { var mirror = reflectType(r!.declaredType!); if (mirror.isSubtypeOf(reflectType(ManagedSet))) { mirror = mirror.typeArguments.first; @@ -488,7 +487,7 @@ class ManagedEntityRuntimeImpl extends ManagedEntityRuntime { _entity.relationships = {$relationshipsStr}; _entity.validators = []; _entity.validators.addAll(_entity.attributes.values.expand((a) => a!.validators)); - _entity.validators.addAll(_entity.relationships?.values.expand((a) => a!.validators) ?? []); + _entity.validators.addAll(_entity.relationships.values.expand((a) => a!.validators)); entity.uniquePropertySet = $uniqueStr; } diff --git a/packages/core/lib/src/runtime/resource_controller/documenter.dart b/packages/core/lib/src/runtime/resource_controller/documenter.dart index 28d37540c..2c9950c93 100644 --- a/packages/core/lib/src/runtime/resource_controller/documenter.dart +++ b/packages/core/lib/src/runtime/resource_controller/documenter.dart @@ -62,7 +62,7 @@ class ResourceControllerDocumenterImpl extends ResourceControllerDocumenter { } @override - List documentOperationParameters( + List documentOperationParameters( ResourceController rc, APIDocumentContext context, Operation? operation, @@ -85,7 +85,7 @@ class ResourceControllerDocumenterImpl extends ResourceControllerDocumenter { return _documentParameter(context, operation, param); }) - .where((p) => p != null) + .nonNulls .toList(); } @@ -153,12 +153,12 @@ class ResourceControllerDocumenterImpl extends ResourceControllerDocumenter { return opsForPath.fold({}, (prev, opObj) { final instanceMembers = reflect(rc).type.instanceMembers; - final Operation? metadata = + final Operation metadata = firstMetadataOfType(instanceMembers[Symbol(opObj.dartMethodName)]!); final operationDoc = APIOperation( opObj.dartMethodName, - rc.documentOperationResponses(context, metadata!), + rc.documentOperationResponses(context, metadata), summary: rc.documentOperationSummary(context, metadata), description: rc.documentOperationDescription(context, metadata), parameters: rc.documentOperationParameters(context, metadata), @@ -169,7 +169,7 @@ class ResourceControllerDocumenterImpl extends ResourceControllerDocumenter { if (opObj.scopes != null) { context.defer(() async { operationDoc.security?.forEach((sec) { - sec!.requirements!.forEach((name, operationScopes) { + sec.requirements!.forEach((name, operationScopes) { final secType = context.document.components!.securitySchemes[name]; if (secType?.type == APISecuritySchemeType.oauth2 || diff --git a/packages/core/lib/src/runtime/resource_controller_impl.dart b/packages/core/lib/src/runtime/resource_controller_impl.dart index e0ffef8a1..21b2b4bca 100644 --- a/packages/core/lib/src/runtime/resource_controller_impl.dart +++ b/packages/core/lib/src/runtime/resource_controller_impl.dart @@ -227,7 +227,7 @@ class ResourceControllerRuntimeImpl extends ResourceControllerRuntime { } decoder = (value) { return _convertParameterListWithMirror( - value as List?, + value as List, boundType, ); }; @@ -242,7 +242,7 @@ class ResourceControllerRuntimeImpl extends ResourceControllerRuntime { ); } decoder = (value) { - return _convertParameterWithMirror(value as String?, mirror.type); + return _convertParameterWithMirror(value as String, mirror.type); }; } break; @@ -258,7 +258,7 @@ class ResourceControllerRuntimeImpl extends ResourceControllerRuntime { } decoder = (value) { return _convertParameterListWithMirror( - value as List?, + value as List, mirror.type, ); }; @@ -365,17 +365,17 @@ void _enforceTypeCanBeParsedFromString( } dynamic _convertParameterListWithMirror( - List? parameterValues, + List parameterValues, TypeMirror typeMirror, ) { if (typeMirror.isSubtypeOf(reflectType(List))) { - final iterable = parameterValues!.map( + final iterable = parameterValues.map( (str) => _convertParameterWithMirror(str, typeMirror.typeArguments.first), ); return (typeMirror as ClassMirror).newInstance(#from, [iterable]).reflectee; } else { - if (parameterValues!.length > 1) { + if (parameterValues.length > 1) { throw ArgumentError("multiple values not expected"); } return _convertParameterWithMirror(parameterValues.first, typeMirror); @@ -383,7 +383,7 @@ dynamic _convertParameterListWithMirror( } dynamic _convertParameterWithMirror( - String? parameterValue, + String parameterValue, TypeMirror typeMirror, ) { if (typeMirror.isSubtypeOf(reflectType(bool))) { diff --git a/packages/core/pubspec.yaml b/packages/core/pubspec.yaml index 46b8dc0a8..c12cb8711 100644 --- a/packages/core/pubspec.yaml +++ b/packages/core/pubspec.yaml @@ -6,10 +6,10 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: - analyzer: ^6.4.1 + analyzer: ^6.5.0 args: ^2.4.2 collection: ^1.18.0 conduit_common: ^5.0.3 diff --git a/packages/core/test/auth/auth_controller_test.dart b/packages/core/test/auth/auth_controller_test.dart index 1b296cdf3..0cc385b76 100644 --- a/packages/core/test/auth/auth_controller_test.dart +++ b/packages/core/test/auth/auth_controller_test.dart @@ -10,7 +10,7 @@ import 'package:test/test.dart'; int port = 8887; void main() { HttpServer? server; - AuthServer? authenticationServer; + late AuthServer authenticationServer; Router? router; //////////// setUp(() async { @@ -188,7 +188,7 @@ void main() { group("Success Cases: authorization_code", () { test("Exchange valid code gets access token with refresh token", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.redirect", @@ -199,7 +199,7 @@ void main() { }); test("If code is scoped, token has same scope", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.scoped", @@ -327,7 +327,7 @@ void main() { group("code Failure Cases", () { test("code is invalid (not issued)", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.redirect", @@ -351,7 +351,7 @@ void main() { }); test("code is duplicated", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.redirect", @@ -379,7 +379,7 @@ void main() { }); test("code is from a different client", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.redirect", @@ -596,7 +596,7 @@ void main() { setUp(() async { client = Agent.onPort(port); - refreshTokenString = (await authenticationServer!.authenticate( + refreshTokenString = (await authenticationServer.authenticate( user1["username"], user1["password"], "com.stablekernel.app1", @@ -675,7 +675,7 @@ void main() { setUp(() async { client = Agent.onPort(port); - code = (await authenticationServer!.authenticateForCode( + code = (await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.redirect", @@ -727,7 +727,7 @@ void main() { group("Scope failure cases", () { test("Try to add scope to code exchange is invalid_request", () async { - final code = await authenticationServer!.authenticateForCode( + final code = await authenticationServer.authenticateForCode( user1["username"], user1["password"], "com.stablekernel.scoped", diff --git a/packages/core/test/auth/auth_documentation_test.dart b/packages/core/test/auth/auth_documentation_test.dart index f6cfe72ae..4a671ebab 100644 --- a/packages/core/test/auth/auth_documentation_test.dart +++ b/packages/core/test/auth/auth_documentation_test.dart @@ -59,7 +59,7 @@ void main() { test("POST requires client authorization", () { expect(operations!["post"]!.security!.length, 1); expect( - operations!["post"]!.security!.first!.requirements, + operations!["post"]!.security!.first.requirements, {"oauth2-client-authentication": []}, ); }); @@ -179,7 +179,7 @@ void main() { final op = operations!["get"]!; expect(op.parameters!.length, 4); expect( - op.parameters!.every((p) => p!.location == APIParameterLocation.query), + op.parameters!.every((p) => p.location == APIParameterLocation.query), true, ); expect(op.parameterNamed("client_id")!.schema!.type, APIType.string); diff --git a/packages/core/test/auth/auth_redirect_controller_test.dart b/packages/core/test/auth/auth_redirect_controller_test.dart index 4e64d30b6..0d0a71b62 100644 --- a/packages/core/test/auth/auth_redirect_controller_test.dart +++ b/packages/core/test/auth/auth_redirect_controller_test.dart @@ -23,7 +23,7 @@ void main() { return req.post(); } - Future tokenResponse(Map form) { + Future tokenResponse(Map form) { final m = Map.from(form); m.addAll({"response_type": "token"}); @@ -46,8 +46,8 @@ void main() { }); setUp(() async { - (application.channel.authServer!.delegate as InMemoryAuthStorage).reset(); - (application.channel.authServer!.delegate as InMemoryAuthStorage) + (application.channel.authServer.delegate as InMemoryAuthStorage).reset(); + (application.channel.authServer.delegate as InMemoryAuthStorage) .createUsers(2); }); @@ -238,7 +238,7 @@ void main() { final redirectURI = Uri.parse(resp.headers["location"]!.first); final codeParam = redirectURI.queryParameters["code"]; - final token = await application.channel.authServer! + final token = await application.channel.authServer .exchange(codeParam, "com.stablekernel.scoped", "kilimanjaro"); expect(token.scopes!.length, 1); expect(token.scopes!.first.isExactly("user"), true); @@ -261,7 +261,7 @@ void main() { final redirectURI = Uri.parse(resp.headers["location"]!.first); final codeParam = redirectURI.queryParameters["code"]; - final token = await application.channel.authServer! + final token = await application.channel.authServer .exchange(codeParam, "com.stablekernel.scoped", "kilimanjaro"); expect(token.scopes!.length, 2); expect(token.scopes!.any((s) => s.isExactly("user")), true); @@ -550,7 +550,7 @@ void main() { test("password is incorrect yields 302 with error", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.public.redirect", - "username": user1["username"], + "username": user1["username"]!, "password": "nonsense", "state": "a" }); @@ -565,7 +565,7 @@ void main() { test("password is empty returns 302 with error", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.public.redirect", - "username": user1["username"], + "username": user1["username"]!, "password": "", "state": "a" }); @@ -580,7 +580,7 @@ void main() { test("password is missing returns 302 with error", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.public.redirect", - "username": user1["username"], + "username": user1["username"]!, "state": "a" }); expectTokenErrorRedirect( @@ -663,8 +663,8 @@ void main() { group("client_id failures", () { test("Omit client_id returns 400", () async { final resp = await tokenResponse({ - "username": user1["username"], - "password": user1["password"], + "username": user1["username"]!, + "password": user1["password"]!, "state": "a" }); expect(resp, hasStatus(400)); @@ -673,8 +673,8 @@ void main() { test("client_id does not exist for app returns 400", () async { final resp = await tokenResponse({ "client_id": "abc", - "username": user1["username"], - "password": user1["password"], + "username": user1["username"]!, + "password": user1["password"]!, "state": "a" }); expect(resp, hasStatus(400)); @@ -683,8 +683,8 @@ void main() { test("client_id that does not have redirectURI returns 400", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.app1", - "username": user1["username"], - "password": user1["password"], + "username": user1["username"]!, + "password": user1["password"]!, "state": "a" }); expect(resp, hasStatus(400)); @@ -716,8 +716,8 @@ void main() { test("client_id is empty returns 400", () async { final resp = await tokenResponse({ "client_id": "", - "username": user1["username"], - "password": user1["password"], + "username": user1["username"]!, + "password": user1["password"]!, "state": "a" }); expect(resp, hasStatus(400)); @@ -806,7 +806,7 @@ void main() { test("Omit state is error", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.public.redirect", - "username": user1["username"], + "username": user1["username"]!, "password": InMemoryAuthStorage.defaultPassword }); @@ -835,7 +835,7 @@ void main() { test("Failed password + state still returns state in error", () async { final resp = await tokenResponse({ "client_id": "com.stablekernel.public.redirect", - "username": user1["username"], + "username": user1["username"]!, "password": "nonsense", "state": "xyz" }); @@ -887,7 +887,7 @@ void main() { class TestChannel extends ApplicationChannel implements AuthRedirectControllerDelegate { - AuthServer? authServer; + late final AuthServer authServer; BadAuthRedirectDelegate badDelegate = BadAuthRedirectDelegate(); @override @@ -919,11 +919,11 @@ class TestChannel extends ApplicationChannel } @override - Future render( + Future render( AuthRedirectController forController, Uri requestUri, String? responseType, - String? clientID, + String clientID, String? state, String? scope, ) async { @@ -943,7 +943,7 @@ class BadAuthRedirectDelegate implements AuthRedirectControllerDelegate { AuthRedirectController forController, Uri requestUri, String? responseType, - String? clientID, + String clientID, String? state, String? scope, ) async { diff --git a/packages/core/test/auth/authenticate_test.dart b/packages/core/test/auth/authenticate_test.dart index e508a949d..245620124 100644 --- a/packages/core/test/auth/authenticate_test.dart +++ b/packages/core/test/auth/authenticate_test.dart @@ -54,9 +54,9 @@ void main() { expect(await auth.getClient("com.stablekernel.app1"), isNull); }); - test("Cannot revoke null client", () async { + test("Cannot revoke empty client", () async { try { - await auth.removeClient(null); + await auth.removeClient(''); expect(true, false); // ignore: empty_catches } on AuthServerException {} @@ -433,7 +433,7 @@ void main() { test("Cannot refresh token if client id is missing", () async { try { - await auth.refresh(initialToken.refreshToken, null, "kilimanjaro"); + await auth.refresh(initialToken.refreshToken, '', "kilimanjaro"); expect(true, false); // ignore: empty_catches } on AuthServerException {} @@ -584,19 +584,20 @@ void main() { } }); - test("Generate auth code with no client id", () async { - try { - await auth.authenticateForCode( - createdUser!.username, - InMemoryAuthStorage.defaultPassword, - null, - ); - expect(true, false); - } on AuthServerException catch (e) { - expect(e.client, isNull); - expect(e.reason, AuthRequestError.invalidClient); - } - }); + // Note: No longer supporting nullable client id + // test("Generate auth code with no client id", () async { + // try { + // await auth.authenticateForCode( + // createdUser!.username, + // InMemoryAuthStorage.defaultPassword, + // null, + // ); + // expect(true, false); + // } on AuthServerException catch (e) { + // expect(e.client, isNull); + // expect(e.reason, AuthRequestError.invalidClient); + // } + // }); }); group("Exchanging auth code", () { @@ -734,7 +735,7 @@ void main() { test("Null client ID fails", () async { try { - await auth.exchange(code.code, null, "mckinley"); + await auth.exchange(code.code, '', "mckinley"); expect(true, false); // ignore: empty_catches diff --git a/packages/core/test/db/data_model_test.dart b/packages/core/test/db/data_model_test.dart index 83c7f9b77..3611539e6 100644 --- a/packages/core/test/db/data_model_test.dart +++ b/packages/core/test/db/data_model_test.dart @@ -59,25 +59,25 @@ void main() { expect(entity.properties[key] == attr, true); }); - entity.relationships!.forEach((key, attr) { + entity.relationships.forEach((key, attr) { expect(entity.properties[key] == attr, true); }); } }); test("Relationships aren't attributes and vice versa", () { - expect(dataModel.entityForType(User).relationships!["id"], isNull); + expect(dataModel.entityForType(User).relationships["id"], isNull); expect(dataModel.entityForType(User).attributes["id"], isNotNull); expect(dataModel.entityForType(User).attributes["manager"], isNull); expect( - dataModel.entityForType(User).relationships!["manager"], + dataModel.entityForType(User).relationships["manager"], isNotNull, ); expect(dataModel.entityForType(Manager).attributes["worker"], isNull); expect( - dataModel.entityForType(Manager).relationships!["worker"], + dataModel.entityForType(Manager).relationships["worker"], isNotNull, ); }); @@ -138,12 +138,12 @@ void main() { test("Relationships have appropriate values set", () { var entity = dataModel.entityForType(Item); - var relDesc = entity.relationships!["user"]!; + var relDesc = entity.relationships["user"]!; expect(relDesc.isNullable, false); expect(relDesc.inverseKey, "items"); expect( relDesc.inverse == - dataModel.entityForType(User).relationships![relDesc.inverseKey], + dataModel.entityForType(User).relationships[relDesc.inverseKey], true, ); expect(relDesc.deleteRule, DeleteRule.cascade); @@ -151,12 +151,12 @@ void main() { expect(relDesc.relationshipType, ManagedRelationshipType.belongsTo); entity = dataModel.entityForType(Manager); - relDesc = entity.relationships!["worker"]!; + relDesc = entity.relationships["worker"]!; expect(relDesc.isNullable, true); expect(relDesc.inverseKey, "manager"); expect( relDesc.inverse == - dataModel.entityForType(User).relationships![relDesc.inverseKey], + dataModel.entityForType(User).relationships[relDesc.inverseKey], true, ); expect(relDesc.deleteRule, DeleteRule.nullify); @@ -164,11 +164,11 @@ void main() { expect(relDesc.relationshipType, ManagedRelationshipType.belongsTo); entity = dataModel.entityForType(User); - relDesc = entity.relationships!["manager"]!; + relDesc = entity.relationships["manager"]!; expect(relDesc.inverseKey, "worker"); expect( relDesc.inverse == - dataModel.entityForType(Manager).relationships![relDesc.inverseKey], + dataModel.entityForType(Manager).relationships[relDesc.inverseKey], true, ); expect( @@ -178,7 +178,7 @@ void main() { expect(relDesc.relationshipType, ManagedRelationshipType.hasOne); expect( - entity.relationships!["items"]!.relationshipType, + entity.relationships["items"]!.relationshipType, ManagedRelationshipType.hasMany, ); }); @@ -219,66 +219,66 @@ void main() { expect( dm .entityForType(CyclicLeft) - .relationships!["leftRef"]! + .relationships["leftRef"]! .destinationEntity .name, "CyclicRight", ); expect( - dm.entityForType(CyclicLeft).relationships!["leftRef"]!.inverse!.name, + dm.entityForType(CyclicLeft).relationships["leftRef"]!.inverse!.name, "from", ); expect( - dm.entityForType(CyclicLeft).relationships!["leftRef"]!.isBelongsTo, + dm.entityForType(CyclicLeft).relationships["leftRef"]!.isBelongsTo, true, ); expect( dm .entityForType(CyclicLeft) - .relationships!["from"]! + .relationships["from"]! .destinationEntity .name, "CyclicRight", ); expect( - dm.entityForType(CyclicLeft).relationships!["from"]!.inverse!.name, + dm.entityForType(CyclicLeft).relationships["from"]!.inverse!.name, "rightRef", ); expect( - dm.entityForType(CyclicLeft).relationships!["from"]!.isBelongsTo, + dm.entityForType(CyclicLeft).relationships["from"]!.isBelongsTo, false, ); expect( dm .entityForType(CyclicRight) - .relationships!["rightRef"]! + .relationships["rightRef"]! .destinationEntity .name, "CyclicLeft", ); expect( - dm.entityForType(CyclicRight).relationships!["rightRef"]!.inverse!.name, + dm.entityForType(CyclicRight).relationships["rightRef"]!.inverse!.name, "from", ); expect( - dm.entityForType(CyclicRight).relationships!["rightRef"]!.isBelongsTo, + dm.entityForType(CyclicRight).relationships["rightRef"]!.isBelongsTo, true, ); expect( dm .entityForType(CyclicRight) - .relationships!["from"]! + .relationships["from"]! .destinationEntity .name, "CyclicLeft", ); expect( - dm.entityForType(CyclicRight).relationships!["from"]!.inverse!.name, + dm.entityForType(CyclicRight).relationships["from"]!.inverse!.name, "leftRef", ); expect( - dm.entityForType(CyclicRight).relationships!["from"]!.isBelongsTo, + dm.entityForType(CyclicRight).relationships["from"]!.isBelongsTo, false, ); }); @@ -288,7 +288,7 @@ void main() { expect( dm .entityForType(SelfReferential) - .relationships!["parent"]! + .relationships["parent"]! .destinationEntity .name, "SelfReferential", @@ -296,33 +296,29 @@ void main() { expect( dm .entityForType(SelfReferential) - .relationships!["parent"]! + .relationships["parent"]! .inverse! .name, "child", ); expect( - dm.entityForType(SelfReferential).relationships!["parent"]!.isBelongsTo, + dm.entityForType(SelfReferential).relationships["parent"]!.isBelongsTo, true, ); expect( dm .entityForType(SelfReferential) - .relationships!["child"]! + .relationships["child"]! .destinationEntity .name, "SelfReferential", ); expect( - dm - .entityForType(SelfReferential) - .relationships!["child"]! - .inverse! - .name, + dm.entityForType(SelfReferential).relationships["child"]!.inverse!.name, "parent", ); expect( - dm.entityForType(SelfReferential).relationships!["child"]!.isBelongsTo, + dm.entityForType(SelfReferential).relationships["child"]!.isBelongsTo, false, ); }); @@ -338,7 +334,7 @@ void main() { final isManyOf = model .entityForType(DoubleRelationshipForeignKeyModel) - .relationships!["isManyOf"]!; + .relationships["isManyOf"]!; expect(isManyOf.inverse!.name, "hasManyOf"); expect( isManyOf.destinationEntity.tableName, @@ -347,7 +343,7 @@ void main() { final isOneOf = model .entityForType(DoubleRelationshipForeignKeyModel) - .relationships!["isOneOf"]!; + .relationships["isOneOf"]!; expect(isOneOf.inverse!.name, "hasOneOf"); expect( isOneOf.destinationEntity.tableName, @@ -366,7 +362,7 @@ void main() { final partial = model .entityForType(DoubleRelationshipForeignKeyModel) - .relationships!["partial"]!; + .relationships["partial"]!; expect( partial.destinationEntity.tableName, model.entityForType(SomeOtherRelationshipModel).tableName, @@ -391,17 +387,17 @@ void main() { expect(totalEntity.attributes["field"]!.isIndexed, true); expect( totalEntity - .relationships!["hasManyRelationship"]!.destinationEntity.tableName, + .relationships["hasManyRelationship"]!.destinationEntity.tableName, referenceEntity.tableName, ); expect( - totalEntity.relationships!["hasManyRelationship"]!.relationshipType, + totalEntity.relationships["hasManyRelationship"]!.relationshipType, ManagedRelationshipType.hasMany, ); expect( referenceEntity - .relationships!["foreignKeyColumn"]!.destinationEntity.tableName, + .relationships["foreignKeyColumn"]!.destinationEntity.tableName, totalEntity.tableName, ); }); @@ -470,12 +466,12 @@ void main() { final joinEntity = model.entityForType(JoinMany); expect( - joinEntity.relationships!["left"]!.destinationEntity.instanceType == + joinEntity.relationships["left"]!.destinationEntity.instanceType == LeftMany, true, ); expect( - joinEntity.relationships!["right"]!.destinationEntity.instanceType == + joinEntity.relationships["right"]!.destinationEntity.instanceType == RightMany, true, ); diff --git a/packages/core/test/db/model_controller_test.dart b/packages/core/test/db/model_controller_test.dart index 22a3ee0e3..e7d8100dd 100644 --- a/packages/core/test/db/model_controller_test.dart +++ b/packages/core/test/db/model_controller_test.dart @@ -87,7 +87,7 @@ class TestModelController extends QueryController { statusCode = 400; } - if (query!.values.backing.contents!.isNotEmpty) { + if (query!.values.backing.contents.isNotEmpty) { statusCode = 400; } @@ -111,7 +111,7 @@ class TestModelController extends QueryController { statusCode = 400; } - if (query!.values.backing.contents!.isNotEmpty) { + if (query!.values.backing.contents.isNotEmpty) { statusCode = 400; } diff --git a/packages/core/test/db/predicate_test.dart b/packages/core/test/db/predicate_test.dart index dff7a1a79..b97d63b99 100644 --- a/packages/core/test/db/predicate_test.dart +++ b/packages/core/test/db/predicate_test.dart @@ -25,10 +25,11 @@ void main() { expect(QueryPredicate.and([]).parameters, {}); }); - test("If null, return empty predicate", () { - expect(QueryPredicate.and(null).format, ""); - expect(QueryPredicate.and(null).parameters, {}); - }); + // No Longer allowing null values + // test("If null, return empty predicate", () { + // expect(QueryPredicate.and(null).format, ""); + // expect(QueryPredicate.and(null).parameters, {}); + // }); test("If only one element in list, return that element", () { final valid = QueryPredicate("x=@a", {"a": 0}); @@ -44,12 +45,13 @@ void main() { expect(p.parameters, valid.parameters); }); - test("If and'ing null predicate, ignore it", () { - final valid = QueryPredicate("x=@a", {"a": 0}); - final p = QueryPredicate.and([valid, null]); - expect(p.format, valid.format); - expect(p.parameters, valid.parameters); - }); + // Not allowing null values + // test("If and'ing null predicate, ignore it", () { + // final valid = QueryPredicate("x=@a", {"a": 0}); + // final p = QueryPredicate.and([valid, null]); + // expect(p.format, valid.format); + // expect(p.parameters, valid.parameters); + // }); test("And'ing predicate with no parameters", () { final valid = QueryPredicate("x=y"); diff --git a/packages/core/test/db/query_test.dart b/packages/core/test/db/query_test.dart index 8f89e570d..90194e699 100644 --- a/packages/core/test/db/query_test.dart +++ b/packages/core/test/db/query_test.dart @@ -129,8 +129,8 @@ void main() { ..id = 1 ..name = "bob"; - expect(q.values.backing.contents!.keys, ["parent"]); - expect(q.values.backing.contents!["parent"].backing.contents, {"id": 1}); + expect(q.values.backing.contents.keys, ["parent"]); + expect(q.values.backing.contents["parent"].backing.contents, {"id": 1}); try { q.values.parent.name = "bob"; @@ -176,8 +176,8 @@ void main() { () { final q = Query(ctx); q.values = Child()..parent = (Root()..name = "fred"); - expect(q.values.backing.contents!.keys, ["parent"]); - expect(q.values.backing.contents!["parent"].backing.contents, {}); + expect(q.values.backing.contents.keys, ["parent"]); + expect(q.values.backing.contents["parent"].backing.contents, {}); }); test( @@ -201,8 +201,8 @@ void main() { ..name = "fred") ..name = "fred"; - expect(q.values.backing.contents!.keys, ["parent", "name"]); - expect(q.values.backing.contents!["parent"].backing.contents, {"id": 1}); + expect(q.values.backing.contents.keys, ["parent", "name"]); + expect(q.values.backing.contents["parent"].backing.contents, {"id": 1}); }); }); } diff --git a/packages/core/test/db/schema_builder_test.dart b/packages/core/test/db/schema_builder_test.dart index be681568b..4ff6cfa75 100644 --- a/packages/core/test/db/schema_builder_test.dart +++ b/packages/core/test/db/schema_builder_test.dart @@ -20,7 +20,7 @@ void main() { test("Adding a table", () { builder.createTable(SchemaTable("foobar", [])); expect( - builder.schema!.tables.firstWhere((st) => st.name == "foobar"), + builder.schema.tables.firstWhere((st) => st.name == "foobar"), isNotNull, ); @@ -49,15 +49,14 @@ void main() { builder.deleteTable("_DefaultItem"); expect( - builder.schema!.tables + builder.schema.tables .firstWhereOrNull((st) => st.name == "_DefaultItem"), isNull, ); builder.deleteTable("_cONTAINER"); expect( - builder.schema!.tables - .firstWhereOrNull((st) => st.name == "_Container"), + builder.schema.tables.firstWhereOrNull((st) => st.name == "_Container"), isNull, ); }); @@ -68,7 +67,7 @@ void main() { }); expect( - builder.schema!.tableForName("_ExtensiveModel")!.uniqueColumnSet, + builder.schema.tableForName("_ExtensiveModel")!.uniqueColumnSet, ["indexedValue", "startDate"], ); }); @@ -82,7 +81,7 @@ void main() { }); expect( - builder.schema!.tableForName("_ExtensiveModel")!.uniqueColumnSet, + builder.schema.tableForName("_ExtensiveModel")!.uniqueColumnSet, isNull, ); }); @@ -96,7 +95,7 @@ void main() { }); expect( - builder.schema!.tableForName("_ExtensiveModel")!.uniqueColumnSet, + builder.schema.tableForName("_ExtensiveModel")!.uniqueColumnSet, ["autoincrementValue", "startDate"], ); @@ -105,7 +104,7 @@ void main() { }); expect( - builder.schema!.tableForName("_ExtensiveModel")!.uniqueColumnSet, + builder.schema.tableForName("_ExtensiveModel")!.uniqueColumnSet, ["autoincrementValue", "indexedValue", "startDate"], ); }); @@ -120,14 +119,14 @@ void main() { SchemaColumn("col2", ManagedPropertyType.integer), ); expect( - builder.schema! + builder.schema .tableForName("_DefaultItem")! .columns .firstWhere((sc) => sc.name == "col1"), isNotNull, ); expect( - builder.schema! + builder.schema .tableForName("_DefaultItem")! .columns .firstWhere((sc) => sc.name == "col2"), @@ -158,7 +157,7 @@ void main() { test("Deleting column", () { builder.deleteColumn("_DefaultItem", "id"); expect( - builder.schema! + builder.schema .tableForName("_DefaultItem")! .columns .firstWhereOrNull((sc) => sc.name == "id"), @@ -253,35 +252,35 @@ void main() { ); expect( - builder.schema! + builder.schema .tableForName("_LoadedItem")! .columnForName("someIndexedThing")! .isIndexed, false, ); expect( - builder.schema! + builder.schema .tableForName("_LoadedItem")! .columnForName("someIndexedThing")! .isNullable, true, ); expect( - builder.schema! + builder.schema .tableForName("_LoadedItem")! .columnForName("someIndexedThing")! .isUnique, true, ); expect( - builder.schema! + builder.schema .tableForName("_LoadedItem")! .columnForName("someIndexedThing")! .defaultValue, "'bar'", ); expect( - builder.schema! + builder.schema .tableForName("_LoadedItem")! .columnForName("someIndexedThing")! .deleteRule, diff --git a/packages/core/test/db/validate_value_test.dart b/packages/core/test/db/validate_value_test.dart index 293fbded4..5b6d32abb 100644 --- a/packages/core/test/db/validate_value_test.dart +++ b/packages/core/test/db/validate_value_test.dart @@ -298,7 +298,7 @@ void main() { }); test("Implicitly added to enum types", () { - final e = EnumObject()..backing.contents!["enumValues"] = "foobar"; + final e = EnumObject()..backing.contents["enumValues"] = "foobar"; expect(e.validate().isValid, false); e.enumValues = EnumValues.abcd; expect(e.validate().isValid, true); diff --git a/packages/core/test/http/moc_openapi_test.dart b/packages/core/test/http/moc_openapi_test.dart index f8620b452..722e9009a 100644 --- a/packages/core/test/http/moc_openapi_test.dart +++ b/packages/core/test/http/moc_openapi_test.dart @@ -108,7 +108,7 @@ void main() { expect(op.responses!.length, 2); expect(op.parameters!.length, 6); - expect(op.parameters!.every((p) => p!.isRequired == false), true); + expect(op.parameters!.every((p) => p.isRequired == false), true); expect(op.responses!["400"], isNotNull); expect( diff --git a/packages/core/test/http/recycling_test.dart b/packages/core/test/http/recycling_test.dart index 56d56d5cf..c82774f45 100644 --- a/packages/core/test/http/recycling_test.dart +++ b/packages/core/test/http/recycling_test.dart @@ -127,7 +127,7 @@ void main() { "A recycled controller always sends unhandled requests to the next linked controller", () async { server.root - .link(() => MiddlewareRecyclable())! + .link(() => MiddlewareRecyclable()) .link(() => DefaultController()); server.root.didAddToChannel(); @@ -176,7 +176,7 @@ void main() { "A recycled controller sends unhandled request to the next linked recyclable", () async { server.root - .link(() => MiddlewareRecyclable())! + .link(() => MiddlewareRecyclable()) .link(() => DefaultRecyclable()); server.root.didAddToChannel(); diff --git a/packages/core/test/http/resource_controller_scope_test.dart b/packages/core/test/http/resource_controller_scope_test.dart index 673880285..d15950e77 100644 --- a/packages/core/test/http/resource_controller_scope_test.dart +++ b/packages/core/test/http/resource_controller_scope_test.dart @@ -101,7 +101,7 @@ void main() { } class Channel extends ApplicationChannel { - AuthServer? authServer; + late AuthServer authServer; @override Controller get entryPoint { diff --git a/packages/core/test/http/websocket_test.dart b/packages/core/test/http/websocket_test.dart index 1b109c647..635845c09 100644 --- a/packages/core/test/http/websocket_test.dart +++ b/packages/core/test/http/websocket_test.dart @@ -1,3 +1,5 @@ +// ignore_for_file: null_argument_to_non_null_type + @Timeout(Duration(seconds: 120)) import 'dart:async'; import 'dart:convert'; @@ -159,7 +161,7 @@ class TestController extends ResourceController { } @Operation.get() - Future testMethod() { + Future testMethod() { _stopwatch.start(); final httpRequest = request!.raw; WebSocketTransformer.upgrade(httpRequest).then(_processConnection); @@ -185,7 +187,7 @@ class ChatController extends ResourceController { } @Operation.get() - Future newChat(@Bind.query('user') String user) async { + Future newChat(@Bind.query('user') String user) async { final httpRequest = request!.raw; _socket[user] = await WebSocketTransformer.upgrade(httpRequest); _socket[user]!.listen((event) => handleEvent(event as String, user)); diff --git a/packages/core/test/managed_auth/managed_auth_role_storage_test.dart b/packages/core/test/managed_auth/managed_auth_role_storage_test.dart index 454e5b4fe..e291e2d72 100644 --- a/packages/core/test/managed_auth/managed_auth_role_storage_test.dart +++ b/packages/core/test/managed_auth/managed_auth_role_storage_test.dart @@ -10,7 +10,7 @@ import '../not_tests/postgres_test_config.dart'; // have scope rules. void main() { RoleBasedAuthStorage storage; - ManagedContext? context; + late ManagedContext context; late AuthServer auth; late List createdUsers; @@ -44,15 +44,14 @@ void main() { ..redirectURI = ac.redirectURI, ) .map((mc) { - final q = Query(context!)..values = mc; + final q = Query(context)..values = mc; return q.insert(); }), ); }); tearDownAll(() async { - await context?.close(); - context = null; + await context.close(); }); group("Resource owner", () { @@ -358,7 +357,7 @@ class RoleBasedAuthStorage extends ManagedAuthDelegate { @override Future getResourceOwner(AuthServer server, String username) { - final query = Query(context!) + final query = Query(context) ..where((o) => o.username).equalTo(username) ..returningProperties( (t) => [t.id, t.hashedPassword, t.salt, t.username, t.role], diff --git a/packages/core/test/managed_auth/managed_auth_storage_test.dart b/packages/core/test/managed_auth/managed_auth_storage_test.dart index abd5e332d..cd34ed9ea 100644 --- a/packages/core/test/managed_auth/managed_auth_storage_test.dart +++ b/packages/core/test/managed_auth/managed_auth_storage_test.dart @@ -12,7 +12,7 @@ import '../not_tests/postgres_test_config.dart'; // to manage long-term storage/cleanup of tokens and related items. void main() { late ManagedAuthDelegate storage; - ManagedContext? context; + late ManagedContext context; setUp(() async { context = await PostgresTestConfig() @@ -55,7 +55,7 @@ void main() { ..redirectURI = ac.redirectURI, ) .map((mc) { - final q = Query(context!)..values = mc; + final q = Query(context)..values = mc; return q.insert(); }), ); @@ -64,8 +64,7 @@ void main() { }); tearDown(() async { - await context?.close(); - context = null; + await context.close(); }); group("Client behavior", () { @@ -88,18 +87,18 @@ void main() { test("Cannot revoke null client", () async { try { - await auth.removeClient(null); + await auth.removeClient(''); expect(true, false); // ignore: empty_catches } on AuthServerException {} - final q = Query(context!); + final q = Query(context); expect(await q.fetch(), hasLength(5)); }); test("Revoking unknown client has no impact", () async { await auth.removeClient("nonsense"); - final q = Query(context!); + final q = Query(context); expect(await q.fetch(), hasLength(5)); }); @@ -113,7 +112,7 @@ void main() { ); await auth.addClient(client); - final q = Query(context!) + final q = Query(context) ..where((o) => o.id).equalTo("pub-id"); final result0 = await q.fetchOne(); expect(result0, isNotNull); @@ -145,9 +144,9 @@ void main() { } }); - test("If client id is null, exception is thrown", () async { + test("If client id is empty, exception is thrown", () async { final client = generateAPICredentialPair( - null, + '', null, hashLength: auth.hashLength, hashRounds: auth.hashRounds, @@ -157,9 +156,7 @@ void main() { try { await auth.addClient(client); fail('unreachable'); - } on QueryException catch (e) { - expect(e.event, QueryExceptionEvent.input); - } + } on ArgumentError catch (_) {} }); test("If client has redirect uri and no secret, exception is thrown", @@ -185,7 +182,7 @@ void main() { )..allowedScopes = ["scope"].map((s) => AuthScope(s)).toList(); await auth.addClient(client); - final q = Query(context!) + final q = Query(context) ..where((o) => o.id).equalTo("confidential-id"); final result = (await q.fetchOne())!.asClient(); expect(result.id, "confidential-id"); @@ -559,7 +556,7 @@ void main() { } // Make sure we don't have duplicates in the db - final q = Query(context!); + final q = Query(context); expect(await q.fetch(), hasLength(1)); }); @@ -571,9 +568,9 @@ void main() { } on AuthServerException {} }); - test("Cannot refresh token that is null", () async { + test("Cannot refresh token that is empty", () async { try { - await auth.refresh(null, "com.stablekernel.app1", "kilimanjaro"); + await auth.refresh('', "com.stablekernel.app1", "kilimanjaro"); expect(true, false); // ignore: empty_catches } on AuthServerException {} @@ -589,7 +586,7 @@ void main() { test("Cannot refresh token if client id is missing", () async { try { - await auth.refresh(initialToken.refreshToken, null, "kilimanjaro"); + await auth.refresh(initialToken.refreshToken, '', "kilimanjaro"); expect(true, false); // ignore: empty_catches } on AuthServerException {} @@ -771,19 +768,20 @@ void main() { } }); - test("Generate auth code with no client id", () async { - try { - await auth.authenticateForCode( - createdUser.username, - User.defaultPassword, - null, - ); - expect(true, false); - } on AuthServerException catch (e) { - expect(e.client, isNull); - expect(e.reason, AuthRequestError.invalidClient); - } - }); + // Note: No longer supporting nullable client id + // test("Generate auth code with no client id", () async { + // try { + // await auth.authenticateForCode( + // createdUser.username, + // User.defaultPassword, + // null, + // ); + // expect(true, false); + // } on AuthServerException catch (e) { + // expect(e.client, isNull); + // expect(e.reason, AuthRequestError.invalidClient); + // } + // }); test("Code no longer available if owner authentcatable is 'revoked'", () async { @@ -886,7 +884,7 @@ void main() { // ignore: empty_catches } on AuthServerException {} - final q = Query(context!) + final q = Query(context) ..where((o) => o.code).equalTo(code.code); expect(await q.fetch(), isEmpty); }); @@ -915,7 +913,7 @@ void main() { } // Ensure that the associated auth code is also destroyed - final authCodeQuery = Query(context!); + final authCodeQuery = Query(context); expect(await authCodeQuery.fetch(), isEmpty); }); @@ -957,13 +955,13 @@ void main() { } // Ensure that the associated auth code is also destroyed - final authCodeQuery = Query(context!); + final authCodeQuery = Query(context); expect(await authCodeQuery.fetch(), isEmpty); }); - test("Null client ID fails", () async { + test("Empty client ID fails", () async { try { - await auth.exchange(code.code, null, "mckinley"); + await auth.exchange(code.code, '', "mckinley"); expect(true, false); // ignore: empty_catches @@ -1072,7 +1070,7 @@ void main() { expect(e.reason, AuthRequestError.invalidGrant); } - final tokenQuery = Query(context!); + final tokenQuery = Query(context); expect(await tokenQuery.fetch(), isEmpty); }); @@ -1143,7 +1141,7 @@ void main() { const TypeMatcher(), ); - final tokenQuery = Query(context!); + final tokenQuery = Query(context); expect(await tokenQuery.fetch(), hasLength(3)); }); @@ -1243,7 +1241,7 @@ void main() { expect(e.reason, AuthRequestError.invalidGrant); } - final tokenQuery = Query(context!); + final tokenQuery = Query(context); expect(await tokenQuery.fetch(), isEmpty); }); }); @@ -1272,11 +1270,11 @@ void main() { "mckinley", ); - final codeQuery = Query(context!) + final codeQuery = Query(context) ..where((o) => o.code).equalTo(exchangedCode.code); expect(await codeQuery.fetch(), hasLength(1)); - final tokenQuery = Query(context!) + final tokenQuery = Query(context) ..where((o) => o.accessToken).equalTo(exchangedToken.accessToken); await tokenQuery.delete(); @@ -1316,7 +1314,7 @@ void main() { } // Insert the 'race condition' code - final manualInsertQuery = Query(context!) + final manualInsertQuery = Query(context) ..values = manualCode; manualCode = await manualInsertQuery.insert(); @@ -1327,7 +1325,7 @@ void main() { User.defaultPassword, "com.stablekernel.redirect", ); - final codeQuery = Query(context!); + final codeQuery = Query(context); var codesInDB = (await codeQuery.fetch()).map((ac) => ac.code).toList(); // These codes are in chronological order @@ -1404,7 +1402,7 @@ void main() { } // Insert the 'race condition' token - final manualInsertQuery = Query(context!) + final manualInsertQuery = Query(context) ..values = manualToken; manualToken = await manualInsertQuery.insert(); @@ -1416,7 +1414,7 @@ void main() { "com.stablekernel.app1", "kilimanjaro", ); - final tokenQuery = Query(context!); + final tokenQuery = Query(context); var tokensInDB = (await tokenQuery.fetch()).map((ac) => ac.accessToken).toList(); @@ -1563,7 +1561,7 @@ void main() { ..redirectURI = ac.redirectURI, ) .map((mc) { - final q = Query(context!)..values = mc; + final q = Query(context)..values = mc; return q.insert(); }), ); @@ -1875,7 +1873,7 @@ void main() { requestedScopes: [AuthScope("user"), AuthScope("location:add")], ); - final q = Query(context!) + final q = Query(context) ..where((o) => o.id).equalTo("all.redirect") ..values.allowedScope = "user location:add.readonly"; await q.updateOne(); diff --git a/packages/core/test/not_tests/helpers.dart b/packages/core/test/not_tests/helpers.dart index 12ca1e32c..cb02fba57 100644 --- a/packages/core/test/not_tests/helpers.dart +++ b/packages/core/test/not_tests/helpers.dart @@ -71,7 +71,7 @@ class TestToken implements AuthToken, AuthCode { @override int? resourceOwnerIdentifier; @override - String? clientID; + late String clientID; @override String? code; @override @@ -114,7 +114,7 @@ class InMemoryAuthStorage extends AuthServerDelegate { static const String defaultPassword = "foobaraxegrind21%"; - Map? clients; + Map? clients; Map users = {}; List tokens = []; List? allowedScopes; @@ -197,7 +197,7 @@ class InMemoryAuthStorage extends AuthServerDelegate { } @override - FutureOr? getToken( + FutureOr getToken( AuthServer server, { String? byAccessToken, String? byRefreshToken, @@ -331,7 +331,7 @@ class DefaultPersistentStore extends PersistentStore { @override Future executeQuery( String formatString, - Map values, + Map values, int timeoutInSeconds, { PersistentStoreQueryReturnType? returnType, }) async => @@ -341,7 +341,7 @@ class DefaultPersistentStore extends PersistentStore { Future close() async {} @override - Future transaction( + Future transaction( ManagedContext transactionContext, Future Function(ManagedContext transaction) transactionBlock, ) async => @@ -423,12 +423,12 @@ class DefaultPersistentStore extends PersistentStore { Future get schemaVersion async => 0; @override - Future upgrade( + Future upgrade( Schema fromSchema, List withMigrations, { bool temporary = false, }) async { - Schema? out = fromSchema; + Schema out = fromSchema; for (final migration in withMigrations) { migration.database = SchemaBuilder(this, out); await migration.upgrade(); diff --git a/packages/core/test/openapi/document_auth_test.dart b/packages/core/test/openapi/document_auth_test.dart index ed826947b..70734afcb 100644 --- a/packages/core/test/openapi/document_auth_test.dart +++ b/packages/core/test/openapi/document_auth_test.dart @@ -37,12 +37,12 @@ void main() { expect(noVarPath.operations.length, 2); expect(noVarPath.operations["get"]!.security!.length, 1); expect( - noVarPath.operations["get"]!.security!.first!.requirements, + noVarPath.operations["get"]!.security!.first.requirements, {"oauth2-client-authentication": []}, ); expect(noVarPath.operations["post"]!.security!.length, 1); expect( - noVarPath.operations["post"]!.security!.first!.requirements, + noVarPath.operations["post"]!.security!.first.requirements, {"oauth2-client-authentication": []}, ); @@ -50,7 +50,7 @@ void main() { expect(varPath.operations.length, 1); expect(varPath.operations["get"]!.security!.length, 1); expect( - varPath.operations["get"]!.security!.first!.requirements, + varPath.operations["get"]!.security!.first.requirements, {"oauth2-client-authentication": []}, ); }); @@ -61,12 +61,12 @@ void main() { expect(noVarPath.operations.length, 2); expect(noVarPath.operations["get"]!.security!.length, 1); expect( - noVarPath.operations["get"]!.security!.first!.requirements, + noVarPath.operations["get"]!.security!.first.requirements, {"oauth2": []}, ); expect(noVarPath.operations["post"]!.security!.length, 1); expect( - noVarPath.operations["post"]!.security!.first!.requirements, + noVarPath.operations["post"]!.security!.first.requirements, {"oauth2": []}, ); }); @@ -77,11 +77,11 @@ void main() { final noVarPath = doc.paths!["/bearer-scope"]!; expect(noVarPath.operations.length, 2); expect(noVarPath.operations["get"]!.security!.length, 1); - expect(noVarPath.operations["get"]!.security!.first!.requirements, { + expect(noVarPath.operations["get"]!.security!.first.requirements, { "oauth2": ["scope"] }); expect(noVarPath.operations["post"]!.security!.length, 1); - expect(noVarPath.operations["post"]!.security!.first!.requirements, { + expect(noVarPath.operations["post"]!.security!.first.requirements, { "oauth2": ["scope"] }); }); @@ -266,7 +266,7 @@ void main() { } class TestChannel extends ApplicationChannel { - AuthServer? authServer; + late final AuthServer authServer; @override Future prepare() async { @@ -355,7 +355,7 @@ class DocumentedController extends Controller { } class AuthControllerOnlyChannel extends ApplicationChannel { - AuthServer? authServer; + late AuthServer authServer; @override Future prepare() async { @@ -371,7 +371,7 @@ class AuthControllerOnlyChannel extends ApplicationChannel { } class ScopedControllerChannel extends ApplicationChannel { - AuthServer? authServer; + late AuthServer authServer; @override Future prepare() async { diff --git a/packages/core/test/openapi/document_test.dart b/packages/core/test/openapi/document_test.dart index 7ff317e5f..432308ea0 100644 --- a/packages/core/test/openapi/document_test.dart +++ b/packages/core/test/openapi/document_test.dart @@ -294,13 +294,13 @@ void main() { final middlewareParam = op!.parameters! .where( (p) => - p!.referenceURI?.path == "/components/parameters/x-api-key", + p.referenceURI?.path == "/components/parameters/x-api-key", ) .toList(); expect(middlewareParam.length, 1); expect( - doc.components!.resolve(middlewareParam.first!)!.schema!.type, + doc.components!.resolve(middlewareParam.first)!.schema!.type, APIType.string, ); } diff --git a/packages/core/test/openapi/resource_controller_scope_test.dart b/packages/core/test/openapi/resource_controller_scope_test.dart index ddb4ee4dc..731cab630 100644 --- a/packages/core/test/openapi/resource_controller_scope_test.dart +++ b/packages/core/test/openapi/resource_controller_scope_test.dart @@ -23,12 +23,12 @@ void main() { 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["get"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["get"]!.security!.first .requirements!.length, 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["get"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["get"]!.security!.first .requirements!["oauth2"], ["level1"], ); @@ -38,12 +38,12 @@ void main() { 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["post"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["post"]!.security!.first .requirements!.length, 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["post"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["post"]!.security!.first .requirements!["oauth2"], ["level1", "level2"], ); @@ -53,12 +53,12 @@ void main() { 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["delete"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["delete"]!.security!.first .requirements!.length, 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["delete"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["delete"]!.security!.first .requirements!["oauth2"], ["level1", "level2"], ); @@ -68,12 +68,12 @@ void main() { 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["put"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["put"]!.security!.first .requirements!.length, 1, ); expect( - doc.paths!["/level1-authorizer"]!.operations["put"]!.security!.first! + doc.paths!["/level1-authorizer"]!.operations["put"]!.security!.first .requirements!["oauth2"], ["level1"], ); @@ -88,12 +88,12 @@ void main() { ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["get"]!.security! - .first!.requirements!.length, + .first.requirements!.length, 1, ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["get"]!.security! - .first!.requirements!["oauth2"], + .first.requirements!["oauth2"], ["level1:subscope"], ); @@ -104,12 +104,12 @@ void main() { ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["post"]!.security! - .first!.requirements!.length, + .first.requirements!.length, 1, ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["post"]!.security! - .first!.requirements!["oauth2"], + .first.requirements!["oauth2"], ["level1:subscope", "level2"], ); @@ -120,12 +120,12 @@ void main() { ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["put"]!.security! - .first!.requirements!.length, + .first.requirements!.length, 1, ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["put"]!.security! - .first!.requirements!["oauth2"], + .first.requirements!["oauth2"], ["level1"], ); @@ -136,12 +136,12 @@ void main() { ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["delete"]!.security! - .first!.requirements!.length, + .first.requirements!.length, 1, ); expect( doc.paths!["/level1-subscope-authorizer"]!.operations["delete"]!.security! - .first!.requirements!["oauth2"], + .first.requirements!["oauth2"], ["level1", "level2"], ); }); @@ -159,7 +159,7 @@ void main() { } class Channel extends ApplicationChannel { - AuthServer? authServer; + late AuthServer authServer; @override Controller get entryPoint { diff --git a/packages/fs_test_agent/lib/dart_project_agent.dart b/packages/fs_test_agent/lib/dart_project_agent.dart index ed2665d38..8ae807cee 100644 --- a/packages/fs_test_agent/lib/dart_project_agent.dart +++ b/packages/fs_test_agent/lib/dart_project_agent.dart @@ -121,7 +121,7 @@ description: desc version: 0.0.1 environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: ${_asYaml(deps, indent: 1)} diff --git a/packages/fs_test_agent/pubspec.yaml b/packages/fs_test_agent/pubspec.yaml index 8834bdb60..f3df833e5 100644 --- a/packages/fs_test_agent/pubspec.yaml +++ b/packages/fs_test_agent/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: path: ^1.9.0 diff --git a/packages/isolate_exec/lib/src/executor.dart b/packages/isolate_exec/lib/src/executor.dart index b08e287b7..cdb1fc5fc 100644 --- a/packages/isolate_exec/lib/src/executor.dart +++ b/packages/isolate_exec/lib/src/executor.dart @@ -75,6 +75,9 @@ class IsolateExecutor { automaticPackageResolution: packageConfigURI == null, ); return await completer.future; + } catch (e) { + print(e); + rethrow; } finally { onErrorPort.close(); controlPort.close(); diff --git a/packages/isolate_exec/pubspec.yaml b/packages/isolate_exec/pubspec.yaml index fad7c84a3..a0ecb19d4 100644 --- a/packages/isolate_exec/pubspec.yaml +++ b/packages/isolate_exec/pubspec.yaml @@ -6,10 +6,10 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: - analyzer: ^6.4.1 + analyzer: ^6.5.0 glob: ^2.1.2 path: ^1.9.0 diff --git a/packages/isolate_exec_test_packages/test_package/pubspec.yaml b/packages/isolate_exec_test_packages/test_package/pubspec.yaml index 9841c741d..a85cd89a9 100644 --- a/packages/isolate_exec_test_packages/test_package/pubspec.yaml +++ b/packages/isolate_exec_test_packages/test_package/pubspec.yaml @@ -4,4 +4,4 @@ description: test dependency publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" diff --git a/packages/open_api/lib/src/util/list_helper.dart b/packages/open_api/lib/src/util/list_helper.dart index 9a26a0b31..ceb058e94 100644 --- a/packages/open_api/lib/src/util/list_helper.dart +++ b/packages/open_api/lib/src/util/list_helper.dart @@ -5,5 +5,5 @@ List? removeNullsFromList(List? list) { if (list == null) return null; // remove nulls and convert to List - return List.from(list.where((c) => c != null)); + return list.nonNulls.toList(); } diff --git a/packages/open_api/lib/src/v3/operation.dart b/packages/open_api/lib/src/v3/operation.dart index 1513d43c5..4a653dccb 100644 --- a/packages/open_api/lib/src/v3/operation.dart +++ b/packages/open_api/lib/src/v3/operation.dart @@ -48,12 +48,12 @@ class APIOperation extends APIObject { /// A list of parameters that are applicable for this operation. /// /// If a parameter is already defined at the Path Item, the definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. - List? parameters; + List? parameters; /// A declaration of which security mechanisms can be used for this operation. /// /// The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. This definition overrides any declared top-level security. To remove a top-level security declaration, an empty array can be used. - List? security; + List? security; /// The request body applicable for this operation. /// @@ -82,7 +82,7 @@ class APIOperation extends APIObject { /// Returns the parameter named [name] or null if it doesn't exist. APIParameter? parameterNamed(String name) => - parameters?.firstWhere((p) => p?.name == name, orElse: () => null); + parameters?.firstWhere((p) => p.name == name); /// Adds [parameter] to [parameters]. /// @@ -142,14 +142,19 @@ class APIOperation extends APIObject { summary = object.decode("summary"); description = object.decode("description"); id = object.decode("operationId"); - parameters = object.decodeObjects("parameters", () => APIParameter.empty()); + parameters = object + .decodeObjects("parameters", () => APIParameter.empty()) + ?.nonNulls + .toList(); requestBody = object.decodeObject("requestBody", () => APIRequestBody.empty()); responses = object.decodeObjectMap("responses", () => APIResponse.empty()); callbacks = object.decodeObjectMap("callbacks", () => APICallback()); deprecated = object.decode("deprecated"); - security = - object.decodeObjects("security", () => APISecurityRequirement.empty()); + security = object + .decodeObjects("security", () => APISecurityRequirement.empty()) + ?.nonNulls + .toList(); servers = object.decodeObjects("servers", () => APIServerDescription.empty()); } diff --git a/packages/open_api/pubspec.yaml b/packages/open_api/pubspec.yaml index 38c7dafcd..7b397e2d8 100644 --- a/packages/open_api/pubspec.yaml +++ b/packages/open_api/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit_codable: ^5.0.3 diff --git a/packages/open_api/test/v3_test.dart b/packages/open_api/test/v3_test.dart index 12cab3b4a..e323efa22 100644 --- a/packages/open_api/test/v3_test.dart +++ b/packages/open_api/test/v3_test.dart @@ -169,25 +169,25 @@ void main() { expect(getOp.description, contains("10 most recent reversals")); expect(getOp.id, "GetTransfersTransferReversalsId"); expect(getParams!.length, 3); - expect(getParams[0]!.location, APIParameterLocation.query); + expect(getParams[0].location, APIParameterLocation.query); expect( - getParams[0]!.description, + getParams[0].description, "Specifies which fields in the response should be expanded.", ); - expect(getParams[0]!.name, "expand"); - expect(getParams[0]!.isRequired, false); - expect(getParams[0]!.schema!.type, APIType.array); - expect(getParams[0]!.schema!.items!.type, APIType.string); - - expect(getParams[1]!.location, APIParameterLocation.path); - expect(getParams[1]!.name, "id"); - expect(getParams[1]!.isRequired, true); - expect(getParams[1]!.schema!.type, APIType.string); - - expect(getParams[2]!.location, APIParameterLocation.path); - expect(getParams[2]!.name, "transfer"); - expect(getParams[2]!.isRequired, true); - expect(getParams[2]!.schema!.type, APIType.string); + expect(getParams[0].name, "expand"); + expect(getParams[0].isRequired, false); + expect(getParams[0].schema!.type, APIType.array); + expect(getParams[0].schema!.items!.type, APIType.string); + + expect(getParams[1].location, APIParameterLocation.path); + expect(getParams[1].name, "id"); + expect(getParams[1].isRequired, true); + expect(getParams[1].schema!.type, APIType.string); + + expect(getParams[2].location, APIParameterLocation.path); + expect(getParams[2].name, "transfer"); + expect(getParams[2].isRequired, true); + expect(getParams[2].schema!.type, APIType.string); expect(getResponses!.length, 2); expect(getResponses["200"]!.content!.length, 1); diff --git a/packages/password_hash/pubspec.yaml b/packages/password_hash/pubspec.yaml index f40d57606..1f4dd08ec 100644 --- a/packages/password_hash/pubspec.yaml +++ b/packages/password_hash/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: crypto: ^3.0.3 diff --git a/packages/postgresql/lib/src/builders/column.dart b/packages/postgresql/lib/src/builders/column.dart index 18e3b7805..2d6968b19 100644 --- a/packages/postgresql/lib/src/builders/column.dart +++ b/packages/postgresql/lib/src/builders/column.dart @@ -12,7 +12,7 @@ class ColumnBuilder extends Returnable { final entity = table.entity; // Ensure the primary key is always available and at 0th index. - int? primaryKeyIndex; + int primaryKeyIndex = -1; for (var i = 0; i < keys.length; i++) { final firstElement = keys[i].path.first; if (firstElement is ManagedAttributeDescription && @@ -22,7 +22,7 @@ class ColumnBuilder extends Returnable { } } - if (primaryKeyIndex == null) { + if (primaryKeyIndex == -1) { keys.insert(0, KeyPath(entity.primaryKeyAttribute)); } else if (primaryKeyIndex > 0) { keys.removeAt(primaryKeyIndex); diff --git a/packages/postgresql/lib/src/builders/expression.dart b/packages/postgresql/lib/src/builders/expression.dart index 74d963af5..770ff035d 100644 --- a/packages/postgresql/lib/src/builders/expression.dart +++ b/packages/postgresql/lib/src/builders/expression.dart @@ -12,7 +12,7 @@ class ColumnExpressionBuilder extends ColumnBuilder { this.prefix = "", }); - final String? prefix; + final String prefix; PredicateExpression? expression; String get defaultPrefix => "$prefix${table!.sqlTableReference}_"; diff --git a/packages/postgresql/lib/src/builders/sort.dart b/packages/postgresql/lib/src/builders/sort.dart index 1417fa370..588760c45 100644 --- a/packages/postgresql/lib/src/builders/sort.dart +++ b/packages/postgresql/lib/src/builders/sort.dart @@ -4,7 +4,7 @@ import 'column.dart'; import 'table.dart'; class ColumnSortBuilder extends ColumnBuilder { - ColumnSortBuilder(TableBuilder table, String? key, QuerySortOrder order) + ColumnSortBuilder(TableBuilder table, String key, QuerySortOrder order) : order = order == QuerySortOrder.ascending ? "ASC" : "DESC", super(table, table.entity.properties[key]); @@ -14,7 +14,7 @@ class ColumnSortBuilder extends ColumnBuilder { } class ColumnSortPredicateBuilder extends ColumnSortBuilder { - ColumnSortPredicateBuilder(super.table, String super.key, super.order) + ColumnSortPredicateBuilder(super.table, super.key, super.order) : _key = key; final String _key; diff --git a/packages/postgresql/lib/src/builders/table.dart b/packages/postgresql/lib/src/builders/table.dart index ff68a8bef..d0a0c8a3b 100644 --- a/packages/postgresql/lib/src/builders/table.dart +++ b/packages/postgresql/lib/src/builders/table.dart @@ -16,9 +16,8 @@ class TableBuilder implements Returnable { returning = ColumnBuilder.fromKeys(this, query.propertiesToFetch); columnSortBuilders = query.sortDescriptors - ?.map((s) => ColumnSortBuilder(this, s.key, s.order)) - .toList() ?? - []; + .map((s) => ColumnSortBuilder(this, s.key, s.order)) + .toList(); if (query.sortPredicate != null) { columnSortBuilders.add( ColumnSortPredicateBuilder( @@ -55,7 +54,7 @@ class TableBuilder implements Returnable { } } - query.subQueries?.forEach((relationshipDesc, subQuery) { + query.subQueries.forEach((relationshipDesc, subQuery) { addJoinTableBuilder( TableBuilder( subQuery as PostgresQuery, @@ -149,13 +148,11 @@ class TableBuilder implements Returnable { void finalize(Map variables) { final allExpressions = [ - _manualPredicate, + if (_manualPredicate != null) _manualPredicate, ...expressionBuilders.map((c) => c.predicate) ]; predicate = QueryPredicate.and(allExpressions); - if (predicate?.parameters != null) { - variables.addAll(predicate!.parameters); - } + variables.addAll(predicate!.parameters); returning.whereType().forEach((r) { r.finalize(variables); }); @@ -216,7 +213,7 @@ class TableBuilder implements Returnable { joinedTable, inversePrimaryKey, expression.expression, - prefix: tableAlias, + prefix: tableAlias!, ); expressionBuilders.add(expr); } else { @@ -224,7 +221,7 @@ class TableBuilder implements Returnable { joinedTable, lastElement, expression.expression, - prefix: tableAlias, + prefix: tableAlias!, ); expressionBuilders.add(expr); } @@ -275,7 +272,7 @@ class TableBuilder implements Returnable { Methods that return portions of a SQL statement for this object */ - String? get sqlTableName { + String get sqlTableName { if (tableAlias == null) { return entity.tableName; } @@ -283,7 +280,7 @@ class TableBuilder implements Returnable { return "${entity.tableName} $tableAlias"; } - String? get sqlTableReference => tableAlias ?? entity.tableName; + String get sqlTableReference => tableAlias ?? entity.tableName; String get sqlInnerSelect { final nestedJoins = @@ -320,8 +317,8 @@ class TableBuilder implements Returnable { return sqlInnerSelect; } - final totalJoinPredicate = - QueryPredicate.and([joiningPredicate, predicate]); + final totalJoinPredicate = QueryPredicate.and( + [joiningPredicate, if (predicate != null) predicate!]); final thisJoin = "LEFT OUTER JOIN $sqlTableName ON ${totalJoinPredicate.format}"; diff --git a/packages/postgresql/lib/src/postgresql_persistent_store.dart b/packages/postgresql/lib/src/postgresql_persistent_store.dart index d059011f6..78dfaa6a0 100644 --- a/packages/postgresql/lib/src/postgresql_persistent_store.dart +++ b/packages/postgresql/lib/src/postgresql_persistent_store.dart @@ -5,6 +5,20 @@ import 'postgresql_query.dart'; import 'postgresql_schema_generator.dart'; import 'package:postgres/postgres.dart'; +extension ToSslMode on String? { + SslMode toSslMode() { + switch (this) { + case "disable": + return SslMode.disable; + case "require": + return SslMode.require; + case "verifyFull": + return SslMode.verifyFull; + } + return SslMode.disable; + } +} + /// The database layer responsible for carrying out [Query]s against PostgreSQL databases. /// /// To interact with a PostgreSQL database, a [ManagedContext] must have an instance of this class. @@ -19,8 +33,9 @@ class PostgreSQLPersistentStore extends PersistentStore this.port, this.databaseName, { this.timeZone = "UTC", - bool useSSL = false, - }) : isSSLConnection = useSSL; + this.sslMode, + @Deprecated('Use sslMode instead') bool useSSL = false, + }) : isSSLConnection = useSSL || sslMode.toSslMode() != SslMode.disable; /// Same constructor as default constructor. /// @@ -32,17 +47,20 @@ class PostgreSQLPersistentStore extends PersistentStore this.port, this.databaseName, { this.timeZone = "UTC", - bool useSSL = false, - }) : isSSLConnection = useSSL; + this.sslMode, + @Deprecated('Use sslMode instead') bool useSSL = false, + }) : isSSLConnection = useSSL || sslMode.toSslMode() != SslMode.disable; PostgreSQLPersistentStore._from(PostgreSQLPersistentStore from) - : isSSLConnection = from.isSSLConnection, + : isSSLConnection = + from.isSSLConnection || from.sslMode.toSslMode() != SslMode.disable, username = from.username, password = from.password, host = from.host, port = from.port, databaseName = from.databaseName, - timeZone = from.timeZone; + timeZone = from.timeZone, + sslMode = from.sslMode; factory PostgreSQLPersistentStore._transactionProxy( PostgreSQLPersistentStore parent, @@ -75,6 +93,9 @@ class PostgreSQLPersistentStore extends PersistentStore /// Whether this connection is established over SSL. final bool isSSLConnection; + /// The SSL mode of the connection to the database. + final String? sslMode; + /// Whether or not the underlying database connection is open. /// /// Connections are automatically opened when a query is executed, so this property should not be used @@ -102,7 +123,7 @@ class PostgreSQLPersistentStore extends PersistentStore /// /// Use this property to execute raw queries on the underlying database connection. /// If running a transaction, this context is the transaction context. - Future get executionContext => getDatabaseConnection(); + Future get executionContext => getDatabaseConnection(); /// Retrieves a connection to the database this instance connects to. /// @@ -160,7 +181,7 @@ class PostgreSQLPersistentStore extends PersistentStore final now = DateTime.now().toUtc(); final dbConnection = await executionContext; try { - final rows = await dbConnection!.execute( + final rows = await dbConnection.execute( Sql.named(sql), parameters: substitutionValues, timeout: timeout, @@ -191,15 +212,14 @@ class PostgreSQLPersistentStore extends PersistentStore } @override - Future transaction( + Future transaction( ManagedContext transactionContext, - Future Function(ManagedContext transaction) transactionBlock, + Future Function(ManagedContext transaction) transactionBlock, ) async { final Connection dbConnection = await getDatabaseConnection(); - T? output; try { - await dbConnection.runTx((dbTransactionContext) async { + return await dbConnection.runTx((dbTransactionContext) async { transactionContext.persistentStore = PostgreSQLPersistentStore._transactionProxy( this, @@ -207,7 +227,7 @@ class PostgreSQLPersistentStore extends PersistentStore ); try { - output = await transactionBlock(transactionContext); + return await transactionBlock(transactionContext); } on Rollback { /// user triggered a manual rollback. /// TODO: there is currently no reliable way for a user to detect @@ -226,8 +246,6 @@ class PostgreSQLPersistentStore extends PersistentStore rethrow; } - - return output; } @override @@ -251,14 +269,14 @@ class PostgreSQLPersistentStore extends PersistentStore } @override - Future upgrade( - Schema? fromSchema, + Future upgrade( + Schema fromSchema, List withMigrations, { bool temporary = false, }) async { final Connection connection = await getDatabaseConnection(); - Schema? schema = fromSchema; + Schema schema = fromSchema; await connection.runTx((ctx) async { final transactionStore = @@ -323,7 +341,7 @@ class PostgreSQLPersistentStore extends PersistentStore final now = DateTime.now().toUtc(); try { final dbConnection = await executionContext; - final Result results = await dbConnection!.execute( + final Result results = await dbConnection.execute( Sql.named(formatString), parameters: values, timeout: Duration(seconds: timeoutInSeconds), @@ -410,7 +428,6 @@ class PostgreSQLPersistentStore extends PersistentStore Future _connect() { logger.info("PostgreSQL connecting, $username@$host:$port/$databaseName."); - return Connection.open( Endpoint( host: host!, @@ -421,7 +438,7 @@ class PostgreSQLPersistentStore extends PersistentStore ), settings: ConnectionSettings( timeZone: timeZone!, - sslMode: isSSLConnection ? SslMode.verifyFull : SslMode.disable, + sslMode: sslMode.toSslMode(), ignoreSuperfluousParameters: true, ), ); diff --git a/packages/postgresql/lib/src/postgresql_query.dart b/packages/postgresql/lib/src/postgresql_query.dart index cbede873f..a274e7938 100644 --- a/packages/postgresql/lib/src/postgresql_query.dart +++ b/packages/postgresql/lib/src/postgresql_query.dart @@ -59,7 +59,7 @@ class PostgresQuery extends Object final buffer = StringBuffer(); - final allColumns = {}; + final allColumns = {}; final builders = []; for (int i = 0; i < objects.length; i++) { @@ -195,12 +195,11 @@ class PostgresQuery extends Object if (pageDescriptor != null) { validatePageDescriptor(); - } - - if (builder.containsJoins && pageDescriptor != null) { - throw StateError( - "Invalid query. Cannot set both 'pageDescription' and use 'join' in query.", - ); + if (builder.containsJoins) { + throw StateError( + "Invalid query. Cannot set both 'pageDescription' and use 'join' in query.", + ); + } } return builder; @@ -234,17 +233,17 @@ class PostgresQuery extends Object } void validatePageDescriptor() { - final prop = entity.attributes[pageDescriptor!.propertyName]; + final pd = pageDescriptor!; + final prop = entity.attributes[pd.propertyName]; if (prop == null) { throw StateError( - "Invalid query page descriptor. Column '${pageDescriptor!.propertyName}' does not exist for table '${entity.tableName}'", + "Invalid query page descriptor. Column '${pd.propertyName}' does not exist for table '${entity.tableName}'", ); } - if (pageDescriptor!.boundingValue != null && - !prop.isAssignableWith(pageDescriptor!.boundingValue)) { + if (pd.boundingValue != null && !prop.isAssignableWith(pd.boundingValue)) { throw StateError( - "Invalid query page descriptor. Bounding value for column '${pageDescriptor!.propertyName}' has invalid type.", + "Invalid query page descriptor. Bounding value for column '${pd.propertyName}' has invalid type.", ); } } diff --git a/packages/postgresql/lib/src/postgresql_query_reduce.dart b/packages/postgresql/lib/src/postgresql_query_reduce.dart index ec6b68c45..d5924383b 100644 --- a/packages/postgresql/lib/src/postgresql_query_reduce.dart +++ b/packages/postgresql/lib/src/postgresql_query_reduce.dart @@ -6,13 +6,12 @@ import 'postgresql_persistent_store.dart'; import 'postgresql_query.dart'; import 'query_builder.dart'; -// ignore_for_file: constant_identifier_names enum _Reducer { - AVG, - COUNT, - MAX, - MIN, - SUM, + avg, + count, + max, + min, + sum, } class PostgresQueryReduce @@ -25,29 +24,29 @@ class PostgresQueryReduce @override Future average(num? Function(T object) selector) { return _execute( - _Reducer.AVG, + _Reducer.avg, query.entity.identifyAttribute(selector), ); } @override Future count() { - return _execute(_Reducer.COUNT); + return _execute(_Reducer.count); } @override Future maximum(U? Function(T object) selector) { - return _execute(_Reducer.MAX, query.entity.identifyAttribute(selector)); + return _execute(_Reducer.max, query.entity.identifyAttribute(selector)); } @override Future minimum(U? Function(T object) selector) { - return _execute(_Reducer.MIN, query.entity.identifyAttribute(selector)); + return _execute(_Reducer.min, query.entity.identifyAttribute(selector)); } @override Future sum(U? Function(T object) selector) { - return _execute(_Reducer.SUM, query.entity.identifyAttribute(selector)); + return _execute(_Reducer.sum, query.entity.identifyAttribute(selector)); } String _columnName(ManagedAttributeDescription? property) { @@ -62,7 +61,7 @@ class PostgresQueryReduce String _function(_Reducer reducer, ManagedAttributeDescription? property) { return "${reducer.toString().split('.').last}" // The aggregation function "(${_columnName(property)})" // The Column for the aggregation - "${reducer == _Reducer.AVG ? '::float' : ''}"; // Optional cast to float for AVG + "${reducer == _Reducer.avg ? '::float' : ''}"; // Optional cast to float for AVG } Future _execute( @@ -89,7 +88,7 @@ class PostgresQueryReduce final store = query.context.persistentStore as PostgreSQLPersistentStore; final connection = await store.executionContext; try { - final result = await connection!.execute( + final result = await connection.execute( Sql.named(buffer.toString()), parameters: builder.variables, queryMode: QueryMode.extended, diff --git a/packages/postgresql/lib/src/postgresql_schema_generator.dart b/packages/postgresql/lib/src/postgresql_schema_generator.dart index e0259a416..2b36a8b43 100644 --- a/packages/postgresql/lib/src/postgresql_schema_generator.dart +++ b/packages/postgresql/lib/src/postgresql_schema_generator.dart @@ -221,7 +221,7 @@ mixin PostgreSQLSchemaGenerator { return elements.join(" "); } - String? _columnNameForColumn(SchemaColumn column) { + String _columnNameForColumn(SchemaColumn column) { if (column.relatedColumnName != null) { return "${column.name}_${column.relatedColumnName}"; } diff --git a/packages/postgresql/lib/src/query_builder.dart b/packages/postgresql/lib/src/query_builder.dart index c2edb80fe..4bd2c3f38 100644 --- a/packages/postgresql/lib/src/query_builder.dart +++ b/packages/postgresql/lib/src/query_builder.dart @@ -10,7 +10,7 @@ class PostgresQueryBuilder extends TableBuilder { : valueKeyPrefix = "v${prefixIndex}_", placeholderKeyPrefix = "@v${prefixIndex}_", super(query) { - (query.valueMap ?? query.values.backing.contents)! + (query.valueMap ?? query.values.backing.contents) .forEach(addColumnValueBuilder); finalize(variables); } @@ -22,7 +22,7 @@ class PostgresQueryBuilder extends TableBuilder { final Map columnValueBuildersByKey = {}; - Iterable get columnValueKeys => + Iterable get columnValueKeys => columnValueBuildersByKey.keys.toList().reversed; Iterable get columnValueBuilders => @@ -98,7 +98,7 @@ class PostgresQueryBuilder extends TableBuilder { String get sqlValuesToInsert => valuesToInsert(columnValueKeys); - String valuesToInsert(Iterable forKeys) { + String valuesToInsert(Iterable forKeys) { if (forKeys.isEmpty) { return "DEFAULT"; } diff --git a/packages/postgresql/lib/src/row_instantiator.dart b/packages/postgresql/lib/src/row_instantiator.dart index f832a2633..93e45c596 100644 --- a/packages/postgresql/lib/src/row_instantiator.dart +++ b/packages/postgresql/lib/src/row_instantiator.dart @@ -63,7 +63,7 @@ class RowInstantiator { ManagedObject createInstanceWithPrimaryKeyValue( TableBuilder table, - dynamic primaryKeyValue, + Object primaryKeyValue, ) { final instance = table.entity.instanceOf(); diff --git a/packages/postgresql/pubspec.yaml b/packages/postgresql/pubspec.yaml index a7e86c826..4a7f8a217 100644 --- a/packages/postgresql/pubspec.yaml +++ b/packages/postgresql/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: collection: ^1.17.1 diff --git a/packages/postgresql/test/fetch_test.dart b/packages/postgresql/test/fetch_test.dart index e70e43bfc..ef318fede 100644 --- a/packages/postgresql/test/fetch_test.dart +++ b/packages/postgresql/test/fetch_test.dart @@ -337,14 +337,14 @@ void main() { final result = await iq.insert(); expect(result.id, greaterThan(0)); - expect(result.backing.contents!["text"], isNull); + expect(result.backing.contents["text"], isNull); final fq = Query(context!) ..predicate = QueryPredicate("id=@id", {"id": result.id}); final fResult = (await fq.fetchOne())!; expect(fResult.id, result.id); - expect(fResult.backing.contents!["text"], isNull); + expect(fResult.backing.contents["text"], isNull); }); test( @@ -390,7 +390,7 @@ void main() { final result = (await q.fetchOne())!; expect(result.owner!.id, 1); - expect(result.owner!.backing.contents!.length, 1); + expect(result.owner!.backing.contents.length, 1); try { q = Query(context!) diff --git a/packages/postgresql/test/has_many_fetch_test.dart b/packages/postgresql/test/has_many_fetch_test.dart index f8c1a06f2..912ee4b94 100644 --- a/packages/postgresql/test/has_many_fetch_test.dart +++ b/packages/postgresql/test/has_many_fetch_test.dart @@ -79,9 +79,9 @@ void main() { expect(p.pid, isNotNull); expect(p.children!.first.cid, isNotNull); expect(p.children!.first.name, "C5"); - expect(p.children!.first.backing.contents!.containsKey("toy"), false); + expect(p.children!.first.backing.contents.containsKey("toy"), false); expect( - p.children!.first.backing.contents!.containsKey("vaccinations"), + p.children!.first.backing.contents.containsKey("vaccinations"), false, ); } @@ -106,7 +106,7 @@ void main() { expect(p.pid, isNotNull); expect(p.children!.first.cid, isNotNull); expect(p.children!.first.name, "C3"); - expect(p.children!.first.backing.contents!.containsKey("toy"), true); + expect(p.children!.first.backing.contents.containsKey("toy"), true); expect(p.children!.first.toy, isNull); expect(p.children!.first.vaccinations!.length, 1); expect(p.children!.first.vaccinations!.first.vid, isNotNull); @@ -114,7 +114,7 @@ void main() { expect(p.children!.last.cid, isNotNull); expect(p.children!.last.name, "C4"); - expect(p.children!.last.backing.contents!.containsKey("toy"), true); + expect(p.children!.last.backing.contents.containsKey("toy"), true); expect(p.children!.last.toy, isNull); expect(p.children!.last.vaccinations, []); } @@ -174,21 +174,21 @@ void main() { expect(results.first.children!.length, 2); expect(results.first.children!.first.name, "C1"); expect( - results.first.children!.first.backing.contents!.containsKey("toy"), + results.first.children!.first.backing.contents.containsKey("toy"), false, ); expect( - results.first.children!.first.backing.contents! + results.first.children!.first.backing.contents .containsKey("vaccinations"), false, ); expect(results.first.children!.last.name, "C2"); expect( - results.first.children!.last.backing.contents!.containsKey("toy"), + results.first.children!.last.backing.contents.containsKey("toy"), false, ); expect( - results.first.children!.last.backing.contents! + results.first.children!.last.backing.contents .containsKey("vaccinations"), false, ); @@ -198,16 +198,11 @@ void main() { expect(results[1].children!.length, 1); expect(results[1].children!.first.name, "C5"); expect( - results[1].children!.first.backing.contents!.containsKey("toy"), + results[1].children!.first.backing.contents.containsKey("toy"), false, ); expect( - results[1] - .children! - .first - .backing - .contents! - .containsKey("vaccinations"), + results[1].children!.first.backing.contents.containsKey("vaccinations"), false, ); diff --git a/packages/postgresql/test/has_one_fetch_test.dart b/packages/postgresql/test/has_one_fetch_test.dart index c9fd05f58..fc1a7ba03 100644 --- a/packages/postgresql/test/has_one_fetch_test.dart +++ b/packages/postgresql/test/has_one_fetch_test.dart @@ -39,8 +39,8 @@ void main() { expect(p, isNotNull); expect(p!.name, "D"); expect(p.pid, isNotNull); - expect(p.backing.contents!["child"], isNull); - expect(p.backing.contents!.containsKey("child"), true); + expect(p.backing.contents["child"], isNull); + expect(p.backing.contents.containsKey("child"), true); } verifier(await q.fetchOne()); @@ -60,8 +60,8 @@ void main() { expect(p, isNotNull); expect(p!.name, "D"); expect(p.pid, isNotNull); - expect(p.backing.contents!["child"], isNull); - expect(p.backing.contents!.containsKey("child"), true); + expect(p.backing.contents["child"], isNull); + expect(p.backing.contents.containsKey("child"), true); } verifier(await q.fetchOne()); @@ -81,8 +81,8 @@ void main() { expect(p.pid, isNotNull); expect(p.child!.cid, isNotNull); expect(p.child!.name, "C3"); - expect(p.child!.backing.contents!.containsKey("toy"), false); - expect(p.child!.backing.contents!.containsKey("vaccinations"), false); + expect(p.child!.backing.contents.containsKey("toy"), false); + expect(p.child!.backing.contents.containsKey("vaccinations"), false); } verifier(await q.fetchOne()); @@ -104,7 +104,7 @@ void main() { expect(p.pid, isNotNull); expect(p.child!.cid, isNotNull); expect(p.child!.name, "C2"); - expect(p.child!.backing.contents!.containsKey("toy"), true); + expect(p.child!.backing.contents.containsKey("toy"), true); expect(p.child!.toy, isNull); expect(p.child!.vaccinations!.length, 1); expect(p.child!.vaccinations!.first.vid, isNotNull); @@ -130,7 +130,7 @@ void main() { expect(p.pid, isNotNull); expect(p.child!.cid, isNotNull); expect(p.child!.name, "C3"); - expect(p.child!.backing.contents!.containsKey("toy"), true); + expect(p.child!.backing.contents.containsKey("toy"), true); expect(p.child!.toy, isNull); expect(p.child!.vaccinations, []); } @@ -153,7 +153,7 @@ void main() { expect(results.last.pid, isNotNull); expect(results.last.name, "D"); - expect(results.last.backing.contents!.containsKey("child"), true); + expect(results.last.backing.contents.containsKey("child"), true); expect(results.last.child, isNull); }); @@ -244,7 +244,7 @@ void main() { for (final other in results.sublist(1)) { expect(other.child, isNull); - expect(other.backing.contents!.containsKey("child"), true); + expect(other.backing.contents.containsKey("child"), true); } }); @@ -298,7 +298,7 @@ void main() { final res1 = await q.fetchOne(); expect(res1, isNotNull); expect(res1!.pid, 1); - expect(res1.backing.contents!.containsKey("child"), false); + expect(res1.backing.contents.containsKey("child"), false); final q2 = Query(context!) ..where((o) => o.child!.name).equalTo("C1") @@ -335,12 +335,12 @@ void main() { for (final p in parents) { expect(p.name, isNotNull); expect(p.pid, isNotNull); - expect(p.backing.contents!.length, 3); + expect(p.backing.contents.length, 3); if (p.child != null) { expect(p.child!.name, isNotNull); expect(p.child!.cid, isNotNull); - expect(p.child!.backing.contents!.length, 3); + expect(p.child!.backing.contents.length, 3); for (final v in p.child!.vaccinations!) { expect(v.kind, isNotNull); @@ -363,15 +363,15 @@ void main() { final parents = await q.fetch(); for (final p in parents) { expect(p.pid, isNotNull); - expect(p.backing.contents!.length, 2); + expect(p.backing.contents.length, 2); if (p.child != null) { expect(p.child!.cid, isNotNull); - expect(p.child!.backing.contents!.length, 2); + expect(p.child!.backing.contents.length, 2); for (final v in p.child!.vaccinations!) { expect(v.vid, isNotNull); - expect(v.backing.contents!.length, 1); + expect(v.backing.contents.length, 1); } } } diff --git a/packages/postgresql/test/not_tests/helpers.dart b/packages/postgresql/test/not_tests/helpers.dart index 12ca1e32c..be3458d9a 100644 --- a/packages/postgresql/test/not_tests/helpers.dart +++ b/packages/postgresql/test/not_tests/helpers.dart @@ -71,7 +71,7 @@ class TestToken implements AuthToken, AuthCode { @override int? resourceOwnerIdentifier; @override - String? clientID; + late final String clientID; @override String? code; @override @@ -114,7 +114,7 @@ class InMemoryAuthStorage extends AuthServerDelegate { static const String defaultPassword = "foobaraxegrind21%"; - Map? clients; + Map? clients; Map users = {}; List tokens = []; List? allowedScopes; @@ -197,7 +197,7 @@ class InMemoryAuthStorage extends AuthServerDelegate { } @override - FutureOr? getToken( + FutureOr getToken( AuthServer server, { String? byAccessToken, String? byRefreshToken, @@ -296,7 +296,7 @@ class InMemoryAuthStorage extends AuthServerDelegate { tokens.removeWhere((c) => c.code == code); @override - FutureOr getClient(AuthServer server, String? clientID) => + FutureOr getClient(AuthServer server, String clientID) => clients?[clientID]; @override @@ -331,7 +331,7 @@ class DefaultPersistentStore extends PersistentStore { @override Future executeQuery( String formatString, - Map values, + Map values, int timeoutInSeconds, { PersistentStoreQueryReturnType? returnType, }) async => @@ -341,7 +341,7 @@ class DefaultPersistentStore extends PersistentStore { Future close() async {} @override - Future transaction( + Future transaction( ManagedContext transactionContext, Future Function(ManagedContext transaction) transactionBlock, ) async => @@ -423,12 +423,12 @@ class DefaultPersistentStore extends PersistentStore { Future get schemaVersion async => 0; @override - Future upgrade( + Future upgrade( Schema fromSchema, List withMigrations, { bool temporary = false, }) async { - Schema? out = fromSchema; + Schema out = fromSchema; for (final migration in withMigrations) { migration.database = SchemaBuilder(this, out); await migration.upgrade(); diff --git a/packages/postgresql/test/tiered_where_test.dart b/packages/postgresql/test/tiered_where_test.dart index 6cbae4b45..c6a92a793 100644 --- a/packages/postgresql/test/tiered_where_test.dart +++ b/packages/postgresql/test/tiered_where_test.dart @@ -38,10 +38,10 @@ void main() { final results = await q.fetch(); for (final r in results) { - expect(r.backing.contents!.containsKey("child"), false); - expect(r.backing.contents!.length, r.entity.defaultProperties!.length); + expect(r.backing.contents.containsKey("child"), false); + expect(r.backing.contents.length, r.entity.defaultProperties!.length); for (final property in r.entity.defaultProperties!) { - expect(r.backing.contents!.containsKey(property), true); + expect(r.backing.contents.containsKey(property), true); } } }); @@ -52,22 +52,22 @@ void main() { for (final r in results) { expect( - r.backing.contents!.length, + r.backing.contents.length, r.entity.defaultProperties!.length + 1, ); // +1 is for key containing 'child' for (final property in r.entity.defaultProperties!) { - expect(r.backing.contents!.containsKey(property), true); + expect(r.backing.contents.containsKey(property), true); } // Child may be null, but even if it is the key must be in the map - expect(r.backing.contents!.containsKey("child"), true); + expect(r.backing.contents.containsKey("child"), true); if (r.child != null) { expect( - r.child!.backing.contents!.length, + r.child!.backing.contents.length, r.child!.entity.defaultProperties!.length, ); for (final property in r.child!.entity.defaultProperties!) { - expect(r.child!.backing.contents!.containsKey(property), true); + expect(r.child!.backing.contents.containsKey(property), true); } } } @@ -91,24 +91,24 @@ void main() { for (final r in results) { expect( - r.backing.contents!.length, + r.backing.contents.length, r.entity.defaultProperties!.length + 1, ); // +1 is for key containing 'child' for (final property in r.entity.defaultProperties!) { - expect(r.backing.contents!.containsKey(property), true); + expect(r.backing.contents.containsKey(property), true); } // Child may be null, but even if it is the key must be in the map - expect(r.backing.contents!.containsKey("child"), true); + expect(r.backing.contents.containsKey("child"), true); if (r.child != null) { expect( - r.child!.backing.contents!.length, + r.child!.backing.contents.length, r.child!.entity.defaultProperties!.length, ); for (final property in r.child!.entity.defaultProperties!) { - expect(r.child!.backing.contents!.containsKey(property), true); + expect(r.child!.backing.contents.containsKey(property), true); } - expect(r.child!.backing.contents!.containsKey("grandChild"), false); + expect(r.child!.backing.contents.containsKey("grandChild"), false); } } }); @@ -121,33 +121,33 @@ void main() { final results = await q.fetch(); for (final r in results) { expect( - r.backing.contents!.length, + r.backing.contents.length, r.entity.defaultProperties!.length + 1, ); // +1 is for key containing 'child' for (final property in r.entity.defaultProperties!) { - expect(r.backing.contents!.containsKey(property), true); + expect(r.backing.contents.containsKey(property), true); } - expect(r.backing.contents!.containsKey("child"), true); + expect(r.backing.contents.containsKey("child"), true); if (r.child != null) { expect( - r.child!.backing.contents!.length, + r.child!.backing.contents.length, r.child!.entity.defaultProperties!.length + 1, ); // +1 is for key containing 'grandchild for (final property in r.child!.entity.defaultProperties!) { - expect(r.child!.backing.contents!.containsKey(property), true); + expect(r.child!.backing.contents.containsKey(property), true); } - expect(r.child!.backing.contents!.containsKey("grandChild"), true); + expect(r.child!.backing.contents.containsKey("grandChild"), true); if (r.child!.grandChild != null) { expect( - r.child!.grandChild!.backing.contents!.length, + r.child!.grandChild!.backing.contents.length, r.child!.grandChild!.entity.defaultProperties!.length, ); for (final property in r.child!.grandChild!.entity.defaultProperties!) { expect( - r.child!.grandChild!.backing.contents!.containsKey(property), + r.child!.grandChild!.backing.contents.containsKey(property), true, ); } @@ -166,13 +166,13 @@ void main() { final results = await q.fetch(); for (final r in results) { - expect(r.backing.contents!.length, 2 /* id + child */); - expect(r.backing.contents!.containsKey("rid"), true); - expect(r.backing.contents!.containsKey("child"), true); + expect(r.backing.contents.length, 2 /* id + child */); + expect(r.backing.contents.containsKey("rid"), true); + expect(r.backing.contents.containsKey("child"), true); if (r.child != null) { - expect(r.child!.backing.contents!.length, 1); - expect(r.child!.backing.contents!.containsKey("cid"), true); + expect(r.child!.backing.contents.length, 1); + expect(r.child!.backing.contents.containsKey("cid"), true); } } }); @@ -189,19 +189,19 @@ void main() { final results = await q.fetch(); for (final r in results) { - expect(r.backing.contents!.length, 2 /* id + child */); - expect(r.backing.contents!.containsKey("rid"), true); - expect(r.backing.contents!.containsKey("child"), true); + expect(r.backing.contents.length, 2 /* id + child */); + expect(r.backing.contents.containsKey("rid"), true); + expect(r.backing.contents.containsKey("child"), true); if (r.child != null) { - expect(r.child!.backing.contents!.length, 2 /* id + grandchild */); - expect(r.child!.backing.contents!.containsKey("cid"), true); - expect(r.child!.backing.contents!.containsKey("grandChild"), true); + expect(r.child!.backing.contents.length, 2 /* id + grandchild */); + expect(r.child!.backing.contents.containsKey("cid"), true); + expect(r.child!.backing.contents.containsKey("grandChild"), true); if (r.child?.grandChild != null) { - expect(r.child!.grandChild!.backing.contents!.length, 1); + expect(r.child!.grandChild!.backing.contents.length, 1); expect( - r.child!.grandChild!.backing.contents!.containsKey("gid"), + r.child!.grandChild!.backing.contents.containsKey("gid"), true, ); } @@ -296,7 +296,7 @@ void main() { expect(results.length, 1); expect(results.first.rid, 1); - expect(results.first.backing.contents!.containsKey("children"), false); + expect(results.first.backing.contents.containsKey("children"), false); q = Query(ctx!); // ..where((o) => o.children.haveAtLeastOneWhere.cid).equalTo(2) @@ -351,8 +351,7 @@ void main() { expect(results.firstWhere((r) => r.child?.cid == 1).child, isNotNull); expect( results.where((r) => r.rid != 1).every( - (r) => - r.backing.contents!.containsKey("child") && r.child == null, + (r) => r.backing.contents.containsKey("child") && r.child == null, ), true, ); @@ -508,14 +507,14 @@ void main() { final results = await q.fetch(); for (final r in results) { expect( - r.backing.contents!.length, + r.backing.contents.length, r.entity.defaultProperties!.length + 1, ); // +1 is for child for (final property in r.entity.defaultProperties!) { - expect(r.backing.contents!.containsKey(property), true); + expect(r.backing.contents.containsKey(property), true); } - expect(r.child!.backing.contents!.length, 1); - expect(r.child!.backing.contents!.containsKey("cid"), true); + expect(r.child!.backing.contents.length, 1); + expect(r.child!.backing.contents.containsKey("cid"), true); } }); @@ -561,7 +560,7 @@ void main() { expect(results.any((r) => r.rid == 2), true); expect(results.any((r) => r.rid == 4), true); expect( - results.every((r) => r.backing.contents!["children"] == null), + results.every((r) => r.backing.contents["children"] == null), true, ); }); @@ -574,7 +573,7 @@ void main() { expect(results.any((r) => r.rid == 3), true); expect(results.any((r) => r.rid == 5), true); expect( - results.every((r) => r.backing.contents!["children"] == null), + results.every((r) => r.backing.contents["children"] == null), true, ); }); @@ -587,7 +586,7 @@ void main() { expect(results.any((r) => r.rid == 1), true); expect(results.any((r) => r.rid == 2), true); expect(results.any((r) => r.rid == 3), true); - expect(results.every((r) => r.backing.contents!["child"] == null), true); + expect(results.every((r) => r.backing.contents["child"] == null), true); }); test("WhereNull on hasOne", () async { @@ -597,7 +596,7 @@ void main() { expect(results.length, 2); expect(results.any((r) => r.rid == 4), true); expect(results.any((r) => r.rid == 5), true); - expect(results.every((r) => r.backing.contents!["child"] == null), true); + expect(results.every((r) => r.backing.contents["child"] == null), true); }); }); @@ -653,7 +652,7 @@ void main() { final result = await q.fetch(); expect(result.length, 1); expect(result.first.rid, 1); - expect(result.first.backing.contents!.containsKey("child"), false); + expect(result.first.backing.contents.containsKey("child"), false); }); test("From belongs-to-one", () async { @@ -663,7 +662,7 @@ void main() { expect(result.length, 1); expect(result.first.gid, 1); expect( - result.first.backing.contents!["parent"].backing.contents.keys.length, + result.first.backing.contents["parent"].backing.contents.keys.length, 1, ); }); @@ -678,7 +677,7 @@ void main() { expect( result.any( (g) => - g.backing.contents!["parents"].backing.contents.keys.length != 1, + g.backing.contents["parents"].backing.contents.keys.length != 1, ), false, ); diff --git a/packages/runtime/lib/src/build.dart b/packages/runtime/lib/src/build.dart index c5d4c44f1..9529edcfb 100644 --- a/packages/runtime/lib/src/build.dart +++ b/packages/runtime/lib/src/build.dart @@ -51,7 +51,7 @@ class Build { final pubspecMap = { 'name': 'runtime_target', 'version': '1.0.0', - 'environment': {'sdk': '>=3.3.0 <4.0.0'}, + 'environment': {'sdk': '>=3.4.0 <4.0.0'}, 'dependency_overrides': {} }; final overrides = pubspecMap['dependency_overrides'] as Map; diff --git a/packages/runtime/lib/src/context.dart b/packages/runtime/lib/src/context.dart index 23e96f13f..b09006ea3 100644 --- a/packages/runtime/lib/src/context.dart +++ b/packages/runtime/lib/src/context.dart @@ -30,11 +30,11 @@ abstract class RuntimeContext { class RuntimeCollection { RuntimeCollection(this.map); - final Map map; + final Map map; - Iterable get iterable => map.values; + Iterable get iterable => map.values; - dynamic operator [](Type t) { + Object operator [](Type t) { //todo: optimize by keeping a cache where keys are of type [Type] to avoid the // expensive indexOf and substring calls in this method final typeName = t.toString(); diff --git a/packages/runtime/lib/src/generator.dart b/packages/runtime/lib/src/generator.dart index e7ea32a2f..15afa2d62 100644 --- a/packages/runtime/lib/src/generator.dart +++ b/packages/runtime/lib/src/generator.dart @@ -45,7 +45,7 @@ description: A runtime generated by package:conduit_runtime version: 1.0.0 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: '>=3.4.0 <4.0.0' """; String get _loaderShell => """ @@ -57,7 +57,7 @@ RuntimeContext instance = GeneratedContext._(); class GeneratedContext extends RuntimeContext { GeneratedContext._() { - final map = {}; + final map = {}; $_assignmentToken diff --git a/packages/runtime/lib/src/mirror_context.dart b/packages/runtime/lib/src/mirror_context.dart index 59e82100d..a280f8212 100644 --- a/packages/runtime/lib/src/mirror_context.dart +++ b/packages/runtime/lib/src/mirror_context.dart @@ -76,7 +76,7 @@ T? firstMetadataOfType(DeclarationMirror dm, {TypeMirror? dynamicType}) { try { return dm.metadata .firstWhere((im) => im.type.isSubtypeOf(tMirror)) - .reflectee as T?; + .reflectee as T; } on StateError { return null; } diff --git a/packages/runtime/pubspec.yaml b/packages/runtime/pubspec.yaml index 6c8b87bac..6c9d683bb 100644 --- a/packages/runtime/pubspec.yaml +++ b/packages/runtime/pubspec.yaml @@ -6,10 +6,10 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: - analyzer: ^6.4.1 + analyzer: ^6.5.0 args: ^2.0.0 conduit_isolate_exec: ^5.0.3 io: ^1.0.4 diff --git a/packages/runtime_test_packages/application/pubspec.yaml b/packages/runtime_test_packages/application/pubspec.yaml index c729f40d7..9d11e7c57 100644 --- a/packages/runtime_test_packages/application/pubspec.yaml +++ b/packages/runtime_test_packages/application/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: dependency: diff --git a/packages/runtime_test_packages/dependency/pubspec.yaml b/packages/runtime_test_packages/dependency/pubspec.yaml index 4418ac5c1..3eb8edace 100644 --- a/packages/runtime_test_packages/dependency/pubspec.yaml +++ b/packages/runtime_test_packages/dependency/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 publish_to: none environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: conduit_runtime: diff --git a/packages/test_harness/lib/src/agent.dart b/packages/test_harness/lib/src/agent.dart index dc7fdf44b..de69a7481 100644 --- a/packages/test_harness/lib/src/agent.dart +++ b/packages/test_harness/lib/src/agent.dart @@ -96,7 +96,7 @@ class Agent { if (!_application.isRunning) { throw StateError("Application under test is not running."); } - return "${_application.server.requiresHTTPS ? "https" : "http"}://localhost:${_application.channel.server.server!.port}"; + return "${_application.server.requiresHTTPS ? "https" : "http"}://localhost:${_application.channel.server.server.port}"; } return "$_scheme://$_host:$_port"; diff --git a/packages/test_harness/lib/src/auth_harness.dart b/packages/test_harness/lib/src/auth_harness.dart index c7555e79c..c50fcb419 100644 --- a/packages/test_harness/lib/src/auth_harness.dart +++ b/packages/test_harness/lib/src/auth_harness.dart @@ -42,7 +42,7 @@ mixin TestHarnessAuthMixin /// Return that [AuthServer] from this method, e.g., /// /// AuthServer get authServer => channel.authServer; - AuthServer? get authServer; + AuthServer get authServer; /// Creates a new OAuth2 client identifier and returns an [Agent] that makes requests on behalf of that client. /// @@ -65,7 +65,7 @@ mixin TestHarnessAuthMixin ..redirectURI = redirectUri; } - await authServer!.addClient(client); + await authServer.addClient(client); final authorizationHeader = "Basic ${base64.encode("$id:${secret ?? ""}".codeUnits)}"; @@ -90,7 +90,7 @@ mixin TestHarnessAuthMixin final credentials = parser.parse(authorizationHeader); try { - final token = await authServer!.authenticate( + final token = await authServer.authenticate( username, password, credentials.username, credentials.password, requestedScopes: scopes?.map(AuthScope.new).toList()); return Agent.from(fromAgent) diff --git a/packages/test_harness/pubspec.yaml b/packages/test_harness/pubspec.yaml index 5a1c3ef67..3e6a4ecad 100644 --- a/packages/test_harness/pubspec.yaml +++ b/packages/test_harness/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: test: ^1.25.2 diff --git a/packages/test_harness/test/auth_harness_test.dart b/packages/test_harness/test/auth_harness_test.dart index d42c9f3df..479ea74a2 100644 --- a/packages/test_harness/test/auth_harness_test.dart +++ b/packages/test_harness/test/auth_harness_test.dart @@ -117,8 +117,8 @@ void main() { } class Channel extends ApplicationChannel { - ManagedContext? context; - AuthServer? authServer; + late ManagedContext context; + late final AuthServer authServer; @override Future prepare() async { @@ -144,7 +144,7 @@ class HarnessSubclass extends TestHarness Future seed() async {} @override - AuthServer? get authServer => channel!.authServer; + AuthServer get authServer => channel!.authServer; @override ManagedContext? get context => channel!.context; diff --git a/pubspec.yaml b/pubspec.yaml index e73d797aa..58c971f96 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,11 +1,11 @@ name: conduit_workspace -version: 5.0.3 +version: 5.1.0 home: https://www.theconduit.dev repository: https://github.com/conduit-dart/conduit issue_tracker: https://github.com/conduit-dart/conduit/issues environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dev_dependencies: melos: ^6.0.0 diff --git a/utils/pubspec.yaml b/utils/pubspec.yaml index c2d94d81d..92234a641 100644 --- a/utils/pubspec.yaml +++ b/utils/pubspec.yaml @@ -1,7 +1,7 @@ name: utils environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ">=3.4.0 <4.0.0" dependencies: test: ^1.25.2