From 62f2235a6d09936c7dcf824faa9f825dbe2c4451 Mon Sep 17 00:00:00 2001 From: thomashii Date: Sun, 20 Jun 2021 20:37:20 +0800 Subject: [PATCH] Merged from sdk-2.12.x_nnbd --- packages/body_parser/.idea/body_parser.iml | 15 - .../.idea/libraries/Dart_Packages.xml | 421 --------- packages/body_parser/.idea/modules.xml | 8 - .../.idea/runConfigurations/main_dart.xml | 7 - packages/body_parser/.idea/vcs.xml | 6 - packages/body_parser/AUTHORS.md | 12 + packages/body_parser/CHANGELOG.md | 3 + packages/body_parser/analysis_options.yaml | 1 + packages/body_parser/example/main.dart | 22 +- .../lib/src/body_parse_result.dart | 8 +- packages/body_parser/lib/src/chunk.dart | 2 +- .../body_parser/lib/src/file_upload_info.dart | 8 +- packages/body_parser/lib/src/get_value.dart | 20 +- .../body_parser/lib/src/map_from_uri.dart | 33 +- packages/body_parser/lib/src/parse_body.dart | 53 +- packages/body_parser/pubspec.yaml | 17 +- packages/body_parser/test/form_data_test.dart | 52 +- packages/body_parser/test/server_test.dart | 42 +- packages/html/AUTHORS.md | 12 + packages/html/CHANGELOG.md | 3 + packages/html/LICENSE | 6 +- packages/html/example/main.dart | 7 +- packages/html/lib/angel_html.dart | 19 +- packages/html/pubspec.yaml | 34 +- packages/html/test/all_test.dart | 25 +- .../analysis_options.yaml | 1 + .../bin/jael_language_server.dart | 14 +- .../lib/src/analyzer.dart | 55 +- .../jael_language_server/lib/src/object.dart | 4 +- .../protocol/language_server/interface.dart | 16 +- .../protocol/language_server/messages.dart | 702 +++++++-------- .../src/protocol/language_server/server.dart | 30 +- .../protocol/language_server/wireformat.dart | 2 +- .../jael_language_server/lib/src/server.dart | 217 +++-- .../jael/jael_language_server/pubspec.yaml | 41 +- packages/jael/jael_web/LICENSE | 6 +- packages/jael/jael_web/example/stateful.dart | 8 +- .../jael/jael_web/example/stateful.g.dart | 2 +- .../jael_web/example/using_components.dart | 2 +- .../jael_web/example/using_components.g.dart | 4 +- .../jael_web/lib/src/builder/builder.dart | 12 +- .../jael/jael_web/lib/src/builder/util.dart | 20 +- .../jael/jael_web/lib/src/builder_node.dart | 6 +- packages/jael/jael_web/lib/src/component.dart | 2 +- .../jael/jael_web/lib/src/dom_builder.dart | 2 +- packages/jael/jael_web/lib/src/elements.dart | 836 +++++++++--------- .../jael/jael_web/lib/src/jael_component.dart | 8 +- packages/jael/jael_web/pubspec.yaml | 31 +- packages/jinja/AUTHORS.md | 12 + packages/jinja/CHANGELOG.md | 5 +- packages/jinja/README.md | 2 +- packages/jinja/example/main.dart | 2 +- packages/jinja/lib/angel_jinja.dart | 34 +- packages/jinja/pubspec.yaml | 28 +- packages/markdown/AUTHORS.md | 12 + packages/markdown/CHANGELOG.md | 3 + packages/markdown/example/main.dart | 4 +- packages/markdown/lib/angel_markdown.dart | 18 +- packages/markdown/pubspec.yaml | 28 +- packages/mustache/AUTHORS.md | 12 + packages/mustache/CHANGELOG.md | 4 + packages/mustache/LICENSE | 2 +- packages/mustache/analysis_options.yaml | 4 +- packages/mustache/example/main.dart | 4 +- packages/mustache/lib/angel_mustache.dart | 34 +- packages/mustache/lib/src/cache.dart | 49 +- .../mustache/lib/src/mustache_context.dart | 11 +- packages/mustache/pubspec.yaml | 24 +- packages/mustache/test/all_test.dart | 25 +- packages/paginate/AUTHORS.md | 12 + packages/paginate/CHANGELOG.md | 3 + packages/paginate/LICENSE | 4 +- packages/paginate/analysis_options.yaml | 4 + packages/paginate/example/main.dart | 6 +- packages/paginate/lib/angel_paginate.dart | 71 +- packages/paginate/pubspec.yaml | 25 +- packages/paginate/test/all_test.dart | 2 +- packages/paginate/test/bounds_test.dart | 8 +- packages/paginate/test/paginate_test.dart | 16 +- packages/poll/AUTHORS.md | 12 + packages/poll/CHANGELOG.md | 3 + packages/poll/LICENSE | 4 +- packages/poll/analysis_options.yaml | 4 +- packages/poll/example/main.dart | 8 +- packages/poll/lib/angel_poll.dart | 95 +- packages/poll/pubspec.yaml | 25 +- packages/poll/test/all_test.dart | 62 +- packages/redis/AUTHORS.md | 12 + packages/redis/CHANGELOG.md | 3 + packages/redis/LICENSE | 6 +- packages/redis/analysis_options.yaml | 4 + packages/redis/example/main.dart | 9 +- packages/redis/lib/src/redis_service.dart | 95 +- packages/redis/pubspec.yaml | 25 +- packages/redis/test/all_test.dart | 11 +- packages/relations/AUTHORS.md | 12 + packages/relations/CHANGELOG.md | 5 + packages/relations/LICENSE | 4 +- packages/relations/analysis_options.yaml | 4 + packages/relations/lib/src/belongs_to.dart | 57 +- .../relations/lib/src/belongs_to_many.dart | 59 +- packages/relations/lib/src/has_many.dart | 50 +- .../relations/lib/src/has_many_through.dart | 80 +- packages/relations/lib/src/has_one.dart | 51 +- packages/relations/lib/src/no_service.dart | 2 +- packages/relations/lib/src/plural.dart | 14 +- packages/relations/pubspec.yaml | 25 +- packages/relations/test/belongs_to_test.dart | 12 +- packages/relations/test/common.dart | 24 +- packages/relations/test/has_many_test.dart | 12 +- packages/relations/test/has_one_test.dart | 12 +- packages/rethink/AUTHORS.md | 12 + packages/rethink/CHANGELOG.md | 3 + packages/rethink/LICENSE | 4 +- packages/rethink/analysis_options.yaml | 4 + packages/rethink/lib/src/rethink_service.dart | 104 ++- packages/rethink/pubspec.yaml | 40 +- packages/security/AUTHORS.md | 12 + packages/security/CHANGELOG.md | 3 + packages/security/LICENSE | 4 +- packages/security/example/cookie_signer.dart | 5 +- packages/security/example/rate_limit.dart | 3 +- .../security/example/rate_limit_redis.dart | 7 +- packages/security/lib/src/cookie_signer.dart | 8 +- packages/security/lib/src/csrf_filter.dart | 3 +- packages/security/lib/src/helmet.dart | 6 +- .../lib/src/in_memory_rate_limiter.dart | 2 +- packages/security/lib/src/rate_limiter.dart | 25 +- .../lib/src/rate_limiting_window.dart | 8 +- .../lib/src/service_rate_limiter.dart | 2 +- packages/security/pubspec.yaml | 60 +- packages/seeder/AUTHORS.md | 12 + packages/seeder/CHANGELOG.md | 5 + packages/seeder/LICENSE | 4 +- packages/seeder/analysis_options.yaml | 4 + packages/seeder/lib/angel_seeder.dart | 68 +- packages/seeder/pubspec.yaml | 18 +- packages/seeder/test/all_test.dart | 35 +- packages/sembast/AUTHORS.md | 12 + packages/sembast/CHANGELOG.md | 3 + packages/sembast/LICENSE | 6 +- packages/sembast/example/main.dart | 2 +- packages/sembast/lib/angel_sembast.dart | 44 +- packages/sembast/pubspec.yaml | 28 +- packages/sembast/test/all_test.dart | 14 +- packages/seo/AUTHORS.md | 12 + packages/seo/CHANGELOG.md | 3 + packages/seo/LICENSE | 6 +- packages/seo/analysis_options.yaml | 1 + packages/seo/example/main.dart | 14 +- packages/seo/lib/src/inline_assets.dart | 22 +- packages/seo/pubspec.yaml | 42 +- packages/seo/test/inline_assets_test.dart | 19 +- packages/shelf/AUTHORS.md | 12 + packages/shelf/CHANGELOG.md | 3 + packages/shelf/LICENSE | 4 +- packages/shelf/example/angel_in_shelf.dart | 2 +- packages/shelf/lib/src/convert.dart | 14 +- packages/shelf/lib/src/embed_shelf.dart | 4 +- packages/shelf/lib/src/shelf_driver.dart | 66 +- packages/shelf/lib/src/shelf_request.dart | 12 +- packages/shelf/lib/src/shelf_response.dart | 49 +- packages/shelf/pubspec.yaml | 40 +- packages/shelf/test/all.dart | 2 +- packages/shelf/test/embed_shelf_test.dart | 25 +- packages/sync/AUTHORS.md | 12 + packages/sync/CHANGELOG.md | 3 + packages/sync/LICENSE | 4 +- packages/sync/analysis_options.yaml | 1 + packages/sync/example/main.dart | 48 +- packages/sync/lib/angel_sync.dart | 18 +- packages/sync/pubspec.yaml | 32 +- packages/sync/test/all_test.dart | 48 +- packages/typed_service/AUTHORS.md | 12 + packages/typed_service/CHANGELOG.md | 3 + packages/typed_service/LICENSE | 4 +- packages/typed_service/example/main.dart | 12 +- .../lib/angel_typed_service.dart | 61 +- packages/typed_service/pubspec.yaml | 31 +- .../test/typed_service_test.dart | 20 +- packages/user_agent/CHANGELOG.md | 2 - .../{ => angel_user_agent}/.gitignore | 0 .../user_agent/angel_user_agent/AUTHORS.md | 12 + .../user_agent/angel_user_agent/CHANGELOG.md | 5 + .../user_agent/{ => angel_user_agent}/LICENSE | 4 +- .../{ => angel_user_agent}/README.md | 0 .../angel_user_agent/analysis_options.yaml | 4 + .../example/example.dart | 6 +- .../lib/angel_user_agent.dart | 13 +- .../user_agent/angel_user_agent/pubspec.yaml | 19 + packages/user_agent/pubspec.yaml | 11 - packages/user_agent/user_agent/.gitignore | 25 + packages/user_agent/user_agent/.travis.yml | 1 + packages/user_agent/user_agent/AUTHORS.md | 12 + packages/user_agent/user_agent/CHANGELOG.md | 9 + packages/user_agent/user_agent/LICENSE | 21 + packages/user_agent/user_agent/LICENSE.orig | 25 + packages/user_agent/user_agent/README.md | 21 + .../user_agent/analysis_options.yaml | 4 + .../user_agent/example/example.dart | 7 + .../user_agent/user_agent/lib/user_agent.dart | 235 +++++ packages/user_agent/user_agent/pubspec.yaml | 10 + .../user_agent/test/user_agent_test.dart | 30 + .../vscode/jael_language_server/AUTHORS.md | 12 + .../vscode/jael_language_server/CHANGELOG.md | 5 + packages/vscode/jael_language_server/LICENSE | 4 +- .../vscode/jael_language_server/README.md | 1 + .../analysis_options.yaml | 1 + .../bin/jael_language_server.dart | 12 +- .../lib/src/analyzer.dart | 55 +- .../lib/src/formatter.dart | 40 +- .../jael_language_server/lib/src/object.dart | 4 +- .../protocol/language_server/interface.dart | 14 +- .../protocol/language_server/messages.dart | 703 ++++++++------- .../src/protocol/language_server/server.dart | 28 +- .../protocol/language_server/wireformat.dart | 2 +- .../jael_language_server/lib/src/server.dart | 206 +++-- .../vscode/jael_language_server/pubspec.yaml | 43 +- packages/wings/benchmark/empty.dart | 2 +- packages/wings/benchmark/util.dart | 4 +- packages/wings/example/main.dart | 4 +- packages/wings/example/shared.dart | 2 +- packages/wings/example/socket.dart | 2 +- packages/wings/lib/src/wings_driver.dart | 30 +- packages/wings/lib/src/wings_request.dart | 37 +- packages/wings/lib/src/wings_response.dart | 54 +- packages/wings/lib/src/wings_socket.dart | 22 +- packages/wings/pubspec.yaml | 34 +- 228 files changed, 3849 insertions(+), 3305 deletions(-) delete mode 100644 packages/body_parser/.idea/body_parser.iml delete mode 100644 packages/body_parser/.idea/libraries/Dart_Packages.xml delete mode 100644 packages/body_parser/.idea/modules.xml delete mode 100644 packages/body_parser/.idea/runConfigurations/main_dart.xml delete mode 100644 packages/body_parser/.idea/vcs.xml create mode 100644 packages/body_parser/AUTHORS.md create mode 100644 packages/html/AUTHORS.md create mode 100644 packages/jinja/AUTHORS.md create mode 100644 packages/markdown/AUTHORS.md create mode 100644 packages/mustache/AUTHORS.md create mode 100644 packages/paginate/AUTHORS.md create mode 100644 packages/paginate/analysis_options.yaml create mode 100644 packages/poll/AUTHORS.md create mode 100644 packages/redis/AUTHORS.md create mode 100644 packages/redis/analysis_options.yaml create mode 100644 packages/relations/AUTHORS.md create mode 100644 packages/relations/CHANGELOG.md create mode 100644 packages/relations/analysis_options.yaml create mode 100644 packages/rethink/AUTHORS.md create mode 100644 packages/rethink/analysis_options.yaml create mode 100644 packages/security/AUTHORS.md create mode 100644 packages/seeder/AUTHORS.md create mode 100644 packages/seeder/CHANGELOG.md create mode 100644 packages/seeder/analysis_options.yaml create mode 100644 packages/sembast/AUTHORS.md create mode 100644 packages/seo/AUTHORS.md create mode 100644 packages/shelf/AUTHORS.md create mode 100644 packages/sync/AUTHORS.md create mode 100644 packages/typed_service/AUTHORS.md delete mode 100644 packages/user_agent/CHANGELOG.md rename packages/user_agent/{ => angel_user_agent}/.gitignore (100%) create mode 100644 packages/user_agent/angel_user_agent/AUTHORS.md create mode 100644 packages/user_agent/angel_user_agent/CHANGELOG.md rename packages/user_agent/{ => angel_user_agent}/LICENSE (97%) rename packages/user_agent/{ => angel_user_agent}/README.md (100%) create mode 100644 packages/user_agent/angel_user_agent/analysis_options.yaml rename packages/user_agent/{ => angel_user_agent}/example/example.dart (83%) rename packages/user_agent/{ => angel_user_agent}/lib/angel_user_agent.dart (63%) create mode 100644 packages/user_agent/angel_user_agent/pubspec.yaml delete mode 100644 packages/user_agent/pubspec.yaml create mode 100644 packages/user_agent/user_agent/.gitignore create mode 100644 packages/user_agent/user_agent/.travis.yml create mode 100644 packages/user_agent/user_agent/AUTHORS.md create mode 100644 packages/user_agent/user_agent/CHANGELOG.md create mode 100644 packages/user_agent/user_agent/LICENSE create mode 100644 packages/user_agent/user_agent/LICENSE.orig create mode 100644 packages/user_agent/user_agent/README.md create mode 100644 packages/user_agent/user_agent/analysis_options.yaml create mode 100644 packages/user_agent/user_agent/example/example.dart create mode 100644 packages/user_agent/user_agent/lib/user_agent.dart create mode 100644 packages/user_agent/user_agent/pubspec.yaml create mode 100644 packages/user_agent/user_agent/test/user_agent_test.dart create mode 100644 packages/vscode/jael_language_server/AUTHORS.md create mode 100644 packages/vscode/jael_language_server/CHANGELOG.md create mode 100644 packages/vscode/jael_language_server/README.md diff --git a/packages/body_parser/.idea/body_parser.iml b/packages/body_parser/.idea/body_parser.iml deleted file mode 100644 index ae9af975..00000000 --- a/packages/body_parser/.idea/body_parser.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/packages/body_parser/.idea/libraries/Dart_Packages.xml b/packages/body_parser/.idea/libraries/Dart_Packages.xml deleted file mode 100644 index 3a4aead0..00000000 --- a/packages/body_parser/.idea/libraries/Dart_Packages.xml +++ /dev/null @@ -1,421 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/packages/body_parser/.idea/modules.xml b/packages/body_parser/.idea/modules.xml deleted file mode 100644 index 9c283837..00000000 --- a/packages/body_parser/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/packages/body_parser/.idea/runConfigurations/main_dart.xml b/packages/body_parser/.idea/runConfigurations/main_dart.xml deleted file mode 100644 index 750f7262..00000000 --- a/packages/body_parser/.idea/runConfigurations/main_dart.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/packages/body_parser/.idea/vcs.xml b/packages/body_parser/.idea/vcs.xml deleted file mode 100644 index 35eb1ddf..00000000 --- a/packages/body_parser/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/packages/body_parser/AUTHORS.md b/packages/body_parser/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/body_parser/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/body_parser/CHANGELOG.md b/packages/body_parser/CHANGELOG.md index 2304947d..0b3d60c5 100644 --- a/packages/body_parser/CHANGELOG.md +++ b/packages/body_parser/CHANGELOG.md @@ -1,3 +1,6 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 1.1.1 * Dart 2 updates; should fix Angel in Travis. diff --git a/packages/body_parser/analysis_options.yaml b/packages/body_parser/analysis_options.yaml index eae1e42a..c230cee7 100644 --- a/packages/body_parser/analysis_options.yaml +++ b/packages/body_parser/analysis_options.yaml @@ -1,3 +1,4 @@ +include: package:pedantic/analysis_options.yaml analyzer: strong-mode: implicit-casts: false \ No newline at end of file diff --git a/packages/body_parser/example/main.dart b/packages/body_parser/example/main.dart index bda53141..b882307b 100644 --- a/packages/body_parser/example/main.dart +++ b/packages/body_parser/example/main.dart @@ -5,16 +5,16 @@ import 'dart:isolate'; import 'package:http_parser/http_parser.dart'; import 'package:body_parser/body_parser.dart'; -main() async { +void main() async { var address = '127.0.0.1'; var port = 3000; var futures = []; - for (int i = 1; i < Platform.numberOfProcessors; i++) { + for (var i = 1; i < Platform.numberOfProcessors; i++) { futures.add(Isolate.spawn(start, [address, port, i])); } - Future.wait(futures).then((_) { + await Future.wait(futures).then((_) { print('All instances started.'); print( 'Test with "wrk -t12 -c400 -d30s -s ./example/post.lua http://localhost:3000" or similar'); @@ -23,13 +23,13 @@ main() async { } void start(List args) { - var address = new InternetAddress(args[0] as String); - int port = 8080; + var address = InternetAddress(args[0] as String); + var port = 8080; if (args[1] is int) { args[1]; } - int id = 0; + var id = 0; if (args[2] is int) { args[2]; } @@ -39,9 +39,9 @@ void start(List args) { // ignore: deprecated_member_use var body = await defaultParseBody(request); request.response - ..headers.contentType = new ContentType('application', 'json') - ..write(json.encode(body.body)) - ..close(); + ..headers.contentType = ContentType('application', 'json') + ..write(json.encode(body.body)); + await request.response.close(); }); print( @@ -50,11 +50,11 @@ void start(List args) { } Future defaultParseBody(HttpRequest request, - {bool storeOriginalBuffer: false}) { + {bool storeOriginalBuffer = false}) { return parseBodyFromStream( request, request.headers.contentType != null - ? new MediaType.parse(request.headers.contentType.toString()) + ? MediaType.parse(request.headers.contentType.toString()) : null, request.uri, storeOriginalBuffer: storeOriginalBuffer); diff --git a/packages/body_parser/lib/src/body_parse_result.dart b/packages/body_parser/lib/src/body_parse_result.dart index 806335c3..e47fc890 100644 --- a/packages/body_parser/lib/src/body_parse_result.dart +++ b/packages/body_parser/lib/src/body_parse_result.dart @@ -3,10 +3,10 @@ import 'file_upload_info.dart'; /// A representation of data from an incoming request. abstract class BodyParseResult { /// The parsed body. - Map get body; + Map get body; /// The parsed query string. - Map get query; + Map get query; /// All files uploaded within this request. List get files; @@ -14,7 +14,7 @@ abstract class BodyParseResult { /// The original body bytes sent with this request. /// /// You must set [storeOriginalBuffer] to `true` to see this. - List get originalBuffer; + List? get originalBuffer; /// If an error was encountered while parsing the body, it will appear here. /// @@ -24,5 +24,5 @@ abstract class BodyParseResult { /// If an error was encountered while parsing the body, the call stack will appear here. /// /// Otherwise, this is `null`. - StackTrace get stack; + StackTrace? get stack; } diff --git a/packages/body_parser/lib/src/chunk.dart b/packages/body_parser/lib/src/chunk.dart index 58776ca0..90c078b8 100644 --- a/packages/body_parser/lib/src/chunk.dart +++ b/packages/body_parser/lib/src/chunk.dart @@ -2,6 +2,6 @@ import 'file_upload_info.dart'; List getFileDataFromChunk( String chunk, String boundary, String fileUploadName, Map body) { - List result = []; + var result = []; return result; } diff --git a/packages/body_parser/lib/src/file_upload_info.dart b/packages/body_parser/lib/src/file_upload_info.dart index 5db8b785..285d72d4 100644 --- a/packages/body_parser/lib/src/file_upload_info.dart +++ b/packages/body_parser/lib/src/file_upload_info.dart @@ -1,17 +1,17 @@ /// Represents a file uploaded to the server. class FileUploadInfo { /// The MIME type of the uploaded file. - String mimeType; + String? mimeType; /// The name of the file field from the request. - String name; + String? name; /// The filename of the file. - String filename; + String? filename; /// The bytes that make up this file. List data; FileUploadInfo( - {this.mimeType, this.name, this.filename, this.data: const []}) {} + {this.mimeType, this.name, this.filename, this.data = const []}); } diff --git a/packages/body_parser/lib/src/get_value.dart b/packages/body_parser/lib/src/get_value.dart index d3c6c3f1..8d2106ee 100644 --- a/packages/body_parser/lib/src/get_value.dart +++ b/packages/body_parser/lib/src/get_value.dart @@ -1,20 +1,22 @@ -import 'package:dart2_constant/convert.dart'; +import 'dart:convert'; -getValue(String value) { +dynamic getValue(String value) { try { - num numValue = num.parse(value); - if (!numValue.isNaN) + var numValue = num.parse(value); + if (!numValue.isNaN) { return numValue; - else + } else { return value; + } } on FormatException { - if (value.startsWith('[') && value.endsWith(']')) + if (value.startsWith('[') && value.endsWith(']')) { return json.decode(value); - else if (value.startsWith('{') && value.endsWith('}')) + } else if (value.startsWith('{') && value.endsWith('}')) { return json.decode(value); - else if (value.trim().toLowerCase() == 'null') + } else if (value.trim().toLowerCase() == 'null') { return null; - else + } else { return value; + } } } diff --git a/packages/body_parser/lib/src/map_from_uri.dart b/packages/body_parser/lib/src/map_from_uri.dart index 0945ce6b..df193da2 100644 --- a/packages/body_parser/lib/src/map_from_uri.dart +++ b/packages/body_parser/lib/src/map_from_uri.dart @@ -3,19 +3,18 @@ import 'get_value.dart'; /// Parses a URI-encoded string into real data! **Wow!** /// /// Whichever map you provide will be automatically populated from the urlencoded body string you provide. -buildMapFromUri(Map map, String body) { - RegExp parseArrayRgx = new RegExp(r'^(.+)\[\]$'); +void buildMapFromUri(Map map, String body) { + var parseArrayRgx = RegExp(r'^(.+)\[\]$'); - for (String keyValuePair in body.split('&')) { + for (var keyValuePair in body.split('&')) { if (keyValuePair.contains('=')) { var equals = keyValuePair.indexOf('='); - String key = Uri.decodeQueryComponent(keyValuePair.substring(0, equals)); - String value = - Uri.decodeQueryComponent(keyValuePair.substring(equals + 1)); + var key = Uri.decodeQueryComponent(keyValuePair.substring(0, equals)); + var value = Uri.decodeQueryComponent(keyValuePair.substring(equals + 1)); if (parseArrayRgx.hasMatch(key)) { - Match queryMatch = parseArrayRgx.firstMatch(key); - key = queryMatch.group(1); + Match queryMatch = parseArrayRgx.firstMatch(key)!; + key = queryMatch.group(1)!; if (!(map[key] is List)) { map[key] = []; } @@ -23,21 +22,23 @@ buildMapFromUri(Map map, String body) { map[key].add(getValue(value)); } else if (key.contains('.')) { // i.e. map.foo.bar => [map, foo, bar] - List keys = key.split('.'); + var keys = key.split('.'); - Map targetMap = map[keys[0]] != null ? map[keys[0]] as Map : {}; + var targetMap = map[keys[0]] != null ? map[keys[0]] as Map? : {}; map[keys[0]] = targetMap; - for (int i = 1; i < keys.length; i++) { + for (var i = 1; i < keys.length; i++) { if (i < keys.length - 1) { - targetMap[keys[i]] = targetMap[keys[i]] ?? {}; - targetMap = targetMap[keys[i]] as Map; + targetMap![keys[i]] = targetMap[keys[i]] ?? {}; + targetMap = targetMap[keys[i]] as Map?; } else { - targetMap[keys[i]] = getValue(value); + targetMap![keys[i]] = getValue(value); } } - } else + } else { map[key] = getValue(value); - } else + } + } else { map[Uri.decodeQueryComponent(keyValuePair)] = true; + } } } diff --git a/packages/body_parser/lib/src/parse_body.dart b/packages/body_parser/lib/src/parse_body.dart index 8fdb94b9..9c9344cf 100644 --- a/packages/body_parser/lib/src/parse_body.dart +++ b/packages/body_parser/lib/src/parse_body.dart @@ -1,8 +1,8 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; -import 'package:dart2_constant/convert.dart'; import 'package:http_parser/http_parser.dart'; import 'package:http_server/http_server.dart'; import 'package:mime/mime.dart'; @@ -14,11 +14,11 @@ import 'map_from_uri.dart'; /// Forwards to [parseBodyFromStream]. @deprecated Future parseBody(HttpRequest request, - {bool storeOriginalBuffer: false}) { + {bool storeOriginalBuffer = false}) { return parseBodyFromStream( request, request.headers.contentType != null - ? new MediaType.parse(request.headers.contentType.toString()) + ? MediaType.parse(request.headers.contentType.toString()) : null, request.uri, storeOriginalBuffer: storeOriginalBuffer); @@ -33,13 +33,13 @@ Future parseBody(HttpRequest request, /// /// Use [storeOriginalBuffer] to add the original request bytes to the result. Future parseBodyFromStream( - Stream data, MediaType contentType, Uri requestUri, - {bool storeOriginalBuffer: false}) async { - var result = new _BodyParseResultImpl(); + Stream data, MediaType? contentType, Uri requestUri, + {bool storeOriginalBuffer = false}) async { + var result = _BodyParseResultImpl(); Future getBytes() { return data - .fold(new BytesBuilder(copy: false), (a, b) => a..add(b)) + .fold(BytesBuilder(copy: false), (a, b) => a..add(b)) .then((b) => b.takeBytes()); } @@ -62,30 +62,29 @@ Future parseBodyFromStream( if (storeOriginalBuffer) { var bytes = result.originalBuffer = await getBytes(); - var ctrl = new StreamController() - ..add(bytes) - ..close(); + var ctrl = StreamController()..add(bytes); + await ctrl.close(); stream = ctrl.stream; } else { stream = data; } - var parts = MimeMultipartTransformer( - contentType.parameters['boundary']).bind(stream) + var parts = MimeMultipartTransformer(contentType.parameters['boundary']!) + .bind(stream) .map((part) => HttpMultipartFormData.parse(part, defaultEncoding: utf8)); await for (HttpMultipartFormData part in parts) { if (part.isBinary || - part.contentDisposition.parameters.containsKey("filename")) { - BytesBuilder builder = await part.fold( - new BytesBuilder(copy: false), + part.contentDisposition.parameters.containsKey('filename')) { + var builder = await part.fold( + BytesBuilder(copy: false), (BytesBuilder b, d) => b ..add(d is! String - ? (d as List) - : (d as String).codeUnits)); - var upload = new FileUploadInfo( - mimeType: part.contentType.mimeType, + ? (d as List?)! + : d.codeUnits)); + var upload = FileUploadInfo( + mimeType: part.contentType!.mimeType, name: part.contentDisposition.parameters['name'], filename: part.contentDisposition.parameters['filename'] ?? 'file', @@ -99,9 +98,9 @@ Future parseBodyFromStream( } } else if (contentType.mimeType == 'application/json') { result.body - .addAll(_foldToStringDynamic(json.decode(await getBody()) as Map)); + .addAll(_foldToStringDynamic(json.decode(await getBody()) as Map?)!); } else if (contentType.mimeType == 'application/x-www-form-urlencoded') { - String body = await getBody(); + var body = await getBody(); buildMapFromUri(result.body, body); } else if (storeOriginalBuffer == true) { result.originalBuffer = await getBytes(); @@ -125,25 +124,25 @@ Future parseBodyFromStream( class _BodyParseResultImpl implements BodyParseResult { @override - Map body = {}; + Map body = {}; @override List files = []; @override - List originalBuffer; + List? originalBuffer; @override - Map query = {}; + Map query = {}; @override - var error = null; + var error; @override - StackTrace stack = null; + StackTrace? stack; } -Map _foldToStringDynamic(Map map) { +Map? _foldToStringDynamic(Map? map) { return map == null ? null : map.keys.fold>( diff --git a/packages/body_parser/pubspec.yaml b/packages/body_parser/pubspec.yaml index a761ce02..1f5b5b8c 100644 --- a/packages/body_parser/pubspec.yaml +++ b/packages/body_parser/pubspec.yaml @@ -1,15 +1,14 @@ name: body_parser -author: Tobe O -version: 1.1.1 +version: 2.0.0 description: Parse request bodies and query strings in Dart. Supports JSON, URL-encoded, and multi-part bodies. homepage: https://github.com/angel-dart/body_parser environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - dart2_constant: ^1.0.0 - http_parser: ">=3.1.1 <4.0.0" - http_server: ">=0.9.6 <1.0.0" - mime: ">=0.9.3 <1.0.0" + http_parser: ^4.0.0 + http_server: ^1.0.0 + mime: ^1.0.0 dev_dependencies: - http: ">=0.11.3 <0.12.0" - test: ^1.15.7 \ No newline at end of file + http: ^0.13.0 + test: ^1.17.0 + pedantic: ^1.11.0 \ No newline at end of file diff --git a/packages/body_parser/test/form_data_test.dart b/packages/body_parser/test/form_data_test.dart index abab9ff7..dfa27a28 100644 --- a/packages/body_parser/test/form_data_test.dart +++ b/packages/body_parser/test/form_data_test.dart @@ -1,54 +1,54 @@ import 'dart:io'; import 'dart:convert'; import 'package:body_parser/body_parser.dart'; -import 'package:dart2_constant/convert.dart'; import 'package:http/http.dart' as http; import 'package:test/test.dart'; import 'server_test.dart'; void main() { - HttpServer server; - String url; - http.Client client; + HttpServer? server; + String? url; + http.Client? client; setUp(() async { server = await HttpServer.bind('127.0.0.1', 0); - server.listen((HttpRequest request) async { + server!.listen((HttpRequest request) async { //Server will simply return a JSON representation of the parsed body // ignore: deprecated_member_use request.response.write(jsonEncodeBody(await parseBody(request))); await request.response.close(); }); - url = 'http://localhost:${server.port}'; + url = 'http://localhost:${server!.port}'; print('Test server listening on $url'); client = http.Client(); }); tearDown(() async { - await server.close(force: true); - client.close(); + await server!.close(force: true); + client!.close(); server = null; url = null; client = null; }); test('No upload', () async { - String boundary = 'myBoundary'; - Map headers = { + var boundary = 'myBoundary'; + var headers = { 'content-type': 'multipart/form-data; boundary=$boundary' }; - String postData = ''' + var postData = ''' --$boundary Content-Disposition: form-data; name="hello" world --$boundary-- ''' - .replaceAll("\n", "\r\n"); + .replaceAll('\n', '\r\n'); print( 'Form Data: \n${postData.replaceAll("\r", "\\r").replaceAll("\n", "\\n")}'); - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var jsons = json.decode(response.body); var files = jsons['files'].map((map) { @@ -62,12 +62,12 @@ world }); test('Single upload', () async { - String boundary = 'myBoundary'; - Map headers = { - 'content-type': ContentType("multipart", "form-data", - parameters: {"boundary": boundary}).toString() + var boundary = 'myBoundary'; + var headers = { + 'content-type': ContentType('multipart', 'form-data', + parameters: {'boundary': boundary}).toString() }; - String postData = ''' + var postData = ''' --$boundary Content-Disposition: form-data; name="hello" @@ -79,11 +79,12 @@ Content-Type: application/dart Hello world --$boundary-- ''' - .replaceAll("\n", "\r\n"); + .replaceAll('\n', '\r\n'); print( 'Form Data: \n${postData.replaceAll("\r", "\\r").replaceAll("\n", "\\n")}'); - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var jsons = json.decode(response.body); var files = jsons['files']; @@ -96,11 +97,11 @@ Hello world }); test('Multiple upload', () async { - String boundary = 'myBoundary'; - Map headers = { + var boundary = 'myBoundary'; + var headers = { 'content-type': 'multipart/form-data; boundary=$boundary' }; - String postData = ''' + var postData = ''' --$boundary Content-Disposition: form-data; name="json" @@ -123,11 +124,12 @@ function main() { } --$boundary-- ''' - .replaceAll("\n", "\r\n"); + .replaceAll('\n', '\r\n'); print( 'Form Data: \n${postData.replaceAll("\r", "\\r").replaceAll("\n", "\\n")}'); - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var jsons = json.decode(response.body); var files = jsons['files']; diff --git a/packages/body_parser/test/server_test.dart b/packages/body_parser/test/server_test.dart index de82e652..5ca2a8da 100644 --- a/packages/body_parser/test/server_test.dart +++ b/packages/body_parser/test/server_test.dart @@ -1,7 +1,7 @@ +import 'dart:convert'; import 'dart:io' show HttpRequest, HttpServer; import 'package:body_parser/body_parser.dart'; -import 'package:dart2_constant/convert.dart'; import 'package:http/http.dart' as http; import 'package:test/test.dart'; @@ -27,26 +27,26 @@ String jsonEncodeBody(BodyParseResult result) { } void main() { - HttpServer server; - String url; - http.Client client; + HttpServer? server; + String? url; + http.Client? client; setUp(() async { server = await HttpServer.bind('127.0.0.1', 0); - server.listen((HttpRequest request) async { + server!.listen((HttpRequest request) async { //Server will simply return a JSON representation of the parsed body request.response.write( // ignore: deprecated_member_use jsonEncodeBody(await parseBody(request, storeOriginalBuffer: true))); await request.response.close(); }); - url = 'http://localhost:${server.port}'; + url = 'http://localhost:${server!.port}'; print('Test server listening on $url'); client = http.Client(); }); tearDown(() async { - await server.close(force: true); - client.close(); + await server!.close(force: true); + client!.close(); server = null; url = null; client = null; @@ -55,7 +55,7 @@ void main() { group('query string', () { test('GET Simple', () async { print('GET $url/?hello=world'); - var response = await client.get('$url/?hello=world'); + var response = await client!.get(Uri.parse('$url/?hello=world')); print('Response: ${response.body}'); var result = json.decode(response.body); expect(result['body'], equals({})); @@ -68,7 +68,7 @@ void main() { var postData = 'hello=world&nums%5B%5D=1&nums%5B%5D=2.0&nums%5B%5D=${3 - 1}&map.foo.bar=baz'; print('Body: $postData'); - var response = await client.get('$url/?$postData'); + var response = await client!.get(Uri.parse('$url/?$postData')); print('Response: ${response.body}'); var query = json.decode(response.body)['query']; expect(query['hello'], equals('world')); @@ -80,7 +80,7 @@ void main() { test('JWT', () async { var postData = 'token=$TOKEN'; print('Body: $postData'); - var response = await client.get('$url/?$postData'); + var response = await client!.get(Uri.parse('$url/?$postData')); print('Response: ${response.body}'); var query = json.decode(response.body)['query']; expect(query['token'], equals(TOKEN)); @@ -88,13 +88,13 @@ void main() { }); group('urlencoded', () { - Map headers = { + var headers = { 'content-type': 'application/x-www-form-urlencoded' }; test('POST Simple', () async { print('Body: hello=world'); - var response = - await client.post(url, headers: headers, body: 'hello=world'); + var response = await client!.post(Uri.parse(url!), + headers: headers, body: 'hello=world'); print('Response: ${response.body}'); var result = json.decode(response.body); expect(result['query'], equals({})); @@ -107,7 +107,8 @@ void main() { test('Post Complex', () async { var postData = 'hello=world&nums%5B%5D=1&nums%5B%5D=2.0&nums%5B%5D=${3 - 1}&map.foo.bar=baz'; - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var body = json.decode(response.body)['body']; expect(body['hello'], equals('world')); @@ -118,18 +119,20 @@ void main() { test('JWT', () async { var postData = 'token=$TOKEN'; - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); var body = json.decode(response.body)['body']; expect(body['token'], equals(TOKEN)); }); }); group('json', () { - Map headers = {'content-type': 'application/json'}; + var headers = {'content-type': 'application/json'}; test('Post Simple', () async { var postData = json.encode({'hello': 'world'}); print('Body: $postData'); - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var result = json.decode(response.body); expect(result['body'], equals({'hello': 'world'})); @@ -147,7 +150,8 @@ void main() { } }); print('Body: $postData'); - var response = await client.post(url, headers: headers, body: postData); + var response = + await client!.post(Uri.parse(url!), headers: headers, body: postData); print('Response: ${response.body}'); var body = json.decode(response.body)['body']; expect(body['hello'], equals('world')); diff --git a/packages/html/AUTHORS.md b/packages/html/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/html/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/html/CHANGELOG.md b/packages/html/CHANGELOG.md index 324effd8..3857adbb 100644 --- a/packages/html/CHANGELOG.md +++ b/packages/html/CHANGELOG.md @@ -1,2 +1,5 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 2.0.0 * Angel 2 + Dart 2 updates. \ No newline at end of file diff --git a/packages/html/LICENSE b/packages/html/LICENSE index 8f65b579..3de28325 100644 --- a/packages/html/LICENSE +++ b/packages/html/LICENSE @@ -1,6 +1,6 @@ -MIT License (MIT) +MIT License -Copyright (c) 2021 dukefirehawk.com +Copyright (c) 2017 Tobe O Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/html/example/main.dart b/packages/html/example/main.dart index d1570ec3..a322cf39 100644 --- a/packages/html/example/main.dart +++ b/packages/html/example/main.dart @@ -4,8 +4,9 @@ import 'package:angel_html/angel_html.dart'; import 'package:html_builder/elements.dart'; import 'package:logging/logging.dart'; -main() async { - var app = Angel(), http = AngelHttp(app); +void main() async { + var app = Angel(); + var http = AngelHttp(app); app.logger = Logger('angel_html') ..onRecord.listen((rec) { print(rec); @@ -29,7 +30,7 @@ main() async { renderHtml( enforceAcceptHeader: true, renderer: StringRenderer( - doctype: null, + //doctype: null, pretty: false, ), ), diff --git a/packages/html/lib/angel_html.dart b/packages/html/lib/angel_html.dart index 81b7c853..2393adb1 100644 --- a/packages/html/lib/angel_html.dart +++ b/packages/html/lib/angel_html.dart @@ -7,20 +7,21 @@ import 'package:html_builder/html_builder.dart'; /// You can provide a custom [renderer]. The default renders minified HTML5 pages. /// /// Set [enforceAcceptHeader] to `true` to throw a `406 Not Acceptable` if the client doesn't accept HTML responses. -RequestHandler renderHtml({StringRenderer renderer, bool enforceAcceptHeader}) { - renderer ??= new StringRenderer(pretty: false, html5: true); +RequestHandler renderHtml({StringRenderer? renderer, bool? enforceAcceptHeader}) { + renderer ??= StringRenderer(pretty: false, html5: true); return (RequestContext req, ResponseContext res) { var oldSerializer = res.serializer; res.serializer = (data) { - if (data is! Node) - return oldSerializer(data); - else { - if (enforceAcceptHeader == true && !req.accepts('text/html')) - throw new AngelHttpException.notAcceptable(); + if (data is! Node) { + return oldSerializer!(data); + } else { + if (enforceAcceptHeader == true && !req.accepts('text/html')) { + throw AngelHttpException.notAcceptable(); + } - var content = renderer.render(data as Node); + var content = renderer!.render(data); res ..headers['content-type'] = 'text/html' ..write(content); @@ -29,6 +30,6 @@ RequestHandler renderHtml({StringRenderer renderer, bool enforceAcceptHeader}) { } }; - return new Future.value(true); + return Future.value(true); }; } diff --git a/packages/html/pubspec.yaml b/packages/html/pubspec.yaml index eb29ec87..1ef34ad1 100644 --- a/packages/html/pubspec.yaml +++ b/packages/html/pubspec.yaml @@ -1,18 +1,28 @@ name: angel_html -version: 2.0.0 +version: 3.0.0 description: Support for rendering html_builder AST's as responses in Angel. -author: Tobe O homepage: https://github.com/angel-dart/html_builder +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - html_builder: ^1.0.0 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + html_builder: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/html_builder dev_dependencies: - angel_test: #^2.0.0-alpha - path: ../test - html: ^0.13.2 - logging: ^0.11.0 - test: ^1.15.7 - pedantic: ^1.0.0 \ No newline at end of file + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + html: ^0.15.0 + logging: ^1.0.1 + test: ^1.17.0 + pedantic: ^1.11.0 \ No newline at end of file diff --git a/packages/html/test/all_test.dart b/packages/html/test/all_test.dart index e6777418..ba2d05d4 100644 --- a/packages/html/test/all_test.dart +++ b/packages/html/test/all_test.dart @@ -5,12 +5,12 @@ import 'package:html_builder/elements.dart'; import 'package:html_builder/html_builder.dart'; import 'package:test/test.dart'; -main() { +void main() { Angel app; - TestClient client; + late TestClient client; setUp(() async { - app = new Angel(); + app = Angel(); app.fallback(renderHtml()); @@ -27,8 +27,8 @@ main() { chain([ renderHtml( enforceAcceptHeader: true, - renderer: new StringRenderer( - doctype: null, + renderer: StringRenderer( + //doctype: null, pretty: false, ), ), @@ -43,7 +43,7 @@ main() { tearDown(() => client.close()); test('sets content type and body', () async { - var response = await client.get('/html'); + var response = await client.get(Uri.parse('/html')); print('Response: ${response.body}'); expect( @@ -56,12 +56,13 @@ main() { group('enforce accept header', () { test('sends if correct accept or wildcard', () async { - var response = await client.get('/strict', headers: {'accept': '*/*'}); + var response = + await client.get(Uri.parse('/strict'), headers: {'accept': '*/*'}); print('Response: ${response.body}'); expect(response, allOf(hasContentType('text/html'), hasBody('
strict
'))); - response = await client.get('/strict', + response = await client.get(Uri.parse('/strict'), headers: {'accept': 'text/html,application/json,text/xml'}); print('Response: ${response.body}'); expect(response, @@ -69,12 +70,12 @@ main() { }); test('throws if incorrect or no accept', () async { - var response = await client.get('/strict'); - print('Response: ${response.body}'); + var response = await client.get(Uri.parse('/strict')); + print('Response: ${response.statusCode} ${response.body}'); expect(response, hasStatus(406)); - response = await client - .get('/strict', headers: {'accept': 'application/json,text/xml'}); + response = await client.get(Uri.parse('/strict'), + headers: {'accept': 'application/json,text/xml'}); print('Response: ${response.body}'); expect(response, isAngelHttpException(statusCode: 406, message: '406 Not Acceptable')); diff --git a/packages/jael/jael_language_server/analysis_options.yaml b/packages/jael/jael_language_server/analysis_options.yaml index eae1e42a..c230cee7 100644 --- a/packages/jael/jael_language_server/analysis_options.yaml +++ b/packages/jael/jael_language_server/analysis_options.yaml @@ -1,3 +1,4 @@ +include: package:pedantic/analysis_options.yaml analyzer: strong-mode: implicit-casts: false \ No newline at end of file diff --git a/packages/jael/jael_language_server/bin/jael_language_server.dart b/packages/jael/jael_language_server/bin/jael_language_server.dart index 77e9ef58..39033ce1 100644 --- a/packages/jael/jael_language_server/bin/jael_language_server.dart +++ b/packages/jael/jael_language_server/bin/jael_language_server.dart @@ -7,8 +7,8 @@ import 'package:io/io.dart'; import 'package:jael_language_server/jael_language_server.dart'; import 'package:jael_language_server/src/protocol/language_server/server.dart'; -main(List args) async { - var argParser = new ArgParser() +void main(List args) async { + var argParser = ArgParser() ..addFlag('help', abbr: 'h', negatable: false, help: 'Print this help information.') ..addOption('log-file', help: 'A path to which to write a log file.'); @@ -25,14 +25,14 @@ main(List args) async { printUsage(); return; } else { - var jaelServer = new JaelLanguageServer(); + var jaelServer = JaelLanguageServer(); if (argResults.wasParsed('log-file')) { - var f = new File(argResults['log-file'] as String); + var f = File(argResults['log-file'] as String); await f.create(recursive: true); jaelServer.logger.onRecord.listen((rec) async { - var sink = await f.openWrite(mode: FileMode.append); + var sink = f.openWrite(mode: FileMode.append); sink.writeln(rec); if (rec.error != null) sink.writeln(rec.error); if (rec.stackTrace != null) sink.writeln(rec.stackTrace); @@ -47,7 +47,7 @@ main(List args) async { }); } - var spec = new ZoneSpecification( + var spec = ZoneSpecification( handleUncaughtError: (self, parent, zone, error, stackTrace) { jaelServer.logger.severe('Uncaught', error, stackTrace); }, @@ -57,7 +57,7 @@ main(List args) async { ); var zone = Zone.current.fork(specification: spec); await zone.run(() async { - var stdio = new StdIOLanguageServer.start(jaelServer); + var stdio = StdIOLanguageServer.start(jaelServer); await stdio.onDone; }); } diff --git a/packages/jael/jael_language_server/lib/src/analyzer.dart b/packages/jael/jael_language_server/lib/src/analyzer.dart index 3d47d057..f9944e7d 100644 --- a/packages/jael/jael_language_server/lib/src/analyzer.dart +++ b/packages/jael/jael_language_server/lib/src/analyzer.dart @@ -7,18 +7,19 @@ class Analyzer extends Parser { final Logger logger; Analyzer(Scanner scanner, this.logger) : super(scanner); + @override final errors = []; - var _scope = new SymbolTable(); + SymbolTable? _scope = SymbolTable(); var allDefinitions = >[]; - SymbolTable get parentScope => - _scope.isRoot ? _scope : _scope.parent; + SymbolTable? get parentScope => + _scope!.isRoot ? _scope : _scope!.parent; - SymbolTable get scope => _scope; + SymbolTable? get scope => _scope; bool ensureAttributeIsPresent(Element element, String name) { if (element.getAttribute(name)?.value == null) { - addError(new JaelError(JaelErrorSeverity.error, + addError(JaelError(JaelErrorSeverity.error, 'Missing required attribute `$name`.', element.span)); return false; } @@ -33,9 +34,9 @@ class Analyzer extends Parser { bool ensureAttributeIsConstantString(Element element, String name) { var a = element.getAttribute(name); if (a?.value is! StringLiteral || a?.value == null) { - var e = new JaelError( + var e = JaelError( JaelErrorSeverity.warning, - "`$name` attribute should be a constant string literal.", + '`$name` attribute should be a constant string literal.', a?.span ?? element.tagName.span); addError(e); return false; @@ -45,18 +46,18 @@ class Analyzer extends Parser { } @override - Element parseElement() { + Element? parseElement() { try { - _scope = _scope.createChild(); + _scope = _scope!.createChild(); var element = super.parseElement(); if (element == null) return null; // Check if any custom element exists. - _scope + _scope! .resolve(element.tagName.name) ?.value ?.usages - ?.add(new SymbolUsage(SymbolUsageType.read, element.span)); + .add(SymbolUsage(SymbolUsageType.read, element.span)); // Validate attrs var forEach = element.getAttribute('for-each'); @@ -64,14 +65,14 @@ class Analyzer extends Parser { var asAttr = element.getAttribute('as'); if (asAttr != null) { if (ensureAttributeIsConstantString(element, 'as')) { - var asName = asAttr.string.value; - _scope.create(asName, - value: new JaelVariable(asName, asAttr.span), constant: true); + var asName = asAttr.string!.value; + _scope!.create(asName, + value: JaelVariable(asName, asAttr.span), constant: true); } } if (forEach.value != null) { - addError(new JaelError(JaelErrorSeverity.error, + addError(JaelError(JaelErrorSeverity.error, 'Missing value for `for-each` directive.', forEach.span)); } } @@ -79,7 +80,7 @@ class Analyzer extends Parser { var iff = element.getAttribute('if'); if (iff != null) { if (iff.value != null) { - addError(new JaelError(JaelErrorSeverity.error, + addError(JaelError(JaelErrorSeverity.error, 'Missing value for `iff` directive.', iff.span)); } } @@ -94,29 +95,29 @@ class Analyzer extends Parser { //logger.info('Found at ${element.span.start.toolString}'); } else if (element.tagName.name == 'declare') { if (element.attributes.isEmpty) { - addError(new JaelError( + addError(JaelError( JaelErrorSeverity.warning, '`declare` directive does not define any new symbols.', element.tagName.span)); } else { for (var attr in element.attributes) { - _scope.create(attr.name, - value: new JaelVariable(attr.name, attr.span)); + _scope! + .create(attr.name, value: JaelVariable(attr.name, attr.span)); } } } else if (element.tagName.name == 'element') { if (ensureAttributeIsConstantString(element, 'name')) { - var nameCtx = element.getAttribute('name').value as StringLiteral; + var nameCtx = element.getAttribute('name')!.value as StringLiteral; var name = nameCtx.value; //logger.info( // 'Found custom element $name at ${element.span.start.toolString}'); try { - var symbol = parentScope.create(name, - value: new JaelCustomElement(name, element.tagName.span), + var symbol = parentScope!.create(name, + value: JaelCustomElement(name, element.tagName.span), constant: true); allDefinitions.add(symbol); } on StateError catch (e) { - addError(new JaelError( + addError(JaelError( JaelErrorSeverity.error, e.message, element.tagName.span)); } } @@ -133,19 +134,19 @@ class Analyzer extends Parser { return element; } finally { - _scope = _scope.parent; + _scope = _scope!.parent; return null; } } @override - Expression parseExpression(int precedence) { + Expression? parseExpression(int precedence) { var expr = super.parseExpression(precedence); if (expr == null) return null; if (expr is Identifier) { - var ref = _scope.resolve(expr.name); - ref?.value?.usages?.add(new SymbolUsage(SymbolUsageType.read, expr.span)); + var ref = _scope!.resolve(expr.name); + ref?.value?.usages.add(SymbolUsage(SymbolUsageType.read, expr.span)); } return expr; diff --git a/packages/jael/jael_language_server/lib/src/object.dart b/packages/jael/jael_language_server/lib/src/object.dart index d91f31aa..79b2e867 100644 --- a/packages/jael/jael_language_server/lib/src/object.dart +++ b/packages/jael/jael_language_server/lib/src/object.dart @@ -11,13 +11,15 @@ abstract class JaelObject { } class JaelCustomElement extends JaelObject { + @override final String name; - final attributes = new SplayTreeSet(); + final attributes = SplayTreeSet(); JaelCustomElement(this.name, FileSpan span) : super(span); } class JaelVariable extends JaelObject { + @override final String name; JaelVariable(this.name, FileSpan span) : super(span); } diff --git a/packages/jael/jael_language_server/lib/src/protocol/language_server/interface.dart b/packages/jael/jael_language_server/lib/src/protocol/language_server/interface.dart index d9e3b222..74d3cdc5 100644 --- a/packages/jael/jael_language_server/lib/src/protocol/language_server/interface.dart +++ b/packages/jael/jael_language_server/lib/src/protocol/language_server/interface.dart @@ -13,8 +13,8 @@ abstract class LanguageServer { _onDone.complete(); } - Future initialize(int clientPid, String rootUri, - ClientCapabilities clientCapabilities, String trace) async => + Future initialize(int? clientPid, String? rootUri, + ClientCapabilities clientCapabilities, String? trace) async => ServerCapabilities((b) => b); void initialized() {} void textDocumentDidOpen(TextDocumentItem document) {} @@ -24,7 +24,7 @@ abstract class LanguageServer { Future textDocumentCompletion( TextDocumentIdentifier documentId, Position position) async => CompletionList((b) => b); - Future textDocumentDefinition( + Future textDocumentDefinition( TextDocumentIdentifier documentId, Position position) async => null; Future> textDocumentReferences( @@ -41,7 +41,7 @@ abstract class LanguageServer { Future> textDocumentSymbols( TextDocumentIdentifier documentId) async => []; - Future> workspaceSymbol(String query) async => []; + Future> workspaceSymbol(String? query) async => []; Future textDocumentHover( TextDocumentIdentifier documentId, Position position) async => null; @@ -51,13 +51,13 @@ abstract class LanguageServer { CodeActionContext context) async => []; Future workspaceExecuteCommand( - String command, List arguments) async {} - Future textDocumentRename(TextDocumentIdentifier documentId, - Position position, String newName) async => + String? command, List? arguments) async {} + Future textDocumentRename(TextDocumentIdentifier documentId, + Position position, String? newName) async => null; Stream get diagnostics => Stream.empty(); Stream get workspaceEdits => Stream.empty(); - Stream get showMessages => Stream.empty(); + Stream? get showMessages => Stream.empty(); Stream get logMessages => Stream.empty(); void setupExtraMethods(Peer peer) {} diff --git a/packages/jael/jael_language_server/lib/src/protocol/language_server/messages.dart b/packages/jael/jael_language_server/lib/src/protocol/language_server/messages.dart index d07341cb..cd8e1147 100644 --- a/packages/jael/jael_language_server/lib/src/protocol/language_server/messages.dart +++ b/packages/jael/jael_language_server/lib/src/protocol/language_server/messages.dart @@ -14,12 +14,12 @@ class ApplyWorkspaceEditParams { ? WorkspaceEdit.fromJson((params['edit'] as Map)) : null, params.containsKey('label') && params['label'] != null - ? (params['label'] as String) + ? (params['label'] as String?) : null); - final WorkspaceEdit edit; + final WorkspaceEdit? edit; - final String label; + final String? label; Map toJson() => {'edit': edit?.toJson(), 'label': label}; @override @@ -40,9 +40,9 @@ class ApplyWorkspaceEditParams { class ApplyWorkspaceEditParams$Builder { ApplyWorkspaceEditParams$Builder._(); - WorkspaceEdit edit; + WorkspaceEdit? edit; - String label; + String? label; } class ClientCapabilities { @@ -63,9 +63,9 @@ class ClientCapabilities { ? WorkspaceClientCapabilities.fromJson((params['workspace'] as Map)) : null); - final TextDocumentClientCapabilities textDocument; + final TextDocumentClientCapabilities? textDocument; - final WorkspaceClientCapabilities workspace; + final WorkspaceClientCapabilities? workspace; Map toJson() => { 'textDocument': textDocument?.toJson(), @@ -89,9 +89,9 @@ class ClientCapabilities { class ClientCapabilities$Builder { ClientCapabilities$Builder._(); - TextDocumentClientCapabilities textDocument; + TextDocumentClientCapabilities? textDocument; - WorkspaceClientCapabilities workspace; + WorkspaceClientCapabilities? workspace; } class CodeAction { @@ -117,25 +117,25 @@ class CodeAction { ? WorkspaceEdit.fromJson((params['edit'] as Map)) : null, params.containsKey('kind') && params['kind'] != null - ? (params['kind'] as String) + ? (params['kind'] as String?) : null, params.containsKey('title') && params['title'] != null - ? (params['title'] as String) + ? (params['title'] as String?) : null); - final Command command; + final Command? command; - final List diagnostics; + final List? diagnostics; - final WorkspaceEdit edit; + final WorkspaceEdit? edit; - final String kind; + final String? kind; - final String title; + final String? title; Map toJson() => { 'command': command?.toJson(), - 'diagnostics': diagnostics?.map((v) => v?.toJson())?.toList(), + 'diagnostics': diagnostics?.map((v) => v.toJson()).toList(), 'edit': edit?.toJson(), 'kind': kind, 'title': title @@ -164,15 +164,15 @@ class CodeAction { class CodeAction$Builder { CodeAction$Builder._(); - Command command; + Command? command; - List diagnostics; + List? diagnostics; - WorkspaceEdit edit; + WorkspaceEdit? edit; - String kind; + String? kind; - String title; + String? title; } class CodeActionCapabilities { @@ -196,12 +196,12 @@ class CodeActionCapabilities { : null, params.containsKey('dynamicRegistration') && params['dynamicRegistration'] != null - ? (params['dynamicRegistration'] as bool) + ? (params['dynamicRegistration'] as bool?) : null); - final CodeActionLiteralSupport codeActionLiteralSupport; + final CodeActionLiteralSupport? codeActionLiteralSupport; - final bool dynamicRegistration; + final bool? dynamicRegistration; Map toJson() => { 'codeActionLiteralSupport': codeActionLiteralSupport?.toJson(), @@ -225,9 +225,9 @@ class CodeActionCapabilities { class CodeActionCapabilities$Builder { CodeActionCapabilities$Builder._(); - CodeActionLiteralSupport codeActionLiteralSupport; + CodeActionLiteralSupport? codeActionLiteralSupport; - bool dynamicRegistration; + bool? dynamicRegistration; } class CodeActionContext { @@ -246,10 +246,10 @@ class CodeActionContext { .toList() : null); - final List diagnostics; + final List? diagnostics; Map toJson() => - {'diagnostics': diagnostics?.map((v) => v?.toJson())?.toList()}; + {'diagnostics': diagnostics?.map((v) => v.toJson()).toList()}; @override int get hashCode { var hash = 698635161; @@ -265,7 +265,7 @@ class CodeActionContext { class CodeActionContext$Builder { CodeActionContext$Builder._(); - List diagnostics; + List? diagnostics; } class CodeActionKinds { @@ -282,7 +282,7 @@ class CodeActionKinds { ? (params['valueSet'] as List).cast() : null); - final List valueSet; + final List? valueSet; Map toJson() => {'valueSet': valueSet}; @override @@ -300,7 +300,7 @@ class CodeActionKinds { class CodeActionKinds$Builder { CodeActionKinds$Builder._(); - List valueSet; + List? valueSet; } class CodeActionLiteralSupport { @@ -319,7 +319,7 @@ class CodeActionLiteralSupport { ? CodeActionKinds.fromJson((params['codeActionKind'] as Map)) : null); - final CodeActionKinds codeActionKind; + final CodeActionKinds? codeActionKind; Map toJson() => {'codeActionKind': codeActionKind?.toJson()}; @override @@ -338,7 +338,7 @@ class CodeActionLiteralSupport { class CodeActionLiteralSupport$Builder { CodeActionLiteralSupport$Builder._(); - CodeActionKinds codeActionKind; + CodeActionKinds? codeActionKind; } class CodeLensOptions { @@ -352,10 +352,10 @@ class CodeLensOptions { factory CodeLensOptions.fromJson(Map params) => CodeLensOptions._( params.containsKey('resolveProvider') && params['resolveProvider'] != null - ? (params['resolveProvider'] as bool) + ? (params['resolveProvider'] as bool?) : null); - final bool resolveProvider; + final bool? resolveProvider; Map toJson() => {'resolveProvider': resolveProvider}; @override @@ -373,7 +373,7 @@ class CodeLensOptions { class CodeLensOptions$Builder { CodeLensOptions$Builder._(); - bool resolveProvider; + bool? resolveProvider; } class Command { @@ -390,17 +390,17 @@ class Command { ? (params['arguments'] as List).cast() : null, params.containsKey('command') && params['command'] != null - ? (params['command'] as String) + ? (params['command'] as String?) : null, params.containsKey('title') && params['title'] != null - ? (params['title'] as String) + ? (params['title'] as String?) : null); - final List arguments; + final List? arguments; - final String command; + final String? command; - final String title; + final String? title; Map toJson() => {'arguments': arguments, 'command': command, 'title': title}; @override @@ -423,11 +423,11 @@ class Command { class Command$Builder { Command$Builder._(); - List arguments; + List? arguments; - String command; + String? command; - String title; + String? title; } class CompletionCapabilities { @@ -449,12 +449,12 @@ class CompletionCapabilities { : null, params.containsKey('dynamicRegistration') && params['dynamicRegistration'] != null - ? (params['dynamicRegistration'] as bool) + ? (params['dynamicRegistration'] as bool?) : null); - final CompletionItemCapabilities completionItem; + final CompletionItemCapabilities? completionItem; - final bool dynamicRegistration; + final bool? dynamicRegistration; Map toJson() => { 'completionItem': completionItem?.toJson(), @@ -478,9 +478,9 @@ class CompletionCapabilities { class CompletionCapabilities$Builder { CompletionCapabilities$Builder._(); - CompletionItemCapabilities completionItem; + CompletionItemCapabilities? completionItem; - bool dynamicRegistration; + bool? dynamicRegistration; } class CompletionItem { @@ -530,61 +530,61 @@ class CompletionItem { ? (params['data'] as dynamic) : null, params.containsKey('detail') && params['detail'] != null - ? (params['detail'] as String) + ? (params['detail'] as String?) : null, params.containsKey('documentation') && params['documentation'] != null - ? (params['documentation'] as String) + ? (params['documentation'] as String?) : null, params.containsKey('filterText') && params['filterText'] != null - ? (params['filterText'] as String) + ? (params['filterText'] as String?) : null, params.containsKey('insertText') && params['insertText'] != null - ? (params['insertText'] as String) + ? (params['insertText'] as String?) : null, params.containsKey('insertTextFormat') && params['insertTextFormat'] != null - ? InsertTextFormat.fromJson((params['insertTextFormat'] as int)) + ? InsertTextFormat.fromJson((params['insertTextFormat'] as int?)) : null, params.containsKey('kind') && params['kind'] != null - ? CompletionItemKind.fromJson((params['kind'] as int)) + ? CompletionItemKind.fromJson((params['kind'] as int?)) : null, params.containsKey('label') && params['label'] != null - ? (params['label'] as String) + ? (params['label'] as String?) : null, params.containsKey('sortText') && params['sortText'] != null - ? (params['sortText'] as String) + ? (params['sortText'] as String?) : null, params.containsKey('textEdit') && params['textEdit'] != null ? TextEdit.fromJson((params['textEdit'] as Map)) : null); - final List additionalTextEdits; + final List? additionalTextEdits; - final Command command; + final Command? command; final dynamic data; - final String detail; + final String? detail; - final String documentation; + final String? documentation; - final String filterText; + final String? filterText; - final String insertText; + final String? insertText; - final InsertTextFormat insertTextFormat; + final InsertTextFormat? insertTextFormat; - final CompletionItemKind kind; + final CompletionItemKind? kind; - final String label; + final String? label; - final String sortText; + final String? sortText; - final TextEdit textEdit; + final TextEdit? textEdit; Map toJson() => { 'additionalTextEdits': - additionalTextEdits?.map((v) => v?.toJson())?.toList(), + additionalTextEdits?.map((v) => v.toJson()).toList(), 'command': command?.toJson(), 'data': data, 'detail': detail, @@ -635,29 +635,29 @@ class CompletionItem { class CompletionItem$Builder { CompletionItem$Builder._(); - List additionalTextEdits; + List? additionalTextEdits; - Command command; + Command? command; dynamic data; - String detail; + String? detail; - String documentation; + String? documentation; - String filterText; + String? filterText; - String insertText; + String? insertText; - InsertTextFormat insertTextFormat; + InsertTextFormat? insertTextFormat; - CompletionItemKind kind; + CompletionItemKind? kind; - String label; + String? label; - String sortText; + String? sortText; - TextEdit textEdit; + TextEdit? textEdit; } class CompletionItemCapabilities { @@ -673,10 +673,10 @@ class CompletionItemCapabilities { factory CompletionItemCapabilities.fromJson(Map params) => CompletionItemCapabilities._(params.containsKey('snippetSupport') && params['snippetSupport'] != null - ? (params['snippetSupport'] as bool) + ? (params['snippetSupport'] as bool?) : null); - final bool snippetSupport; + final bool? snippetSupport; Map toJson() => {'snippetSupport': snippetSupport}; @override @@ -695,11 +695,11 @@ class CompletionItemCapabilities { class CompletionItemCapabilities$Builder { CompletionItemCapabilities$Builder._(); - bool snippetSupport; + bool? snippetSupport; } class CompletionItemKind { - factory CompletionItemKind.fromJson(int value) { + factory CompletionItemKind.fromJson(int? value) { const values = { 7: CompletionItemKind.classKind, 16: CompletionItemKind.color, @@ -720,7 +720,7 @@ class CompletionItemKind { 12: CompletionItemKind.value, 6: CompletionItemKind.variable }; - return values[value]; + return values[value!]!; } const CompletionItemKind._(this._value); @@ -777,7 +777,7 @@ class CompletionList { factory CompletionList.fromJson(Map params) => CompletionList._( params.containsKey('isIncomplete') && params['isIncomplete'] != null - ? (params['isIncomplete'] as bool) + ? (params['isIncomplete'] as bool?) : null, params.containsKey('items') && params['items'] != null ? (params['items'] as List) @@ -785,13 +785,13 @@ class CompletionList { .toList() : null); - final bool isIncomplete; + final bool? isIncomplete; - final List items; + final List? items; Map toJson() => { 'isIncomplete': isIncomplete, - 'items': items?.map((v) => v?.toJson())?.toList() + 'items': items?.map((v) => v?.toJson()).toList() }; @override int get hashCode { @@ -811,9 +811,9 @@ class CompletionList { class CompletionList$Builder { CompletionList$Builder._(); - bool isIncomplete; + bool? isIncomplete; - List items; + List? items; } class CompletionOptions { @@ -827,16 +827,16 @@ class CompletionOptions { factory CompletionOptions.fromJson(Map params) => CompletionOptions._( params.containsKey('resolveProvider') && params['resolveProvider'] != null - ? (params['resolveProvider'] as bool) + ? (params['resolveProvider'] as bool?) : null, params.containsKey('triggerCharacters') && params['triggerCharacters'] != null ? (params['triggerCharacters'] as List).cast() : null); - final bool resolveProvider; + final bool? resolveProvider; - final List triggerCharacters; + final List? triggerCharacters; Map toJson() => { 'resolveProvider': resolveProvider, @@ -860,9 +860,9 @@ class CompletionOptions { class CompletionOptions$Builder { CompletionOptions$Builder._(); - bool resolveProvider; + bool? resolveProvider; - List triggerCharacters; + List? triggerCharacters; } class Diagnostic { @@ -879,27 +879,27 @@ class Diagnostic { ? (params['code'] as dynamic) : null, params.containsKey('message') && params['message'] != null - ? (params['message'] as String) + ? (params['message'] as String?) : null, params.containsKey('range') && params['range'] != null ? Range.fromJson((params['range'] as Map)) : null, params.containsKey('severity') && params['severity'] != null - ? (params['severity'] as int) + ? (params['severity'] as int?) : null, params.containsKey('source') && params['source'] != null - ? (params['source'] as String) + ? (params['source'] as String?) : null); final dynamic code; - final String message; + final String? message; - final Range range; + final Range? range; - final int severity; + final int? severity; - final String source; + final String? source; Map toJson() => { 'code': code, @@ -934,13 +934,13 @@ class Diagnostic$Builder { dynamic code; - String message; + String? message; - Range range; + Range? range; - int severity; + int? severity; - String source; + String? source; } class Diagnostics { @@ -959,15 +959,15 @@ class Diagnostics { .toList() : null, params.containsKey('uri') && params['uri'] != null - ? (params['uri'] as String) + ? (params['uri'] as String?) : null); - final List diagnostics; + final List? diagnostics; - final String uri; + final String? uri; Map toJson() => { - 'diagnostics': diagnostics?.map((v) => v?.toJson())?.toList(), + 'diagnostics': diagnostics?.map((v) => v.toJson()).toList(), 'uri': uri }; @override @@ -988,9 +988,9 @@ class Diagnostics { class Diagnostics$Builder { Diagnostics$Builder._(); - List diagnostics; + List? diagnostics; - String uri; + String? uri; } class DocumentHighlight { @@ -1004,15 +1004,15 @@ class DocumentHighlight { factory DocumentHighlight.fromJson(Map params) => DocumentHighlight._( params.containsKey('kind') && params['kind'] != null - ? DocumentHighlightKind.fromJson((params['kind'] as int)) + ? DocumentHighlightKind.fromJson((params['kind'] as int?)) : null, params.containsKey('range') && params['range'] != null ? Range.fromJson((params['range'] as Map)) : null); - final DocumentHighlightKind kind; + final DocumentHighlightKind? kind; - final Range range; + final Range? range; Map toJson() => {'kind': kind?.toJson(), 'range': range?.toJson()}; @override @@ -1031,19 +1031,19 @@ class DocumentHighlight { class DocumentHighlight$Builder { DocumentHighlight$Builder._(); - DocumentHighlightKind kind; + DocumentHighlightKind? kind; - Range range; + Range? range; } class DocumentHighlightKind { - factory DocumentHighlightKind.fromJson(int value) { + factory DocumentHighlightKind.fromJson(int? value) { const values = { 2: DocumentHighlightKind.read, 1: DocumentHighlightKind.text, 3: DocumentHighlightKind.write }; - return values[value]; + return values[value!]!; } const DocumentHighlightKind._(this._value); @@ -1070,10 +1070,10 @@ class DocumentLinkOptions { factory DocumentLinkOptions.fromJson(Map params) => DocumentLinkOptions._( params.containsKey('resolveProvider') && params['resolveProvider'] != null - ? (params['resolveProvider'] as bool) + ? (params['resolveProvider'] as bool?) : null); - final bool resolveProvider; + final bool? resolveProvider; Map toJson() => {'resolveProvider': resolveProvider}; @override @@ -1091,7 +1091,7 @@ class DocumentLinkOptions { class DocumentLinkOptions$Builder { DocumentLinkOptions$Builder._(); - bool resolveProvider; + bool? resolveProvider; } class DocumentOnTypeFormattingOptions { @@ -1110,16 +1110,16 @@ class DocumentOnTypeFormattingOptions { DocumentOnTypeFormattingOptions._( params.containsKey('firstTriggerCharacter') && params['firstTriggerCharacter'] != null - ? (params['firstTriggerCharacter'] as String) + ? (params['firstTriggerCharacter'] as String?) : null, params.containsKey('moreTriggerCharacter') && params['moreTriggerCharacter'] != null ? (params['moreTriggerCharacter'] as List).cast() : null); - final String firstTriggerCharacter; + final String? firstTriggerCharacter; - final List moreTriggerCharacter; + final List? moreTriggerCharacter; Map toJson() => { 'firstTriggerCharacter': firstTriggerCharacter, @@ -1143,9 +1143,9 @@ class DocumentOnTypeFormattingOptions { class DocumentOnTypeFormattingOptions$Builder { DocumentOnTypeFormattingOptions$Builder._(); - String firstTriggerCharacter; + String? firstTriggerCharacter; - List moreTriggerCharacter; + List? moreTriggerCharacter; } class DynamicRegistrationCapability { @@ -1162,10 +1162,10 @@ class DynamicRegistrationCapability { DynamicRegistrationCapability._( params.containsKey('dynamicRegistration') && params['dynamicRegistration'] != null - ? (params['dynamicRegistration'] as bool) + ? (params['dynamicRegistration'] as bool?) : null); - final bool dynamicRegistration; + final bool? dynamicRegistration; Map toJson() => {'dynamicRegistration': dynamicRegistration}; @override @@ -1184,7 +1184,7 @@ class DynamicRegistrationCapability { class DynamicRegistrationCapability$Builder { DynamicRegistrationCapability$Builder._(); - bool dynamicRegistration; + bool? dynamicRegistration; } class ExecuteCommandOptions { @@ -1202,7 +1202,7 @@ class ExecuteCommandOptions { ? (params['commands'] as List).cast() : null); - final List commands; + final List? commands; Map toJson() => {'commands': commands}; @override @@ -1220,7 +1220,7 @@ class ExecuteCommandOptions { class ExecuteCommandOptions$Builder { ExecuteCommandOptions$Builder._(); - List commands; + List? commands; } class Hover { @@ -1234,15 +1234,15 @@ class Hover { factory Hover.fromJson(Map params) => Hover._( params.containsKey('contents') && params['contents'] != null - ? (params['contents'] as String) + ? (params['contents'] as String?) : null, params.containsKey('range') && params['range'] != null ? Range.fromJson((params['range'] as Map)) : null); - final String contents; + final String? contents; - final Range range; + final Range? range; Map toJson() => {'contents': contents, 'range': range?.toJson()}; @override @@ -1261,9 +1261,9 @@ class Hover { class Hover$Builder { Hover$Builder._(); - String contents; + String? contents; - Range range; + Range? range; } class HoverCapabilities { @@ -1281,12 +1281,12 @@ class HoverCapabilities { : null, params.containsKey('dynamicRegistration') && params['dynamicRegistration'] != null - ? (params['dynamicRegistration'] as bool) + ? (params['dynamicRegistration'] as bool?) : null); - final List contentFormat; + final List? contentFormat; - final bool dynamicRegistration; + final bool? dynamicRegistration; Map toJson() => { 'contentFormat': contentFormat, @@ -1310,9 +1310,9 @@ class HoverCapabilities { class HoverCapabilities$Builder { HoverCapabilities$Builder._(); - List contentFormat; + List? contentFormat; - bool dynamicRegistration; + bool? dynamicRegistration; } class HoverMarkup { @@ -1332,9 +1332,9 @@ class HoverMarkup { ? Range.fromJson((params['range'] as Map)) : null); - final MarkupContent contents; + final MarkupContent? contents; - final Range range; + final Range? range; Map toJson() => {'contents': contents?.toJson(), 'range': range?.toJson()}; @override @@ -1355,15 +1355,15 @@ class HoverMarkup { class HoverMarkup$Builder { HoverMarkup$Builder._(); - MarkupContent contents; + MarkupContent? contents; - Range range; + Range? range; } class InsertTextFormat { - factory InsertTextFormat.fromJson(int value) { + factory InsertTextFormat.fromJson(int? value) { const values = {1: InsertTextFormat.plainText, 2: InsertTextFormat.snippet}; - return values[value]; + return values[value!]!; } const InsertTextFormat._(this._value); @@ -1391,12 +1391,12 @@ class Location { ? Range.fromJson((params['range'] as Map)) : null, params.containsKey('uri') && params['uri'] != null - ? (params['uri'] as String) + ? (params['uri'] as String?) : null); - final Range range; + final Range? range; - final String uri; + final String? uri; Map toJson() => {'range': range?.toJson(), 'uri': uri}; @override @@ -1415,9 +1415,9 @@ class Location { class Location$Builder { Location$Builder._(); - Range range; + Range? range; - String uri; + String? uri; } class MarkupContent { @@ -1431,15 +1431,15 @@ class MarkupContent { factory MarkupContent.fromJson(Map params) => MarkupContent._( params.containsKey('kind') && params['kind'] != null - ? MarkupContentKind.fromJson((params['kind'] as String)) + ? MarkupContentKind.fromJson((params['kind'] as String?)) : null, params.containsKey('value') && params['value'] != null - ? (params['value'] as String) + ? (params['value'] as String?) : null); - final MarkupContentKind kind; + final MarkupContentKind? kind; - final String value; + final String? value; Map toJson() => {'kind': kind?.toJson(), 'value': value}; @override @@ -1458,18 +1458,18 @@ class MarkupContent { class MarkupContent$Builder { MarkupContent$Builder._(); - MarkupContentKind kind; + MarkupContentKind? kind; - String value; + String? value; } class MarkupContentKind { - factory MarkupContentKind.fromJson(String value) { + factory MarkupContentKind.fromJson(String? value) { const values = { 'markdown': MarkupContentKind.markdown, 'plaintext': MarkupContentKind.plaintext }; - return values[value]; + return values[value!]!; } const MarkupContentKind._(this._value); @@ -1484,14 +1484,14 @@ class MarkupContentKind { } class MessageType { - factory MessageType.fromJson(int value) { + factory MessageType.fromJson(int? value) { const values = { 1: MessageType.error, 3: MessageType.info, 4: MessageType.log, 2: MessageType.warning }; - return values[value]; + return values[value!]!; } const MessageType._(this._value); @@ -1520,15 +1520,15 @@ class Position { factory Position.fromJson(Map params) => Position._( params.containsKey('character') && params['character'] != null - ? (params['character'] as int) + ? (params['character'] as int?) : null, params.containsKey('line') && params['line'] != null - ? (params['line'] as int) + ? (params['line'] as int?) : null); - final int character; + final int? character; - final int line; + final int? line; Map toJson() => {'character': character, 'line': line}; @override @@ -1547,9 +1547,9 @@ class Position { class Position$Builder { Position$Builder._(); - int character; + int? character; - int line; + int? line; } class Range { @@ -1569,9 +1569,9 @@ class Range { ? Position.fromJson((params['start'] as Map)) : null); - final Position end; + final Position? end; - final Position start; + final Position? start; Map toJson() => {'end': end?.toJson(), 'start': start?.toJson()}; @override @@ -1590,9 +1590,9 @@ class Range { class Range$Builder { Range$Builder._(); - Position end; + Position? end; - Position start; + Position? start; } class ReferenceContext { @@ -1607,10 +1607,10 @@ class ReferenceContext { factory ReferenceContext.fromJson(Map params) => ReferenceContext._(params.containsKey('includeDeclaration') && params['includeDeclaration'] != null - ? (params['includeDeclaration'] as bool) + ? (params['includeDeclaration'] as bool?) : null); - final bool includeDeclaration; + final bool? includeDeclaration; Map toJson() => {'includeDeclaration': includeDeclaration}; @override @@ -1629,7 +1629,7 @@ class ReferenceContext { class ReferenceContext$Builder { ReferenceContext$Builder._(); - bool includeDeclaration; + bool? includeDeclaration; } class SaveOptions { @@ -1643,10 +1643,10 @@ class SaveOptions { factory SaveOptions.fromJson(Map params) => SaveOptions._( params.containsKey('includeText') && params['includeText'] != null - ? (params['includeText'] as bool) + ? (params['includeText'] as bool?) : null); - final bool includeText; + final bool? includeText; Map toJson() => {'includeText': includeText}; @override @@ -1664,7 +1664,7 @@ class SaveOptions { class SaveOptions$Builder { SaveOptions$Builder._(); - bool includeText; + bool? includeText; } class ServerCapabilities { @@ -1714,7 +1714,7 @@ class ServerCapabilities { factory ServerCapabilities.fromJson(Map params) => ServerCapabilities._( params.containsKey('codeActionProvider') && params['codeActionProvider'] != null - ? (params['codeActionProvider'] as bool) + ? (params['codeActionProvider'] as bool?) : null, params.containsKey('codeLensProvider') && params['codeLensProvider'] != null ? CodeLensOptions.fromJson((params['codeLensProvider'] as Map)) @@ -1723,13 +1723,13 @@ class ServerCapabilities { ? CompletionOptions.fromJson((params['completionProvider'] as Map)) : null, params.containsKey('definitionProvider') && params['definitionProvider'] != null - ? (params['definitionProvider'] as bool) + ? (params['definitionProvider'] as bool?) : null, params.containsKey('documentFormattingProvider') && params['documentFormattingProvider'] != null - ? (params['documentFormattingProvider'] as bool) + ? (params['documentFormattingProvider'] as bool?) : null, params.containsKey('documentHighlightProvider') && params['documentHighlightProvider'] != null - ? (params['documentHighlightProvider'] as bool) + ? (params['documentHighlightProvider'] as bool?) : null, params.containsKey('documentLinkProvider') && params['documentLinkProvider'] != null ? DocumentLinkOptions.fromJson( @@ -1740,57 +1740,57 @@ class ServerCapabilities { (params['documentOnTypeFormattingProvider'] as Map)) : null, params.containsKey('documentRangeFormattingProvider') && params['documentRangeFormattingProvider'] != null - ? (params['documentRangeFormattingProvider'] as bool) + ? (params['documentRangeFormattingProvider'] as bool?) : null, params.containsKey('documentSymbolProvider') && params['documentSymbolProvider'] != null - ? (params['documentSymbolProvider'] as bool) + ? (params['documentSymbolProvider'] as bool?) : null, params.containsKey('executeCommandProvider') && params['executeCommandProvider'] != null ? ExecuteCommandOptions.fromJson((params['executeCommandProvider'] as Map)) : null, - params.containsKey('hoverProvider') && params['hoverProvider'] != null ? (params['hoverProvider'] as bool) : null, - params.containsKey('implementationProvider') && params['implementationProvider'] != null ? (params['implementationProvider'] as bool) : null, - params.containsKey('referencesProvider') && params['referencesProvider'] != null ? (params['referencesProvider'] as bool) : null, - params.containsKey('renameProvider') && params['renameProvider'] != null ? (params['renameProvider'] as bool) : null, + params.containsKey('hoverProvider') && params['hoverProvider'] != null ? (params['hoverProvider'] as bool?) : null, + params.containsKey('implementationProvider') && params['implementationProvider'] != null ? (params['implementationProvider'] as bool?) : null, + params.containsKey('referencesProvider') && params['referencesProvider'] != null ? (params['referencesProvider'] as bool?) : null, + params.containsKey('renameProvider') && params['renameProvider'] != null ? (params['renameProvider'] as bool?) : null, params.containsKey('signatureHelpProvider') && params['signatureHelpProvider'] != null ? SignatureHelpOptions.fromJson((params['signatureHelpProvider'] as Map)) : null, params.containsKey('textDocumentSync') && params['textDocumentSync'] != null ? TextDocumentSyncOptions.fromJson((params['textDocumentSync'] as Map)) : null, - params.containsKey('workspaceSymbolProvider') && params['workspaceSymbolProvider'] != null ? (params['workspaceSymbolProvider'] as bool) : null); + params.containsKey('workspaceSymbolProvider') && params['workspaceSymbolProvider'] != null ? (params['workspaceSymbolProvider'] as bool?) : null); - final bool codeActionProvider; + final bool? codeActionProvider; - final CodeLensOptions codeLensProvider; + final CodeLensOptions? codeLensProvider; - final CompletionOptions completionProvider; + final CompletionOptions? completionProvider; - final bool definitionProvider; + final bool? definitionProvider; - final bool documentFormattingProvider; + final bool? documentFormattingProvider; - final bool documentHighlightProvider; + final bool? documentHighlightProvider; - final DocumentLinkOptions documentLinkProvider; + final DocumentLinkOptions? documentLinkProvider; - final DocumentOnTypeFormattingOptions documentOnTypeFormattingProvider; + final DocumentOnTypeFormattingOptions? documentOnTypeFormattingProvider; - final bool documentRangeFormattingProvider; + final bool? documentRangeFormattingProvider; - final bool documentSymbolProvider; + final bool? documentSymbolProvider; - final ExecuteCommandOptions executeCommandProvider; + final ExecuteCommandOptions? executeCommandProvider; - final bool hoverProvider; + final bool? hoverProvider; - final bool implementationProvider; + final bool? implementationProvider; - final bool referencesProvider; + final bool? referencesProvider; - final bool renameProvider; + final bool? renameProvider; - final SignatureHelpOptions signatureHelpProvider; + final SignatureHelpOptions? signatureHelpProvider; - final TextDocumentSyncOptions textDocumentSync; + final TextDocumentSyncOptions? textDocumentSync; - final bool workspaceSymbolProvider; + final bool? workspaceSymbolProvider; Map toJson() => { 'codeActionProvider': codeActionProvider, @@ -1865,41 +1865,41 @@ class ServerCapabilities { class ServerCapabilities$Builder { ServerCapabilities$Builder._(); - bool codeActionProvider; + bool? codeActionProvider; - CodeLensOptions codeLensProvider; + CodeLensOptions? codeLensProvider; - CompletionOptions completionProvider; + CompletionOptions? completionProvider; - bool definitionProvider; + bool? definitionProvider; - bool documentFormattingProvider; + bool? documentFormattingProvider; - bool documentHighlightProvider; + bool? documentHighlightProvider; - DocumentLinkOptions documentLinkProvider; + DocumentLinkOptions? documentLinkProvider; - DocumentOnTypeFormattingOptions documentOnTypeFormattingProvider; + DocumentOnTypeFormattingOptions? documentOnTypeFormattingProvider; - bool documentRangeFormattingProvider; + bool? documentRangeFormattingProvider; - bool documentSymbolProvider; + bool? documentSymbolProvider; - ExecuteCommandOptions executeCommandProvider; + ExecuteCommandOptions? executeCommandProvider; - bool hoverProvider; + bool? hoverProvider; - bool implementationProvider; + bool? implementationProvider; - bool referencesProvider; + bool? referencesProvider; - bool renameProvider; + bool? renameProvider; - SignatureHelpOptions signatureHelpProvider; + SignatureHelpOptions? signatureHelpProvider; - TextDocumentSyncOptions textDocumentSync; + TextDocumentSyncOptions? textDocumentSync; - bool workspaceSymbolProvider; + bool? workspaceSymbolProvider; } class ShowMessageParams { @@ -1913,15 +1913,15 @@ class ShowMessageParams { factory ShowMessageParams.fromJson(Map params) => ShowMessageParams._( params.containsKey('message') && params['message'] != null - ? (params['message'] as String) + ? (params['message'] as String?) : null, params.containsKey('type') && params['type'] != null - ? MessageType.fromJson((params['type'] as int)) + ? MessageType.fromJson((params['type'] as int?)) : null); - final String message; + final String? message; - final MessageType type; + final MessageType? type; Map toJson() => {'message': message, 'type': type?.toJson()}; @override @@ -1942,9 +1942,9 @@ class ShowMessageParams { class ShowMessageParams$Builder { ShowMessageParams$Builder._(); - String message; + String? message; - MessageType type; + MessageType? type; } class SignatureHelpOptions { @@ -1963,7 +1963,7 @@ class SignatureHelpOptions { ? (params['triggerCharacters'] as List).cast() : null); - final List triggerCharacters; + final List? triggerCharacters; Map toJson() => {'triggerCharacters': triggerCharacters}; @override @@ -1982,7 +1982,7 @@ class SignatureHelpOptions { class SignatureHelpOptions$Builder { SignatureHelpOptions$Builder._(); - List triggerCharacters; + List? triggerCharacters; } class SymbolInformation { @@ -1996,25 +1996,25 @@ class SymbolInformation { factory SymbolInformation.fromJson(Map params) => SymbolInformation._( params.containsKey('containerName') && params['containerName'] != null - ? (params['containerName'] as String) + ? (params['containerName'] as String?) : null, params.containsKey('kind') && params['kind'] != null - ? SymbolKind.fromJson((params['kind'] as int)) + ? SymbolKind.fromJson((params['kind'] as int?)) : null, params.containsKey('location') && params['location'] != null ? Location.fromJson((params['location'] as Map)) : null, params.containsKey('name') && params['name'] != null - ? (params['name'] as String) + ? (params['name'] as String?) : null); - final String containerName; + final String? containerName; - final SymbolKind kind; + final SymbolKind? kind; - final Location location; + final Location? location; - final String name; + final String? name; Map toJson() => { 'containerName': containerName, @@ -2044,17 +2044,17 @@ class SymbolInformation { class SymbolInformation$Builder { SymbolInformation$Builder._(); - String containerName; + String? containerName; - SymbolKind kind; + SymbolKind? kind; - Location location; + Location? location; - String name; + String? name; } class SymbolKind { - factory SymbolKind.fromJson(int value) { + factory SymbolKind.fromJson(int? value) { const values = { 18: SymbolKind.array, 17: SymbolKind.boolean, @@ -2083,7 +2083,7 @@ class SymbolKind { 26: SymbolKind.typeParameter, 13: SymbolKind.variable }; - return values[value]; + return values[value!]!; } const SymbolKind._(this._value); @@ -2161,27 +2161,27 @@ class SynchronizationCapabilities { Map params) => SynchronizationCapabilities._( params.containsKey('didSave') && params['didSave'] != null - ? (params['didSave'] as bool) + ? (params['didSave'] as bool?) : null, params.containsKey('dynamicRegistration') && params['dynamicRegistration'] != null - ? (params['dynamicRegistration'] as bool) + ? (params['dynamicRegistration'] as bool?) : null, params.containsKey('willSave') && params['willSave'] != null - ? (params['willSave'] as bool) + ? (params['willSave'] as bool?) : null, params.containsKey('willSaveWaitUntil') && params['willSaveWaitUntil'] != null - ? (params['willSaveWaitUntil'] as bool) + ? (params['willSaveWaitUntil'] as bool?) : null); - final bool didSave; + final bool? didSave; - final bool dynamicRegistration; + final bool? dynamicRegistration; - final bool willSave; + final bool? willSave; - final bool willSaveWaitUntil; + final bool? willSaveWaitUntil; Map toJson() => { 'didSave': didSave, @@ -2211,13 +2211,13 @@ class SynchronizationCapabilities { class SynchronizationCapabilities$Builder { SynchronizationCapabilities$Builder._(); - bool didSave; + bool? didSave; - bool dynamicRegistration; + bool? dynamicRegistration; - bool willSave; + bool? willSave; - bool willSaveWaitUntil; + bool? willSaveWaitUntil; } class TextDocumentClientCapabilities { @@ -2300,31 +2300,31 @@ class TextDocumentClientCapabilities { params.containsKey('rename') && params['rename'] != null ? DynamicRegistrationCapability.fromJson((params['rename'] as Map)) : null, params.containsKey('synchronization') && params['synchronization'] != null ? SynchronizationCapabilities.fromJson((params['synchronization'] as Map)) : null); - final CodeActionCapabilities codeAction; + final CodeActionCapabilities? codeAction; - final DynamicRegistrationCapability codeLens; + final DynamicRegistrationCapability? codeLens; - final CompletionCapabilities completion; + final CompletionCapabilities? completion; - final DynamicRegistrationCapability definition; + final DynamicRegistrationCapability? definition; - final DynamicRegistrationCapability documentHighlight; + final DynamicRegistrationCapability? documentHighlight; - final DynamicRegistrationCapability documentLink; + final DynamicRegistrationCapability? documentLink; - final DynamicRegistrationCapability documentSymbol; + final DynamicRegistrationCapability? documentSymbol; - final DynamicRegistrationCapability formatting; + final DynamicRegistrationCapability? formatting; - final HoverCapabilities hover; + final HoverCapabilities? hover; - final DynamicRegistrationCapability onTypeFormatting; + final DynamicRegistrationCapability? onTypeFormatting; - final DynamicRegistrationCapability references; + final DynamicRegistrationCapability? references; - final DynamicRegistrationCapability rename; + final DynamicRegistrationCapability? rename; - final SynchronizationCapabilities synchronization; + final SynchronizationCapabilities? synchronization; Map toJson() => { 'codeAction': codeAction?.toJson(), @@ -2381,31 +2381,31 @@ class TextDocumentClientCapabilities { class TextDocumentClientCapabilities$Builder { TextDocumentClientCapabilities$Builder._(); - CodeActionCapabilities codeAction; + CodeActionCapabilities? codeAction; - DynamicRegistrationCapability codeLens; + DynamicRegistrationCapability? codeLens; - CompletionCapabilities completion; + CompletionCapabilities? completion; - DynamicRegistrationCapability definition; + DynamicRegistrationCapability? definition; - DynamicRegistrationCapability documentHighlight; + DynamicRegistrationCapability? documentHighlight; - DynamicRegistrationCapability documentLink; + DynamicRegistrationCapability? documentLink; - DynamicRegistrationCapability documentSymbol; + DynamicRegistrationCapability? documentSymbol; - DynamicRegistrationCapability formatting; + DynamicRegistrationCapability? formatting; - HoverCapabilities hover; + HoverCapabilities? hover; - DynamicRegistrationCapability onTypeFormatting; + DynamicRegistrationCapability? onTypeFormatting; - DynamicRegistrationCapability references; + DynamicRegistrationCapability? references; - DynamicRegistrationCapability rename; + DynamicRegistrationCapability? rename; - SynchronizationCapabilities synchronization; + SynchronizationCapabilities? synchronization; } class TextDocumentContentChangeEvent { @@ -2424,17 +2424,17 @@ class TextDocumentContentChangeEvent { ? Range.fromJson((params['range'] as Map)) : null, params.containsKey('rangeLength') && params['rangeLength'] != null - ? (params['rangeLength'] as int) + ? (params['rangeLength'] as int?) : null, params.containsKey('text') && params['text'] != null - ? (params['text'] as String) + ? (params['text'] as String?) : null); - final Range range; + final Range? range; - final int rangeLength; + final int? rangeLength; - final String text; + final String? text; Map toJson() => {'range': range?.toJson(), 'rangeLength': rangeLength, 'text': text}; @@ -2458,11 +2458,11 @@ class TextDocumentContentChangeEvent { class TextDocumentContentChangeEvent$Builder { TextDocumentContentChangeEvent$Builder._(); - Range range; + Range? range; - int rangeLength; + int? rangeLength; - String text; + String? text; } class TextDocumentIdentifier { @@ -2478,10 +2478,10 @@ class TextDocumentIdentifier { factory TextDocumentIdentifier.fromJson(Map params) => TextDocumentIdentifier._( params.containsKey('uri') && params['uri'] != null - ? (params['uri'] as String) + ? (params['uri'] as String?) : null); - final String uri; + final String? uri; Map toJson() => {'uri': uri}; @override @@ -2499,7 +2499,7 @@ class TextDocumentIdentifier { class TextDocumentIdentifier$Builder { TextDocumentIdentifier$Builder._(); - String uri; + String? uri; } class TextDocumentItem { @@ -2513,25 +2513,25 @@ class TextDocumentItem { factory TextDocumentItem.fromJson(Map params) => TextDocumentItem._( params.containsKey('languageId') && params['languageId'] != null - ? (params['languageId'] as String) + ? (params['languageId'] as String?) : null, params.containsKey('text') && params['text'] != null - ? (params['text'] as String) + ? (params['text'] as String?) : null, params.containsKey('uri') && params['uri'] != null - ? (params['uri'] as String) + ? (params['uri'] as String?) : null, params.containsKey('version') && params['version'] != null - ? (params['version'] as int) + ? (params['version'] as int?) : null); - final String languageId; + final String? languageId; - final String text; + final String? text; - final String uri; + final String? uri; - final int version; + final int? version; Map toJson() => {'languageId': languageId, 'text': text, 'uri': uri, 'version': version}; @@ -2557,23 +2557,23 @@ class TextDocumentItem { class TextDocumentItem$Builder { TextDocumentItem$Builder._(); - String languageId; + String? languageId; - String text; + String? text; - String uri; + String? uri; - int version; + int? version; } class TextDocumentSyncKind { - factory TextDocumentSyncKind.fromJson(int value) { + factory TextDocumentSyncKind.fromJson(int? value) { const values = { 1: TextDocumentSyncKind.full, 2: TextDocumentSyncKind.incremental, 0: TextDocumentSyncKind.none }; - return values[value]; + return values[value!]!; } const TextDocumentSyncKind._(this._value); @@ -2605,31 +2605,31 @@ class TextDocumentSyncOptions { Map params) => TextDocumentSyncOptions._( params.containsKey('change') && params['change'] != null - ? TextDocumentSyncKind.fromJson((params['change'] as int)) + ? TextDocumentSyncKind.fromJson((params['change'] as int?)) : null, params.containsKey('openClose') && params['openClose'] != null - ? (params['openClose'] as bool) + ? (params['openClose'] as bool?) : null, params.containsKey('save') && params['save'] != null ? SaveOptions.fromJson((params['save'] as Map)) : null, params.containsKey('willSave') && params['willSave'] != null - ? (params['willSave'] as bool) + ? (params['willSave'] as bool?) : null, params.containsKey('willSaveWaitUntil') && params['willSaveWaitUntil'] != null - ? (params['willSaveWaitUntil'] as bool) + ? (params['willSaveWaitUntil'] as bool?) : null); - final TextDocumentSyncKind change; + final TextDocumentSyncKind? change; - final bool openClose; + final bool? openClose; - final SaveOptions save; + final SaveOptions? save; - final bool willSave; + final bool? willSave; - final bool willSaveWaitUntil; + final bool? willSaveWaitUntil; Map toJson() => { 'change': change?.toJson(), @@ -2662,15 +2662,15 @@ class TextDocumentSyncOptions { class TextDocumentSyncOptions$Builder { TextDocumentSyncOptions$Builder._(); - TextDocumentSyncKind change; + TextDocumentSyncKind? change; - bool openClose; + bool? openClose; - SaveOptions save; + SaveOptions? save; - bool willSave; + bool? willSave; - bool willSaveWaitUntil; + bool? willSaveWaitUntil; } class TextEdit { @@ -2684,15 +2684,15 @@ class TextEdit { factory TextEdit.fromJson(Map params) => TextEdit._( params.containsKey('newText') && params['newText'] != null - ? (params['newText'] as String) + ? (params['newText'] as String?) : null, params.containsKey('range') && params['range'] != null ? Range.fromJson((params['range'] as Map)) : null); - final String newText; + final String? newText; - final Range range; + final Range? range; Map toJson() => {'newText': newText, 'range': range?.toJson()}; @override @@ -2711,9 +2711,9 @@ class TextEdit { class TextEdit$Builder { TextEdit$Builder._(); - String newText; + String? newText; - Range range; + Range? range; } class VersionedTextDocumentIdentifier { @@ -2729,15 +2729,15 @@ class VersionedTextDocumentIdentifier { factory VersionedTextDocumentIdentifier.fromJson(Map params) => VersionedTextDocumentIdentifier._( params.containsKey('uri') && params['uri'] != null - ? (params['uri'] as String) + ? (params['uri'] as String?) : null, params.containsKey('version') && params['version'] != null - ? (params['version'] as int) + ? (params['version'] as int?) : null); - final String uri; + final String? uri; - final int version; + final int? version; Map toJson() => {'uri': uri, 'version': version}; @override @@ -2758,9 +2758,9 @@ class VersionedTextDocumentIdentifier { class VersionedTextDocumentIdentifier$Builder { VersionedTextDocumentIdentifier$Builder._(); - String uri; + String? uri; - int version; + int? version; } class WorkspaceClientCapabilities { @@ -2779,7 +2779,7 @@ class WorkspaceClientCapabilities { Map params) => WorkspaceClientCapabilities._( params.containsKey('applyEdit') && params['applyEdit'] != null - ? (params['applyEdit'] as bool) + ? (params['applyEdit'] as bool?) : null, params.containsKey('didChangeConfiguration') && params['didChangeConfiguration'] != null @@ -2801,15 +2801,15 @@ class WorkspaceClientCapabilities { (params['symbol'] as Map)) : null); - final bool applyEdit; + final bool? applyEdit; - final DynamicRegistrationCapability didChangeConfiguration; + final DynamicRegistrationCapability? didChangeConfiguration; - final DynamicRegistrationCapability didChangeWatchedFiles; + final DynamicRegistrationCapability? didChangeWatchedFiles; - final DynamicRegistrationCapability executeCommand; + final DynamicRegistrationCapability? executeCommand; - final DynamicRegistrationCapability symbol; + final DynamicRegistrationCapability? symbol; Map toJson() => { 'applyEdit': applyEdit, @@ -2842,15 +2842,15 @@ class WorkspaceClientCapabilities { class WorkspaceClientCapabilities$Builder { WorkspaceClientCapabilities$Builder._(); - bool applyEdit; + bool? applyEdit; - DynamicRegistrationCapability didChangeConfiguration; + DynamicRegistrationCapability? didChangeConfiguration; - DynamicRegistrationCapability didChangeWatchedFiles; + DynamicRegistrationCapability? didChangeWatchedFiles; - DynamicRegistrationCapability executeCommand; + DynamicRegistrationCapability? executeCommand; - DynamicRegistrationCapability symbol; + DynamicRegistrationCapability? symbol; } class WorkspaceEdit { @@ -2872,11 +2872,11 @@ class WorkspaceEdit { .toList())) : null); - final Map> changes; + final Map>? changes; Map toJson() => { 'changes': changes?.map((k, v) => - MapEntry(k, v?.map((v) => v?.toJson())?.toList())) + MapEntry(k, v.map((v) => v.toJson()).toList())) }; @override int get hashCode { @@ -2893,7 +2893,7 @@ class WorkspaceEdit { class WorkspaceEdit$Builder { WorkspaceEdit$Builder._(); - Map> changes; + Map>? changes; } int _hashCombine(int hash, int value) { diff --git a/packages/jael/jael_language_server/lib/src/protocol/language_server/server.dart b/packages/jael/jael_language_server/lib/src/protocol/language_server/server.dart index cb49a5cb..55fd9de0 100644 --- a/packages/jael/jael_language_server/lib/src/protocol/language_server/server.dart +++ b/packages/jael/jael_language_server/lib/src/protocol/language_server/server.dart @@ -10,7 +10,7 @@ import 'wireformat.dart'; /// A Language Server communicating over stdin and stdout. class StdIOLanguageServer { final LanguageServer _server; - Future onDone; + Future? onDone; /// Wrap [_server] and register RPC methods using the LSP wire protocol. /// @@ -38,10 +38,10 @@ class StdIOLanguageServer { peer ..registerMethod('initialize', (params) async { final serverCapabilities = await _server.initialize( - params['processId'].valueOr(0) as int, - params['rootUri'].valueOr('') as String, + params['processId'].valueOr(0) as int?, + params['rootUri'].valueOr('') as String?, ClientCapabilities.fromJson(params['capabilities'].value as Map), - params['trace'].valueOr('off') as String); + params['trace'].valueOr('off') as String?); _isInitialized = true; return {'capabilities': serverCapabilities.toJson()}; }) @@ -90,7 +90,7 @@ class StdIOLanguageServer { }) ..logMessages.map((e) => e.toJson()).forEach( (message) => peer.sendNotification('window/logMessage', message)) - ..showMessages.map((e) => e.toJson()).forEach( + ..showMessages!.map((e) => e.toJson()).forEach( (message) => peer.sendNotification('window/showMessage', message)); } @@ -122,31 +122,31 @@ class StdIOLanguageServer { (params) => _server .textDocumentReferences( _document(params), _position(params), _referenceContext(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); _registerRequest( peer, 'textDocument/implementation', (params) => _server .textDocumentImplementation(_document(params), _position(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); _registerRequest( peer, 'textDocument/documentHighlight', (params) => _server .textDocumentHighlight(_document(params), _position(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); _registerRequest( peer, 'textDocument/documentSymbol', (params) => _server .textDocumentSymbols(_document(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); _registerRequest( peer, 'workspace/symbol', (params) => _server .workspaceSymbol(_query(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); } void _codeActionMethods(Peer peer) { @@ -156,18 +156,18 @@ class StdIOLanguageServer { (params) => _server .textDocumentCodeAction( _document(params), _range(params), _codeActionContext(params)) - .then((r) => r?.map((e) => e.toJson())?.toList())); + .then((r) => r.map((e) => e.toJson()).toList())); _registerRequest( peer, 'workspace/executeCommand', (params) => _server.workspaceExecuteCommand( - params['command'].value as String, - params['arguments']?.value as List)); + params['command'].value as String?, + params['arguments']?.value as List?)); _registerRequest( peer, 'textDocument/rename', (params) async => (await _server.textDocumentRename(_document(params), - _position(params), params['newName'].value as String)) + _position(params), params['newName'].value as String?))! .toJson()); } } @@ -198,4 +198,4 @@ List _contentChanges(params) => .map((change) => TextDocumentContentChangeEvent.fromJson(change as Map)) .toList(); -String _query(params) => params['query'].value as String; +String? _query(params) => params['query'].value as String?; diff --git a/packages/jael/jael_language_server/lib/src/protocol/language_server/wireformat.dart b/packages/jael/jael_language_server/lib/src/protocol/language_server/wireformat.dart index 4d120993..02ef965d 100644 --- a/packages/jael/jael_language_server/lib/src/protocol/language_server/wireformat.dart +++ b/packages/jael/jael_language_server/lib/src/protocol/language_server/wireformat.dart @@ -33,7 +33,7 @@ class _Parser { bool _headerMode = true; int _contentLength = -1; - StreamSubscription _subscription; + late StreamSubscription _subscription; _Parser(Stream> stream) { _subscription = diff --git a/packages/jael/jael_language_server/lib/src/server.dart b/packages/jael/jael_language_server/lib/src/server.dart index 864d9d57..2354ec19 100644 --- a/packages/jael/jael_language_server/lib/src/server.dart +++ b/packages/jael/jael_language_server/lib/src/server.dart @@ -17,14 +17,14 @@ import 'protocol/language_server/interface.dart'; import 'protocol/language_server/messages.dart'; class JaelLanguageServer extends LanguageServer { - var _diagnostics = new StreamController(); - var _done = new Completer(); - var _memFs = new MemoryFileSystem(); - var _localFs = const LocalFileSystem(); - Directory _localRootDir, _memRootDir; - var logger = new Logger('jael'); - Uri _rootUri; - var _workspaceEdits = new StreamController(); + final _diagnostics = StreamController(); + final _done = Completer(); + final _memFs = MemoryFileSystem(); + final _localFs = const LocalFileSystem(); + Directory? _localRootDir, _memRootDir; + var logger = Logger('jael'); + late Uri _rootUri; + final _workspaceEdits = StreamController(); @override Stream get diagnostics => _diagnostics.stream; @@ -48,24 +48,24 @@ class JaelLanguageServer extends LanguageServer { peer.registerMethod('textDocument/formatting', (json_rpc_2.Parameters params) async { var documentId = - new TextDocumentIdentifier.fromJson(params['textDocument'].asMap); + TextDocumentIdentifier.fromJson(params['textDocument'].asMap); var formattingOptions = - new FormattingOptions.fromJson(params['options'].asMap); + FormattingOptions.fromJson(params['options'].asMap); return await textDocumentFormatting(documentId, formattingOptions); }); } @override - Future initialize(int clientPid, String rootUri, - ClientCapabilities clientCapabilities, String trace) async { + Future initialize(int? clientPid, String? rootUri, + ClientCapabilities clientCapabilities, String? trace) async { // Find our real root dir. - _localRootDir = _localFs.directory(_rootUri = Uri.parse(rootUri)); + _localRootDir = _localFs.directory(_rootUri = Uri.parse(rootUri!)); _memRootDir = _memFs.directory('/'); - await _memRootDir.create(recursive: true); + await _memRootDir!.create(recursive: true); _memFs.currentDirectory = _memRootDir; // Copy all real files that end in *.jael (and *.jl for legacy) into the in-memory filesystem. - await for (var entity in _localRootDir.list(recursive: true)) { + await for (var entity in _localRootDir!.list(recursive: true)) { if (entity is File && p.extension(entity.path) == '.jael') { logger.info('HEY ${entity.path}'); var file = _memFs.file(entity.absolute.path); @@ -78,24 +78,24 @@ class JaelLanguageServer extends LanguageServer { 'Found Jael file ${file.path}; copied to ${file.absolute.path}'); // Analyze it - var documentId = new TextDocumentIdentifier((b) { - b..uri = _rootUri.replace(path: file.path).toString(); + var documentId = TextDocumentIdentifier((b) { + b.uri = _rootUri.replace(path: file.path).toString(); }); await analyzerForId(documentId); } } - return new ServerCapabilities((b) { + return ServerCapabilities((b) { b ..codeActionProvider = false - ..completionProvider = new CompletionOptions((b) { + ..completionProvider = CompletionOptions((b) { b ..resolveProvider = true ..triggerCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvxwyz' .codeUnits - .map((c) => new String.fromCharCode(c)) + .map((c) => String.fromCharCode(c)) .toList(); }) ..definitionProvider = true @@ -108,13 +108,13 @@ class JaelLanguageServer extends LanguageServer { ..implementationProvider = true ..referencesProvider = true ..renameProvider = true - ..signatureHelpProvider = new SignatureHelpOptions((b) {}) - ..textDocumentSync = new TextDocumentSyncOptions((b) { + ..signatureHelpProvider = SignatureHelpOptions((b) {}) + ..textDocumentSync = TextDocumentSyncOptions((b) { b ..openClose = true ..change = TextDocumentSyncKind.full - ..save = new SaveOptions((b) { - b..includeText = false; + ..save = SaveOptions((b) { + b.includeText = false; }) ..willSave = false ..willSaveWaitUntil = false; @@ -124,7 +124,7 @@ class JaelLanguageServer extends LanguageServer { } Future fileForId(TextDocumentIdentifier documentId) async { - var uri = Uri.parse(documentId.uri); + var uri = Uri.parse(documentId.uri!); var relativePath = uri.path; var file = _memFs.directory('/').childFile(relativePath); @@ -156,14 +156,14 @@ class JaelLanguageServer extends LanguageServer { Future analyzerForId(TextDocumentIdentifier documentId) async { var scanner = await scannerForId(documentId); - var analyzer = new Analyzer(scanner, logger)..errors.addAll(scanner.errors); + var analyzer = Analyzer(scanner, logger)..errors.addAll(scanner.errors); analyzer.parseDocument(); emitDiagnostics(documentId.uri, analyzer.errors.map(toDiagnostic).toList()); return analyzer; } Diagnostic toDiagnostic(JaelError e) { - return new Diagnostic((b) { + return Diagnostic((b) { b ..message = e.message ..range = toRange(e.span) @@ -182,7 +182,7 @@ class JaelLanguageServer extends LanguageServer { } Range toRange(FileSpan span) { - return new Range((b) { + return Range((b) { b ..start = toPosition(span.start) ..end = toPosition(span.end); @@ -190,8 +190,8 @@ class JaelLanguageServer extends LanguageServer { } Range emptyRange() { - return new Range((b) => b - ..start = b.end = new Position((b) { + return Range((b) => b + ..start = b.end = Position((b) { b ..character = 1 ..line = 0; @@ -199,15 +199,15 @@ class JaelLanguageServer extends LanguageServer { } Position toPosition(SourceLocation location) { - return new Position((b) { + return Position((b) { b ..line = location.line ..character = location.column; }); } - Location toLocation(String uri, FileSpan span) { - return new Location((b) { + Location toLocation(String? uri, FileSpan span) { + return Location((b) { b ..range = toRange(span) ..uri = uri; @@ -215,27 +215,27 @@ class JaelLanguageServer extends LanguageServer { } bool isReachable(JaelObject obj, Position position) { - return obj.span.start.line <= position.line && - obj.span.start.column <= position.character; + return obj.span.start.line <= position.line! && + obj.span.start.column <= position.character!; } - CompletionItem toCompletion(Variable symbol) { + CompletionItem? toCompletion(Variable symbol) { var value = symbol.value; if (value is JaelCustomElement) { var name = value.name; - return new CompletionItem((b) { + return CompletionItem((b) { b ..kind = CompletionItemKind.classKind ..label = symbol.name - ..textEdit = new TextEdit((b) { + ..textEdit = TextEdit((b) { b ..range = emptyRange() ..newText = '<$name\$1>\n \$2\n'; }); }); } else if (value is JaelVariable) { - return new CompletionItem((b) { + return CompletionItem((b) { b ..kind = CompletionItemKind.variable ..label = symbol.name; @@ -245,8 +245,8 @@ class JaelLanguageServer extends LanguageServer { return null; } - void emitDiagnostics(String uri, Iterable diagnostics) { - _diagnostics.add(new Diagnostics((b) { + void emitDiagnostics(String? uri, Iterable diagnostics) { + _diagnostics.add(Diagnostics((b) { logger.info('$uri => ${diagnostics.map((d) => d.message).toList()}'); b ..diagnostics = diagnostics.toList() @@ -256,43 +256,42 @@ class JaelLanguageServer extends LanguageServer { @override Future textDocumentDidOpen(TextDocumentItem document) async { - await analyzerForId( - new TextDocumentIdentifier((b) => b..uri = document.uri)); + await analyzerForId(TextDocumentIdentifier((b) => b..uri = document.uri)); } @override Future textDocumentDidChange(VersionedTextDocumentIdentifier documentId, List changes) async { - var id = new TextDocumentIdentifier((b) => b..uri = documentId.uri); + var id = TextDocumentIdentifier((b) => b..uri = documentId.uri); var file = await fileForId(id); for (var change in changes) { if (change.text != null) { - await file.writeAsString(change.text); + await file.writeAsString(change.text!); } else if (change.range != null) { - var contents = await file.readAsString(); + String? contents = await file.readAsString(); int findIndex(Position position) { - var lines = contents.split('\n'); + var lines = contents!.split('\n'); // Sum the length of the previous lines. - int lineLength = lines - .take(position.line - 1) + var lineLength = lines + .take(position.line! - 1) .map((s) => s.length) .reduce((a, b) => a + b); - return lineLength + position.character - 1; + return lineLength + position.character! - 1; } if (change.range == null) { contents = change.text; } else { - var start = findIndex(change.range.start), - end = findIndex(change.range.end); - contents = contents.replaceRange(start, end, change.text); + var start = findIndex(change.range!.start!), + end = findIndex(change.range!.end!); + contents = contents.replaceRange(start, end, change.text!); } logger.info('${file.path} => $contents'); - await file.writeAsString(contents); + await file.writeAsString(contents!); } } @@ -310,9 +309,9 @@ class JaelLanguageServer extends LanguageServer { Future textDocumentCompletion( TextDocumentIdentifier documentId, Position position) async { var analyzer = await analyzerForId(documentId); - var symbols = analyzer.scope.allVariables; - var reachable = symbols.where((s) => isReachable(s.value, position)); - return new CompletionList((b) { + var symbols = analyzer.scope!.allVariables; + var reachable = symbols.where((s) => isReachable(s.value!, position)); + return CompletionList((b) { b ..isIncomplete = false ..items = reachable.map(toCompletion).toList(); @@ -320,16 +319,16 @@ class JaelLanguageServer extends LanguageServer { } final RegExp _id = - new RegExp(r'(([A-Za-z][A-Za-z0-9_]*-)*([A-Za-z][A-Za-z0-9_]*))'); + RegExp(r'(([A-Za-z][A-Za-z0-9_]*-)*([A-Za-z][A-Za-z0-9_]*))'); - Future currentName( + Future currentName( TextDocumentIdentifier documentId, Position position) async { // First, read the file. var file = await fileForId(documentId); var contents = await file.readAsString(); // Next, find the current index. - var scanner = new SpanScanner(contents); + var scanner = SpanScanner(contents); while (!scanner.isDone && (scanner.state.line != position.line || @@ -339,10 +338,10 @@ class JaelLanguageServer extends LanguageServer { // Next, just read the name. if (scanner.matches(_id)) { - var longest = scanner.lastSpan.text; + var longest = scanner.lastSpan!.text; while (scanner.matches(_id) && scanner.position > 0 && !scanner.isDone) { - longest = scanner.lastSpan.text; + longest = scanner.lastSpan!.text; scanner.position--; } @@ -352,19 +351,19 @@ class JaelLanguageServer extends LanguageServer { } } - Future currentSymbol( + Future currentSymbol( TextDocumentIdentifier documentId, Position position) async { var name = await currentName(documentId, position); if (name == null) return null; var analyzer = await analyzerForId(documentId); - var symbols = analyzer.allDefinitions ?? analyzer.scope.allVariables; + var symbols = analyzer.allDefinitions; // ?? analyzer.scope!.allVariables; logger .info('Current symbols, seeking $name: ${symbols.map((v) => v.name)}'); - return analyzer.scope.resolve(name)?.value; + return analyzer.scope!.resolve(name)?.value; } @override - Future textDocumentDefinition( + Future textDocumentDefinition( TextDocumentIdentifier documentId, Position position) async { var symbol = await currentSymbol(documentId, position); if (symbol != null) { @@ -379,7 +378,7 @@ class JaelLanguageServer extends LanguageServer { var symbol = await currentSymbol(documentId, position); if (symbol != null) { return symbol.usages.map((u) { - return new DocumentHighlight((b) { + return DocumentHighlight((b) { b ..range = toRange(u.span) ..kind = u.type == SymbolUsageType.definition @@ -392,11 +391,11 @@ class JaelLanguageServer extends LanguageServer { } @override - Future textDocumentHover( + Future textDocumentHover( TextDocumentIdentifier documentId, Position position) async { var symbol = await currentSymbol(documentId, position); if (symbol != null) { - return new Hover((b) { + return Hover((b) { b ..contents = symbol.span.text ..range = toRange(symbol.span); @@ -430,27 +429,26 @@ class JaelLanguageServer extends LanguageServer { @override Future textDocumentRename(TextDocumentIdentifier documentId, - Position position, String newName) async { + Position position, String? newName) async { var symbol = await currentSymbol(documentId, position); if (symbol != null) { - return new WorkspaceEdit((b) { - b - ..changes = { - symbol.name: symbol.usages.map((u) { - return new TextEdit((b) { - b - ..range = toRange(u.span) - ..newText = (symbol is JaelCustomElement && - u.type == SymbolUsageType.definition) - ? '"$newName"' - : newName; - }); - }).toList() - }; + return WorkspaceEdit((b) { + b.changes = { + symbol.name: symbol.usages.map((u) { + return TextEdit((b) { + b + ..range = toRange(u.span) + ..newText = (symbol is JaelCustomElement && + u.type == SymbolUsageType.definition) + ? '"$newName"' + : newName; + }); + }).toList() + }; }); } - return new WorkspaceEdit((b) { - b..changes = {}; + return WorkspaceEdit((b) { + b.changes = {}; }); } @@ -459,28 +457,28 @@ class JaelLanguageServer extends LanguageServer { TextDocumentIdentifier documentId) async { var analyzer = await analyzerForId(documentId); return analyzer.allDefinitions.map((symbol) { - return new SymbolInformation((b) { + return SymbolInformation((b) { b ..kind = SymbolKind.classSymbol ..name = symbol.name - ..location = toLocation(documentId.uri, symbol.value.span); + ..location = toLocation(documentId.uri, symbol.value!.span); }); }).toList(); } @override - Future workspaceExecuteCommand(String command, List arguments) async { + Future workspaceExecuteCommand(String? command, List? arguments) async { // TODO: implement workspaceExecuteCommand } @override - Future> workspaceSymbol(String query) async { - var values = []; + Future> workspaceSymbol(String? query) async { + var values = []; - await for (var file in _memRootDir.list(recursive: true)) { + await for (var file in _memRootDir!.list(recursive: true)) { if (file is File) { - var id = new TextDocumentIdentifier((b) { - b..uri = file.uri.toString(); + var id = TextDocumentIdentifier((b) { + b.uri = file.uri.toString(); }); var analyzer = await analyzerForId(id); values.addAll(analyzer.allDefinitions.map((v) => v.value)); @@ -488,11 +486,11 @@ class JaelLanguageServer extends LanguageServer { } return values.map((o) { - return new SymbolInformation((b) { + return SymbolInformation((b) { b - ..name = o.name + ..name = o!.name ..location = toLocation(o.span.sourceUrl.toString(), o.span) - ..containerName = p.basename(o.span.sourceUrl.path) + ..containerName = p.basename(o.span.sourceUrl!.path) ..kind = o is JaelCustomElement ? SymbolKind.classSymbol : SymbolKind.variable; @@ -500,7 +498,7 @@ class JaelLanguageServer extends LanguageServer { }).toList(); } - Future> textDocumentFormatting( + Future?> textDocumentFormatting( TextDocumentIdentifier documentId, FormattingOptions formattingOptions) async { try { @@ -510,16 +508,17 @@ class JaelLanguageServer extends LanguageServer { var document = parseDocument(contents, sourceUrl: file.uri, onError: errors.add); if (errors.isNotEmpty) return null; - var formatter = new JaelFormatter( - formattingOptions.tabSize, formattingOptions.insertSpaces, 80); - var formatted = formatter.apply(document); - logger.info('Original:${contents}\nFormatted:\n$formatted'); + var formatter = JaelFormatter( + formattingOptions.tabSize!, formattingOptions.insertSpaces, 80); + var formatted = formatter.apply(document!); + logger.info('Original:$contents\nFormatted:\n$formatted'); if (formatted.isNotEmpty) await file.writeAsString(formatted); return [ - new TextEdit((b) { + TextEdit((b) { b ..newText = formatted - ..range = document == null ? emptyRange() : toRange(document.span); + ..range = toRange(document + .span); //document == null ? emptyRange() : toRange(document.span); }) ]; } catch (e, st) { @@ -535,7 +534,7 @@ class JaelLanguageServer extends LanguageServer { @override // TODO: implement showMessages - Stream get showMessages => null; + Stream? get showMessages => null; } abstract class DiagnosticSeverity { @@ -543,14 +542,14 @@ abstract class DiagnosticSeverity { } class FormattingOptions { - final num tabSize; + final num? tabSize; - final bool insertSpaces; + final bool? insertSpaces; FormattingOptions(this.tabSize, this.insertSpaces); factory FormattingOptions.fromJson(Map json) { - return new FormattingOptions( - json['tabSize'] as num, json['insertSpaces'] as bool); + return FormattingOptions( + json['tabSize'] as num?, json['insertSpaces'] as bool?); } } diff --git a/packages/jael/jael_language_server/pubspec.yaml b/packages/jael/jael_language_server/pubspec.yaml index 782edf81..70e64626 100644 --- a/packages/jael/jael_language_server/pubspec.yaml +++ b/packages/jael/jael_language_server/pubspec.yaml @@ -1,25 +1,36 @@ name: jael_language_server version: 0.0.0 description: Language Server Protocol implementation for the Jael templating engine. -author: Tobe Osakwe homepage: https://github.com/angel-dart/vscode +publish_to: none environment: - sdk: '>=2.10.0 <2.12.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - args: ^1.0.0 + args: ^2.1.1 # dart_language_server: ^0.1.16 - file: ^5.0.0 - io: ^0.3.2 - jael: #^2.0.0 - path: ../jael - jael_preprocessor: #^2.0.0 - path: ../jael_preprocessor - json_rpc_2: ^2.0.0 - logging: ^0.11.3 - path: ^1.0.0 - source_span: ^1.0.0 - string_scanner: ^1.0.0 - symbol_table: ^2.0.0 + file: ^6.1.2 + io: ^1.0.0 + jael: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/jael/jael + jael_preprocessor: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/jael/jael_preprocessor + json_rpc_2: ^3.0.1 + logging: ^1.0.1 + path: ^1.8.0 + source_span: ^1.8.1 + string_scanner: ^1.1.0 + symbol_table: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/symbol_table + pedantic: ^1.11.0 executables: jael_language_server: jael_language_server \ No newline at end of file diff --git a/packages/jael/jael_web/LICENSE b/packages/jael/jael_web/LICENSE index 8f65b579..89074fd3 100644 --- a/packages/jael/jael_web/LICENSE +++ b/packages/jael/jael_web/LICENSE @@ -1,6 +1,6 @@ -MIT License (MIT) +MIT License -Copyright (c) 2021 dukefirehawk.com +Copyright (c) 2017 The Angel Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/jael/jael_web/example/stateful.dart b/packages/jael/jael_web/example/stateful.dart index 617c7bd2..0a10444f 100644 --- a/packages/jael/jael_web/example/stateful.dart +++ b/packages/jael/jael_web/example/stateful.dart @@ -5,18 +5,18 @@ part 'stateful.g.dart'; void main() {} class _AppState { - final int ticks; + final int? ticks; _AppState({this.ticks}); - _AppState copyWith({int ticks}) { + _AppState copyWith({int? ticks}) { return _AppState(ticks: ticks ?? this.ticks); } } @Jael(template: '
Tick count: {{state.ticks}}
') class StatefulApp extends Component<_AppState> with _StatefulAppJaelTemplate { - Timer _timer; + Timer? _timer; StatefulApp() { state = _AppState(ticks: 0); @@ -27,6 +27,6 @@ class StatefulApp extends Component<_AppState> with _StatefulAppJaelTemplate { @override void beforeDestroy() { - _timer.cancel(); + _timer!.cancel(); } } diff --git a/packages/jael/jael_web/example/stateful.g.dart b/packages/jael/jael_web/example/stateful.g.dart index 398897a8..27186d57 100644 --- a/packages/jael/jael_web/example/stateful.g.dart +++ b/packages/jael/jael_web/example/stateful.g.dart @@ -7,7 +7,7 @@ part of 'stateful.dart'; // ************************************************************************** abstract class _StatefulAppJaelTemplate implements Component<_AppState> { - Timer get _timer; + Timer? get _timer; void beforeDestroy(); @override DomNode render() { diff --git a/packages/jael/jael_web/example/using_components.dart b/packages/jael/jael_web/example/using_components.dart index 50ccbfa5..955426e8 100644 --- a/packages/jael/jael_web/example/using_components.dart +++ b/packages/jael/jael_web/example/using_components.dart @@ -19,7 +19,7 @@ class MyApp extends Component with _MyAppJaelTemplate {} ''') class LabeledInput extends Component with _LabeledInputJaelTemplate { - final String name; + final String? name; LabeledInput({this.name}); } diff --git a/packages/jael/jael_web/example/using_components.g.dart b/packages/jael/jael_web/example/using_components.g.dart index 43a16ceb..fc8ff454 100644 --- a/packages/jael/jael_web/example/using_components.g.dart +++ b/packages/jael/jael_web/example/using_components.g.dart @@ -17,7 +17,7 @@ abstract class _MyAppJaelTemplate implements Component { } abstract class _LabeledInputJaelTemplate implements Component { - String get name; + String? get name; @override DomNode render() { return h('div', {}, [ @@ -27,7 +27,7 @@ abstract class _LabeledInputJaelTemplate implements Component { h('br', {}, []), h('input', { 'name': name, - 'placeholder': "Enter " + name + "...", + 'placeholder': "Enter " + name! + "...", 'type': "text" }, []) ]); diff --git a/packages/jael/jael_web/lib/src/builder/builder.dart b/packages/jael/jael_web/lib/src/builder/builder.dart index 618909c7..473e7ffe 100644 --- a/packages/jael/jael_web/lib/src/builder/builder.dart +++ b/packages/jael/jael_web/lib/src/builder/builder.dart @@ -21,7 +21,7 @@ class JaelComponentGenerator extends GeneratorForAnnotation { Element element, ConstantReader annotation, BuildStep buildStep) async { if (element is ClassElement) { // Load the template - String templateString; + String? templateString; var inputId = buildStep.inputId; var ann = Jael( template: annotation.peek('template')?.stringValue, @@ -47,10 +47,10 @@ class JaelComponentGenerator extends GeneratorForAnnotation { var fs = BuildFileSystem(buildStep, inputId.package); var errors = []; - var doc = await jael.parseDocument(templateString, - sourceUrl: inputId.uri, asDSX: ann.asDsx, onError: errors.add); + var doc = await jael.parseDocument(templateString!, + sourceUrl: inputId.uri, asDSX: ann.asDsx!, onError: errors.add); if (errors.isEmpty) { - doc = await jael.resolve(doc, fs.file(inputId.uri).parent, + doc = await jael.resolve(doc!, fs.file(inputId.uri).parent, onError: errors.add); } @@ -98,7 +98,7 @@ class JaelComponentGenerator extends GeneratorForAnnotation { ..returns = refer('DomNode') ..annotations.add(refer('override')) ..body = Block((b) { - var result = compileElementChild(doc.root); + var result = compileElementChild(doc!.root); b.addExpression(result.returned); }); })); @@ -123,7 +123,7 @@ class JaelComponentGenerator extends GeneratorForAnnotation { for (var attr in child.attributes) { attrs[attr.name] = attr.value == null ? literalTrue - : CodeExpression(Code(attr.value.span.text)); + : CodeExpression(Code(attr.value!.span.text)); } var tagName = child.tagName.name; diff --git a/packages/jael/jael_web/lib/src/builder/util.dart b/packages/jael/jael_web/lib/src/builder/util.dart index b9ba9bc2..e0b2b681 100644 --- a/packages/jael/jael_web/lib/src/builder/util.dart +++ b/packages/jael/jael_web/lib/src/builder/util.dart @@ -10,9 +10,9 @@ import 'package:file/file.dart'; import 'package:path/src/context.dart'; /// Converts a [DartType] to a [TypeReference]. -TypeReference convertTypeReference(DartType t) { +TypeReference convertTypeReference(DartType? t) { return new TypeReference((b) { - b..symbol = t.name; + b..symbol = t!.name; if (t is InterfaceType) { b.types.addAll(t.typeArguments.map(convertTypeReference)); @@ -35,7 +35,7 @@ Parameter convertParameter(ParameterElement e) { ..type = convertTypeReference(e.type) ..named = e.isNamed ..defaultTo = - e.defaultValueCode == null ? null : Code(e.defaultValueCode); + e.defaultValueCode == null ? null : Code(e.defaultValueCode!); }); } @@ -68,11 +68,11 @@ class BuildFileSystem extends FileSystem { @override Directory directory(path) { - String p; + late String p; if (path is String) p = path; else if (path is Uri) - p = p.toString(); + p = path.toString(); //p.toString(); else if (path is FileSystemEntity) p = path.path; else @@ -82,11 +82,11 @@ class BuildFileSystem extends FileSystem { @override File file(path) { - String p; + late String p; if (path is String) p = path; else if (path is Uri) - p = p.toString(); + p = path.toString(); // p.toString(); else if (path is FileSystemEntity) p = path.path; else @@ -192,7 +192,7 @@ class BuildSystemFile extends File { throw _unsupported(); @override - Stream> openRead([int start, int end]) => throw _unsupported(); + Stream> openRead([int? start, int? end]) => throw _unsupported(); @override RandomAccessFile openSync({FileMode mode = FileMode.read}) => @@ -347,10 +347,10 @@ class BuildSystemDirectory extends Directory { void createSync({bool recursive = false}) => throw _unsupported(); @override - Future createTemp([String prefix]) => throw _unsupported(); + Future createTemp([String? prefix]) => throw _unsupported(); @override - Directory createTempSync([String prefix]) => throw _unsupported(); + Directory createTempSync([String? prefix]) => throw _unsupported(); @override Future delete({bool recursive = false}) => diff --git a/packages/jael/jael_web/lib/src/builder_node.dart b/packages/jael/jael_web/lib/src/builder_node.dart index 91c5970e..1490b093 100644 --- a/packages/jael/jael_web/lib/src/builder_node.dart +++ b/packages/jael/jael_web/lib/src/builder_node.dart @@ -2,7 +2,7 @@ import 'dom_builder.dart'; import 'dom_node.dart'; abstract class BuilderNode extends DomNode { - DomBuilderElement build(DomBuilder dom); + DomBuilderElement? build(DomBuilder dom); void destroy(DomBuilderElement el); } @@ -21,7 +21,7 @@ class _Text extends BuilderNode { _Text(this.text); @override - DomBuilderElement build(DomBuilder dom) { + DomBuilderElement? build(DomBuilder dom) { dom.text(text); // TODO: implement build return null; @@ -41,7 +41,7 @@ class _H extends BuilderNode { _H(this.tagName, this.props, this.children); @override - DomBuilderElement build(DomBuilder dom) { + DomBuilderElement? build(DomBuilder dom) { // TODO: implement build return null; } diff --git a/packages/jael/jael_web/lib/src/component.dart b/packages/jael/jael_web/lib/src/component.dart index 4faf6901..69ffef19 100644 --- a/packages/jael/jael_web/lib/src/component.dart +++ b/packages/jael/jael_web/lib/src/component.dart @@ -1,7 +1,7 @@ import 'dom_node.dart'; abstract class Component extends DomNode { - State state; + late State state; DomNode render(); diff --git a/packages/jael/jael_web/lib/src/dom_builder.dart b/packages/jael/jael_web/lib/src/dom_builder.dart index 6800529b..b1d158d7 100644 --- a/packages/jael/jael_web/lib/src/dom_builder.dart +++ b/packages/jael/jael_web/lib/src/dom_builder.dart @@ -6,7 +6,7 @@ abstract class DomBuilder { } abstract class DomBuilderElement extends DomBuilder { - void attr(String name, [String value]); + void attr(String name, [String? value]); void attrs(Map map); diff --git a/packages/jael/jael_web/lib/src/elements.dart b/packages/jael/jael_web/lib/src/elements.dart index c304842d..db59dd27 100644 --- a/packages/jael/jael_web/lib/src/elements.dart +++ b/packages/jael/jael_web/lib/src/elements.dart @@ -2,12 +2,12 @@ import 'builder_node.dart'; import 'dom_node.dart'; Map _apply(Iterable> props, - [Map attrs]) { + [Map? attrs]) { var map = {}; attrs?.forEach((k, attr) { - if (attr is String && attr?.isNotEmpty == true) { + if (attr is String && attr.isNotEmpty == true) { map[k] = attr; - } else if (attr is Iterable && attr?.isNotEmpty == true) { + } else if (attr is Iterable && attr.isNotEmpty == true) { map[k] = attr.toList(); } else if (attr != null) { map[k] = attr; @@ -15,17 +15,17 @@ Map _apply(Iterable> props, }); for (var p in props) { - map.addAll(p ?? {}); + map.addAll(p); } return map.cast(); } DomNode a( - {String href, - String rel, - String target, - String id, + {String? href, + String? rel, + String? target, + String? id, className, style, Map p: const {}, @@ -45,11 +45,11 @@ DomNode a( 'class': className, 'style': style, }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode abbr( - {String title, - String id, + {String? title, + String? id, className, style, Map p: const {}, @@ -60,10 +60,10 @@ DomNode abbr( 'addr', _apply([p, props], {'title': title, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode address( - {String id, + {String? id, className, style, Map p: const {}, @@ -73,21 +73,21 @@ DomNode address( h( 'address', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode area( - {String alt, - Iterable coordinates, - String download, - String href, - String hreflang, - String media, - String nohref, - String rel, - String shape, - String target, - String type, - String id, + {String? alt, + Iterable? coordinates, + String? download, + String? href, + String? hreflang, + String? media, + String? nohref, + String? rel, + String? shape, + String? target, + String? type, + String? id, className, style, Map p: const {}, @@ -122,10 +122,10 @@ DomNode article( Iterable c: const [], @deprecated Iterable children: const []}) => h('article', _apply([p, props], {'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode aside( - {String id, + {String? id, className, style, Map p: const {}, @@ -135,16 +135,16 @@ DomNode aside( h( 'aside', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode audio( - {bool autoplay, - bool controls, - bool loop, - bool muted, - String preload, - String src, - String id, + {bool? autoplay, + bool? controls, + bool? loop, + bool? muted, + String? preload, + String? src, + String? id, className, style, Map p: const {}, @@ -167,10 +167,10 @@ DomNode audio( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode b( - {String id, + {String? id, className, style, Map p: const {}, @@ -178,12 +178,12 @@ DomNode b( Iterable c: const [], @deprecated Iterable children: const []}) => h('b', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode base( - {String href, - String target, - String id, + {String? href, + String? target, + String? id, className, style, Map p: const {}, @@ -202,7 +202,7 @@ DomNode base( })); DomNode bdi( - {String id, + {String? id, className, style, Map p: const {}, @@ -210,11 +210,11 @@ DomNode bdi( Iterable c: const [], @deprecated Iterable children: const []}) => h('bdi', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode bdo( - {String dir, - String id, + {String? dir, + String? id, className, style, Map p: const {}, @@ -225,11 +225,11 @@ DomNode bdo( 'bdo', _apply([p, props], {'dir': dir, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode blockquote( - {String cite, - String id, + {String? cite, + String? id, className, style, Map p: const {}, @@ -240,10 +240,10 @@ DomNode blockquote( 'blockquote', _apply([p, props], {'cite': cite, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode body( - {String id, + {String? id, className, style, Map p: const {}, @@ -253,23 +253,23 @@ DomNode body( h( 'body', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode br() => h('br'); DomNode button( - {bool autofocus, - bool disabled, + {bool? autofocus, + bool? disabled, form, - String formaction, - String formenctype, - String formmethod, - bool formnovalidate, - String formtarget, - String name, - String type, - String value, - String id, + String? formaction, + String? formenctype, + String? formmethod, + bool? formnovalidate, + String? formtarget, + String? name, + String? type, + String? value, + String? id, className, style, Map p: const {}, @@ -297,12 +297,12 @@ DomNode button( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode canvas( - {num height, - num width, - String id, + {num? height, + num? width, + String? id, className, style, Map p: const {}, @@ -321,10 +321,10 @@ DomNode canvas( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode cite( - {String id, + {String? id, className, style, Map p: const {}, @@ -334,10 +334,10 @@ DomNode cite( h( 'cite', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode caption( - {String id, + {String? id, className, style, Map p: const {}, @@ -347,10 +347,10 @@ DomNode caption( h( 'caption', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode code( - {String id, + {String? id, className, style, Map p: const {}, @@ -360,11 +360,11 @@ DomNode code( h( 'code', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode col( - {num span, - String id, + {num? span, + String? id, className, style, Map p: const {}, @@ -375,11 +375,11 @@ DomNode col( 'col', _apply([p, props], {'span': span, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode colgroup( - {num span, - String id, + {num? span, + String? id, className, style, Map p: const {}, @@ -390,10 +390,10 @@ DomNode colgroup( 'colgroup', _apply([p, props], {'span': span, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode datalist( - {String id, + {String? id, className, style, Map p: const {}, @@ -403,10 +403,10 @@ DomNode datalist( h( 'datalist', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode dd( - {String id, + {String? id, className, style, Map p: const {}, @@ -414,12 +414,12 @@ DomNode dd( Iterable c: const [], @deprecated Iterable children: const []}) => h('dd', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode del( - {String cite, - String datetime, - String id, + {String? cite, + String? datetime, + String? id, className, style, Map p: const {}, @@ -438,11 +438,11 @@ DomNode del( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode details( - {bool open, - String id, + {bool? open, + String? id, className, style, Map p: const {}, @@ -453,11 +453,11 @@ DomNode details( 'details', _apply([p, props], {'open': open, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode dfn( - {String title, - String id, + {String? title, + String? id, className, style, Map p: const {}, @@ -468,11 +468,11 @@ DomNode dfn( 'dfn', _apply([p, props], {'title': title, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode dialog( - {bool open, - String id, + {bool? open, + String? id, className, style, Map p: const {}, @@ -483,10 +483,10 @@ DomNode dialog( 'dialog', _apply([p, props], {'open': open, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode div( - {String id, + {String? id, className, style, Map p: const {}, @@ -494,10 +494,10 @@ DomNode div( Iterable c: const [], @deprecated Iterable children: const []}) => h('div', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode dl( - {String id, + {String? id, className, style, Map p: const {}, @@ -505,10 +505,10 @@ DomNode dl( Iterable c: const [], @deprecated Iterable children: const []}) => h('dl', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode dt( - {String id, + {String? id, className, style, Map p: const {}, @@ -516,10 +516,10 @@ DomNode dt( Iterable c: const [], @deprecated Iterable children: const []}) => h('dt', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode em( - {String id, + {String? id, className, style, Map p: const {}, @@ -527,14 +527,14 @@ DomNode em( Iterable c: const [], @deprecated Iterable children: const []}) => h('em', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode embed( - {num height, - String src, - String type, - num width, - String id, + {num? height, + String? src, + String? type, + num? width, + String? id, className, style, Map p: const {}, @@ -555,10 +555,10 @@ DomNode embed( })); DomNode fieldset( - {bool disabled, - String form, - String name, - String id, + {bool? disabled, + String? form, + String? name, + String? id, className, style, Map p: const {}, @@ -578,10 +578,10 @@ DomNode fieldset( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode figcaption( - {String id, + {String? id, className, style, Map p: const {}, @@ -591,10 +591,10 @@ DomNode figcaption( h( 'figcaption', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode figure( - {String id, + {String? id, className, style, Map p: const {}, @@ -604,10 +604,10 @@ DomNode figure( h( 'figure', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode footer( - {String id, + {String? id, className, style, Map p: const {}, @@ -617,19 +617,19 @@ DomNode footer( h( 'footer', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode form( - {String accept, - String acceptCharset, - String action, - bool autocomplete, - String enctype, - String method, - String name, - bool novalidate, - String target, - String id, + {String? accept, + String? acceptCharset, + String? action, + bool? autocomplete, + String? enctype, + String? method, + String? name, + bool? novalidate, + String? target, + String? id, className, style, Map p: const {}, @@ -656,10 +656,10 @@ DomNode form( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h1( - {String id, + {String? id, className, style, Map p: const {}, @@ -667,10 +667,10 @@ DomNode h1( Iterable c: const [], @deprecated Iterable children: const []}) => h('h1', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h2( - {String id, + {String? id, className, style, Map p: const {}, @@ -678,9 +678,9 @@ DomNode h2( Iterable c: const [], @deprecated Iterable children: const []}) => h('h2', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h3( - {String id, + {String? id, className, style, Map p: const {}, @@ -688,10 +688,10 @@ DomNode h3( Iterable c: const [], @deprecated Iterable children: const []}) => h('h3', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h4( - {String id, + {String? id, className, style, Map p: const {}, @@ -699,10 +699,10 @@ DomNode h4( Iterable c: const [], @deprecated Iterable children: const []}) => h('h4', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h5( - {String id, + {String? id, className, style, Map p: const {}, @@ -710,10 +710,10 @@ DomNode h5( Iterable c: const [], @deprecated Iterable children: const []}) => h('h5', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode h6( - {String id, + {String? id, className, style, Map p: const {}, @@ -721,10 +721,10 @@ DomNode h6( Iterable c: const [], @deprecated Iterable children: const []}) => h('h6', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode head( - {String id, + {String? id, className, style, Map p: const {}, @@ -734,10 +734,10 @@ DomNode head( h( 'head', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode header( - {String id, + {String? id, className, style, Map p: const {}, @@ -747,15 +747,15 @@ DomNode header( h( 'header', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode hr() => h('hr'); DomNode html( - {String manifest, - String xmlns, - String lang, - String id, + {String? manifest, + String? xmlns, + String? lang, + String? id, className, style, Map p: const {}, @@ -775,10 +775,10 @@ DomNode html( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode i( - {String id, + {String? id, className, style, Map p: const {}, @@ -786,16 +786,16 @@ DomNode i( Iterable c: const [], @deprecated Iterable children: const []}) => h('i', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode iframe( - {num height, - String name, + {num? height, + String? name, sandbox, - String src, - String srcdoc, - num width, - String id, + String? src, + String? srcdoc, + num? width, + String? id, className, style, Map p: const {}, @@ -818,17 +818,17 @@ DomNode iframe( })); DomNode img( - {String alt, - String crossorigin, - num height, - String ismap, - String longdesc, + {String? alt, + String? crossorigin, + num? height, + String? ismap, + String? longdesc, sizes, - String src, - String srcset, - String usemap, - num width, - String id, + String? src, + String? srcset, + String? usemap, + num? width, + String? id, className, style, Map p: const {}, @@ -855,37 +855,37 @@ DomNode img( })); DomNode input( - {String accept, - String alt, - bool autocomplete, - bool autofocus, - bool checked, - String dirname, - bool disabled, - String form, - String formaction, - String formenctype, - String method, - String formnovalidate, - String formtarget, - num height, - String list, + {String? accept, + String? alt, + bool? autocomplete, + bool? autofocus, + bool? checked, + String? dirname, + bool? disabled, + String? form, + String? formaction, + String? formenctype, + String? method, + String? formnovalidate, + String? formtarget, + num? height, + String? list, max, - num maxlength, + num? maxlength, min, - bool multiple, - String name, - String pattern, - String placeholder, - bool readonly, - bool required, - num size, - String src, - num step, - String type, - String value, - num width, - String id, + bool? multiple, + String? name, + String? pattern, + String? placeholder, + bool? readonly, + bool? required, + num? size, + String? src, + num? step, + String? type, + String? value, + num? width, + String? id, className, style, Map p: const {}, @@ -933,9 +933,9 @@ DomNode input( })); DomNode ins( - {String cite, - String datetime, - String id, + {String? cite, + String? datetime, + String? id, className, style, Map p: const {}, @@ -954,10 +954,10 @@ DomNode ins( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode kbd( - {String id, + {String? id, className, style, Map p: const {}, @@ -965,16 +965,16 @@ DomNode kbd( Iterable c: const [], @deprecated Iterable children: const []}) => h('kbd', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode keygen( - {bool autofocus, - String challenge, - bool disabled, - String from, - String keytype, - String name, - String id, + {bool? autofocus, + String? challenge, + bool? disabled, + String? from, + String? keytype, + String? name, + String? id, className, style, Map p: const {}, @@ -997,12 +997,12 @@ DomNode keygen( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode label( - {String for_, - String form, - String id, + {String? for_, + String? form, + String? id, className, style, Map p: const {}, @@ -1021,10 +1021,10 @@ DomNode label( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode legend( - {String id, + {String? id, className, style, Map p: const {}, @@ -1034,11 +1034,11 @@ DomNode legend( h( 'legend', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode li( - {num value, - String id, + {num? value, + String? id, className, style, Map p: const {}, @@ -1049,18 +1049,18 @@ DomNode li( 'li', _apply([p, props], {'value': value, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode link( - {String crossorigin, - String href, - String hreflang, - String media, - String rel, + {String? crossorigin, + String? href, + String? hreflang, + String? media, + String? rel, sizes, - String target, - String type, - String id, + String? target, + String? type, + String? id, className, style, Map p: const {}, @@ -1085,7 +1085,7 @@ DomNode link( })); DomNode main( - {String id, + {String? id, className, style, Map p: const {}, @@ -1095,11 +1095,11 @@ DomNode main( h( 'main', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode map( - {String name, - String id, + {String? name, + String? id, className, style, Map p: const {}, @@ -1110,10 +1110,10 @@ DomNode map( 'map', _apply([p, props], {'name': name, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode mark( - {String id, + {String? id, className, style, Map p: const {}, @@ -1123,12 +1123,12 @@ DomNode mark( h( 'mark', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode menu( - {String label, - String type, - String id, + {String? label, + String? type, + String? id, className, style, Map p: const {}, @@ -1147,18 +1147,18 @@ DomNode menu( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode menuitem( - {bool checked, + {bool? checked, command, - bool default_, - bool disabled, - String icon, - String label, - String radiogroup, - String type, - String id, + bool? default_, + bool? disabled, + String? icon, + String? label, + String? radiogroup, + String? type, + String? id, className, style, Map p: const {}, @@ -1183,14 +1183,14 @@ DomNode menuitem( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode meta( - {String charset, - String content, - String httpEquiv, - String name, - String id, + {String? charset, + String? content, + String? httpEquiv, + String? name, + String? id, className, style, Map p: const {}, @@ -1211,7 +1211,7 @@ DomNode meta( })); DomNode nav( - {String id, + {String? id, className, style, Map p: const {}, @@ -1219,10 +1219,10 @@ DomNode nav( Iterable c: const [], @deprecated Iterable children: const []}) => h('nav', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode noscript( - {String id, + {String? id, className, style, Map p: const {}, @@ -1232,17 +1232,17 @@ DomNode noscript( h( 'noscript', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode object( - {String data, - String form, - num height, - String name, - String type, - String usemap, - num width, - String id, + {String? data, + String? form, + num? height, + String? name, + String? type, + String? usemap, + num? width, + String? id, className, style, Map p: const {}, @@ -1266,13 +1266,13 @@ DomNode object( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode ol( - {bool reversed, - num start, - String type, - String id, + {bool? reversed, + num? start, + String? type, + String? id, className, style, Map p: const {}, @@ -1292,12 +1292,12 @@ DomNode ol( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode optgroup( - {bool disabled, - String label, - String id, + {bool? disabled, + String? label, + String? id, className, style, Map p: const {}, @@ -1316,14 +1316,14 @@ DomNode optgroup( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode option( - {bool disabled, - String label, - bool selected, - String value, - String id, + {bool? disabled, + String? label, + bool? selected, + String? value, + String? id, className, style, Map p: const {}, @@ -1344,13 +1344,13 @@ DomNode option( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode output( - {String for_, - String form, - String name, - String id, + {String? for_, + String? form, + String? name, + String? id, className, style, Map p: const {}, @@ -1370,10 +1370,10 @@ DomNode output( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode p( - {String id, + {String? id, className, style, Map p: const {}, @@ -1381,12 +1381,12 @@ DomNode p( Iterable c: const [], @deprecated Iterable children: const []}) => h('p', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode param( - {String name, + {String? name, value, - String id, + String? id, className, style, Map p: const {}, @@ -1405,7 +1405,7 @@ DomNode param( })); DomNode picture( - {String id, + {String? id, className, style, Map p: const {}, @@ -1415,10 +1415,10 @@ DomNode picture( h( 'picture', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode pre( - {String id, + {String? id, className, style, Map p: const {}, @@ -1426,12 +1426,12 @@ DomNode pre( Iterable c: const [], @deprecated Iterable children: const []}) => h('pre', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode progress( - {num max, - num value, - String id, + {num? max, + num? value, + String? id, className, style, Map p: const {}, @@ -1450,11 +1450,11 @@ DomNode progress( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode q( - {String cite, - String id, + {String? cite, + String? id, className, style, Map p: const {}, @@ -1465,10 +1465,10 @@ DomNode q( 'q', _apply([p, props], {'cite': cite, 'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode rp( - {String id, + {String? id, className, style, Map p: const {}, @@ -1476,10 +1476,10 @@ DomNode rp( Iterable c: const [], @deprecated Iterable children: const []}) => h('rp', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode rt( - {String id, + {String? id, className, style, Map p: const {}, @@ -1487,10 +1487,10 @@ DomNode rt( Iterable c: const [], @deprecated Iterable children: const []}) => h('rt', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode ruby( - {String id, + {String? id, className, style, Map p: const {}, @@ -1500,10 +1500,10 @@ DomNode ruby( h( 'ruby', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode s( - {String id, + {String? id, className, style, Map p: const {}, @@ -1511,10 +1511,10 @@ DomNode s( Iterable c: const [], @deprecated Iterable children: const []}) => h('s', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode samp( - {String id, + {String? id, className, style, Map p: const {}, @@ -1524,15 +1524,15 @@ DomNode samp( h( 'samp', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode script( - {bool async, - String charset, - bool defer, - String src, - String type, - String id, + {bool? async, + String? charset, + bool? defer, + String? src, + String? type, + String? id, className, style, Map p: const {}, @@ -1554,10 +1554,10 @@ DomNode script( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode section( - {String id, + {String? id, className, style, Map p: const {}, @@ -1567,16 +1567,16 @@ DomNode section( h( 'section', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode select( - {bool autofocus, - bool disabled, - String form, - bool multiple, - bool required, - num size, - String id, + {bool? autofocus, + bool? disabled, + String? form, + bool? multiple, + bool? required, + num? size, + String? id, className, style, Map p: const {}, @@ -1599,10 +1599,10 @@ DomNode select( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode small( - {String id, + {String? id, className, style, Map p: const {}, @@ -1612,15 +1612,15 @@ DomNode small( h( 'small', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode source( - {String src, - String srcset, - String media, + {String? src, + String? srcset, + String? media, sizes, - String type, - String id, + String? type, + String? id, className, style, Map p: const {}, @@ -1642,7 +1642,7 @@ DomNode source( })); DomNode span( - {String id, + {String? id, className, style, Map p: const {}, @@ -1652,10 +1652,10 @@ DomNode span( h( 'span', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode strong( - {String id, + {String? id, className, style, Map p: const {}, @@ -1665,13 +1665,13 @@ DomNode strong( h( 'strong', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode style( - {String media, - bool scoped, - String type, - String id, + {String? media, + bool? scoped, + String? type, + String? id, Map p: const {}, @deprecated Map props: const {}, Iterable c: const [], @@ -1680,10 +1680,10 @@ DomNode style( 'style', _apply([p, props], {'media': media, 'scoped': scoped, 'type': type, 'id': id}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode sub( - {String id, + {String? id, className, style, Map p: const {}, @@ -1691,10 +1691,10 @@ DomNode sub( Iterable c: const [], @deprecated Iterable children: const []}) => h('sub', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode summary( - {String id, + {String? id, className, style, Map p: const {}, @@ -1704,10 +1704,10 @@ DomNode summary( h( 'summary', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode sup( - {String id, + {String? id, className, style, Map p: const {}, @@ -1715,11 +1715,11 @@ DomNode sup( Iterable c: const [], @deprecated Iterable children: const []}) => h('sup', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode table( - {bool sortable, - String id, + {bool? sortable, + String? id, className, style, Map p: const {}, @@ -1737,10 +1737,10 @@ DomNode table( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode tbody( - {String id, + {String? id, className, style, Map p: const {}, @@ -1750,13 +1750,13 @@ DomNode tbody( h( 'tbody', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode td( - {num colspan, + {num? colspan, headers, - num rowspan, - String id, + num? rowspan, + String? id, className, style, Map p: const {}, @@ -1776,22 +1776,22 @@ DomNode td( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode textarea( - {bool autofocus, - num cols, - String dirname, - bool disabled, - String form, - num maxlength, - String name, - String placeholder, - bool readonly, - bool required, - num rows, - String wrap, - String id, + {bool? autofocus, + num? cols, + String? dirname, + bool? disabled, + String? form, + num? maxlength, + String? name, + String? placeholder, + bool? readonly, + bool? required, + num? rows, + String? wrap, + String? id, className, style, Map p: const {}, @@ -1820,10 +1820,10 @@ DomNode textarea( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode tfoot( - {String id, + {String? id, className, style, Map p: const {}, @@ -1833,16 +1833,16 @@ DomNode tfoot( h( 'tfoot', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode th( - {String abbr, - num colspan, + {String? abbr, + num? colspan, headers, - num rowspan, - String scope, + num? rowspan, + String? scope, sorted, - String id, + String? id, className, style, Map p: const {}, @@ -1865,10 +1865,10 @@ DomNode th( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode thead( - {String id, + {String? id, className, style, Map p: const {}, @@ -1878,11 +1878,11 @@ DomNode thead( h( 'thead', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode time( - {String datetime, - String id, + {String? datetime, + String? id, className, style, Map p: const {}, @@ -1900,10 +1900,10 @@ DomNode time( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode title( - {String id, + {String? id, className, style, Map p: const {}, @@ -1913,10 +1913,10 @@ DomNode title( h( 'title', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode tr( - {String id, + {String? id, className, style, Map p: const {}, @@ -1924,15 +1924,15 @@ DomNode tr( Iterable c: const [], @deprecated Iterable children: const []}) => h('tr', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode track( - {bool default_, - String kind, - String label, - String src, - String srclang, - String id, + {bool? default_, + String? kind, + String? label, + String? src, + String? srclang, + String? id, className, style, Map p: const {}, @@ -1954,7 +1954,7 @@ DomNode track( })); DomNode u( - {String id, + {String? id, className, style, Map p: const {}, @@ -1962,10 +1962,10 @@ DomNode u( Iterable c: const [], @deprecated Iterable children: const []}) => h('u', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode ul( - {String id, + {String? id, className, style, Map p: const {}, @@ -1973,10 +1973,10 @@ DomNode ul( Iterable c: const [], @deprecated Iterable children: const []}) => h('ul', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode var_( - {String id, + {String? id, className, style, Map p: const {}, @@ -1984,19 +1984,19 @@ DomNode var_( Iterable c: const [], @deprecated Iterable children: const []}) => h('var', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode video( - {bool autoplay, - bool controls, - num height, - bool loop, - bool muted, - String poster, - String preload, - String src, - num width, - String id, + {bool? autoplay, + bool? controls, + num? height, + bool? loop, + bool? muted, + String? poster, + String? preload, + String? src, + num? width, + String? id, className, style, Map p: const {}, @@ -2022,10 +2022,10 @@ DomNode video( 'class': className, 'style': style }), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); DomNode wbr( - {String id, + {String? id, className, style, Map p: const {}, @@ -2033,4 +2033,4 @@ DomNode wbr( Iterable c: const [], @deprecated Iterable children: const []}) => h('wbr', _apply([p, props], {'id': id, 'class': className, 'style': style}), - []..addAll(c ?? [])..addAll(children ?? [])); + []..addAll(c)..addAll(children)); diff --git a/packages/jael/jael_web/lib/src/jael_component.dart b/packages/jael/jael_web/lib/src/jael_component.dart index 0e0304fe..702b81ec 100644 --- a/packages/jael/jael_web/lib/src/jael_component.dart +++ b/packages/jael/jael_web/lib/src/jael_component.dart @@ -1,19 +1,19 @@ /// A annotation for components that source-gen their `render()` methods. class Jael { /// The raw template. - final String template; + final String? template; /// The path to a [template]. - final String templateUrl; + final String? templateUrl; /// Whether to parse the [template] as `DSX`. - final bool asDsx; + final bool? asDsx; const Jael({this.template, this.templateUrl, this.asDsx}); } /// Shorthand for enabling `DSX` syntax when using a [Jael] annotation. class Dsx extends Jael { - const Dsx({String template, String templateUrl}) + const Dsx({String? template, String? templateUrl}) : super(template: template, templateUrl: templateUrl, asDsx: true); } diff --git a/packages/jael/jael_web/pubspec.yaml b/packages/jael/jael_web/pubspec.yaml index 9352c468..0237d4c8 100644 --- a/packages/jael/jael_web/pubspec.yaml +++ b/packages/jael/jael_web/pubspec.yaml @@ -1,18 +1,25 @@ name: jael_web version: 0.0.0 description: Experimental virtual DOM/SPA engine built on Jael. Supports SSR. +publish_to: none environment: - sdk: '>=2.10.0 <2.12.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - build: ^1.0.0 - build_config: ^0.3.0 - code_builder: ^3.0.0 - jael: #^2.0.0 - path: ../jael - jael_preprocessor: #^2.0.0 - path: ../jael_preprocessor - source_gen: ^0.9.0 + build: ^2.0.2 + build_config: ^1.0.0 + code_builder: ^4.0.0 + jael: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/jael/jael + jael_preprocessor: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/jael/jael_preprocessor + source_gen: ^1.0.2 dev_dependencies: - build_runner: ^1.0.0 - build_web_compilers: ^1.0.0 - pedantic: ^1.0.0 \ No newline at end of file + build_runner: ^2.0.4 + build_web_compilers: ^3.0.0 + pedantic: ^1.11.1 \ No newline at end of file diff --git a/packages/jinja/AUTHORS.md b/packages/jinja/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/jinja/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/jinja/CHANGELOG.md b/packages/jinja/CHANGELOG.md index 687440ba..5a6d4732 100644 --- a/packages/jinja/CHANGELOG.md +++ b/packages/jinja/CHANGELOG.md @@ -1,3 +1,6 @@ -## 1.0.0 +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + +# 1.0.0 - Initial version, created by Stagehand diff --git a/packages/jinja/README.md b/packages/jinja/README.md index 840574ba..19f3e6e0 100644 --- a/packages/jinja/README.md +++ b/packages/jinja/README.md @@ -11,7 +11,7 @@ import 'package:angel_framework/http.dart'; import 'package:angel_jinja/angel_jinja.dart'; import 'package:path/path.dart' as p; -main() async { +void main() async { var app = Angel(); var http = AngelHttp(app); var viewsDir = p.join( diff --git a/packages/jinja/example/main.dart b/packages/jinja/example/main.dart index b40937c0..4e07a125 100644 --- a/packages/jinja/example/main.dart +++ b/packages/jinja/example/main.dart @@ -4,7 +4,7 @@ import 'package:angel_framework/http.dart'; import 'package:angel_jinja/angel_jinja.dart'; import 'package:path/path.dart' as p; -main() async { +void main() async { var app = Angel(); var http = AngelHttp(app); var viewsDir = p.join( diff --git a/packages/jinja/lib/angel_jinja.dart b/packages/jinja/lib/angel_jinja.dart index 89d38df5..24adecad 100644 --- a/packages/jinja/lib/angel_jinja.dart +++ b/packages/jinja/lib/angel_jinja.dart @@ -9,45 +9,45 @@ import 'package:jinja/jinja.dart'; /// All options other than [createLoader] are passed to either [FileSystemLoader] /// or [Environment]. AngelConfigurer jinja({ - Iterable ext = const ['html'], + Set ext = const {'html'}, String path = 'lib/src/templates', bool followLinks = true, - String stmtOpen = '{%', - String stmtClose = '%}', + String blockStart = '{%', + String blockEnd = '%}', String varOpen = '{{', String varClose = '}}', - String commentOpen = '{#', - String commentClose = '#}', + String commentStart = '{#', + String commentEnd = '#}', defaultValue, - bool autoReload = true, + //bool autoReload = true, Map filters = const {}, Map tests = const {}, - Loader Function() createLoader, + Loader Function()? createLoader, }) { return (app) { createLoader ??= () { return FileSystemLoader( - ext: ext.toList(), + extensions: ext, path: path, followLinks: followLinks, ); }; var env = Environment( - loader: createLoader(), - stmtOpen: stmtOpen, - stmtClose: stmtClose, - varOpen: varOpen, - varClose: varClose, - commentOpen: commentOpen, - commentClose: commentClose, + loader: createLoader!(), + blockStart: blockStart, + blockEnd: blockEnd, + variableStart: varOpen, + variableEnd: varClose, + commentStart: commentStart, + commentEnd: commentEnd, //defaultValue: defaultValue, - autoReload: autoReload, + //autoReload: autoReload, filters: filters, tests: tests, ); app.viewGenerator = (path, [values]) { - return env.getTemplate(path).render(values); + return env.getTemplate(path).render(values) as String; }; }; } diff --git a/packages/jinja/pubspec.yaml b/packages/jinja/pubspec.yaml index bf66e650..554e8f94 100644 --- a/packages/jinja/pubspec.yaml +++ b/packages/jinja/pubspec.yaml @@ -1,17 +1,23 @@ name: angel_jinja +version: 2.0.0 description: Angel support for the Jinja2 templating engine, ported from Python to Dart. -version: 1.0.0-rc.0 homepage: https://github.com/angel-dart/jinja -author: Tobe O +publish_to: none environment: - sdk: '>=2.10.0 <2.12.0' + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - jinja: ^0.0.4 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + jinja: ^0.3.1 dev_dependencies: - angel_test: #^2.0.0 - path: ../test - path: ^1.0.0 - pedantic: ^1.0.0 - test: ^1.15.7 + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + path: ^1.8.0 + pedantic: ^1.11.0 + test: ^1.17.0 diff --git a/packages/markdown/AUTHORS.md b/packages/markdown/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/markdown/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/markdown/CHANGELOG.md b/packages/markdown/CHANGELOG.md index 4f34420a..f55bafd5 100644 --- a/packages/markdown/CHANGELOG.md +++ b/packages/markdown/CHANGELOG.md @@ -1,3 +1,6 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 2.0.0 * Angel 2 + Dart 2 updates. * Use `package:file`. \ No newline at end of file diff --git a/packages/markdown/example/main.dart b/packages/markdown/example/main.dart index b1525717..bc7b8d3a 100644 --- a/packages/markdown/example/main.dart +++ b/packages/markdown/example/main.dart @@ -5,7 +5,7 @@ import 'package:angel_framework/http.dart'; import 'package:angel_markdown/angel_markdown.dart'; import 'package:file/local.dart'; -main() async { +void main() async { var app = await createServer(); var http = AngelHttp(app); var server = await http.startServer(InternetAddress.loopbackIPv4, 3000); @@ -14,7 +14,7 @@ main() async { Future createServer() async { // Create a new server, and install the Markdown renderer. - var app = new Angel(); + var app = Angel(); var fs = LocalFileSystem(); await app .configure(markdown(fs.directory('views'), template: (content, locals) { diff --git a/packages/markdown/lib/angel_markdown.dart b/packages/markdown/lib/angel_markdown.dart index 86bab23c..fa8dc066 100644 --- a/packages/markdown/lib/angel_markdown.dart +++ b/packages/markdown/lib/angel_markdown.dart @@ -4,7 +4,7 @@ import 'package:angel_framework/angel_framework.dart'; import 'package:file/file.dart'; import 'package:markdown/markdown.dart'; -final RegExp _braces = new RegExp(r'@?{{(((\\})|([^}]))+)}}'); +final RegExp _braces = RegExp(r'@?{{(((\\})|([^}]))+)}}'); /// Configures an [Angel] instance to render Markdown templates from the specified [viewsDirectory]. /// @@ -18,7 +18,8 @@ AngelConfigurer markdown( Directory viewsDirectory, { String extension, ExtensionSet extensionSet, - FutureOr template(String content, Map locals), + FutureOr Function(String content, Map locals) + template, }) { extension ??= '.md'; extensionSet ??= ExtensionSet.gitHubWeb; @@ -40,9 +41,10 @@ AngelConfigurer markdown( var split = expr.split('.'); var root = split[0]; - if (locals?.containsKey(root) != true) - throw new UnimplementedError( + if (locals?.containsKey(root) != true) { + throw UnimplementedError( 'Expected a local named "$root", but none was provided. Expression text: "$text"'); + } return _resolveDotNotation(split, locals[root]).toString(); } @@ -55,13 +57,13 @@ AngelConfigurer markdown( }; } -_resolveDotNotation(List split, target) { +dynamic _resolveDotNotation(List split, target) { if (split.length == 1) return target; - InstanceMirror mirror = reflect(target); + var mirror = reflect(target); - for (int i = 1; i < split.length; i++) { - mirror = mirror.getField(new Symbol(split[i])); + for (var i = 1; i < split.length; i++) { + mirror = mirror.getField(Symbol(split[i])); } return mirror.reflectee; diff --git a/packages/markdown/pubspec.yaml b/packages/markdown/pubspec.yaml index d3fbb6a4..b1220b89 100644 --- a/packages/markdown/pubspec.yaml +++ b/packages/markdown/pubspec.yaml @@ -1,17 +1,23 @@ name: angel_markdown -version: 2.0.0 +version: 3.0.0 description: Angel Markdown view generator. Write static sites, with no build step. -author: Tobe O homepage: https://github.com/angel-dart/markdown +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: ">=2.10.0 <3.0.0" dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - file: ^5.0.0 - markdown: ^2.0.0 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + file: ^6.1.2 + markdown: ^4.0.0 dev_dependencies: - angel_test: #^2.0.0 - path: ../test - pedantic: ^1.0.0 - test: ^1.15.7 + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + pedantic: ^1.11.0 + test: ^1.17.0 diff --git a/packages/mustache/AUTHORS.md b/packages/mustache/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/mustache/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/mustache/CHANGELOG.md b/packages/mustache/CHANGELOG.md index cde505dc..aec563f5 100644 --- a/packages/mustache/CHANGELOG.md +++ b/packages/mustache/CHANGELOG.md @@ -1,2 +1,6 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD +* Replaced `mustache4dart` with `mustache_template` + # 2.0.0 * Angel 2 and Dart 2 support. \ No newline at end of file diff --git a/packages/mustache/LICENSE b/packages/mustache/LICENSE index 8f65b579..bb161745 100644 --- a/packages/mustache/LICENSE +++ b/packages/mustache/LICENSE @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/mustache/analysis_options.yaml b/packages/mustache/analysis_options.yaml index 518eb901..c230cee7 100644 --- a/packages/mustache/analysis_options.yaml +++ b/packages/mustache/analysis_options.yaml @@ -1,2 +1,4 @@ +include: package:pedantic/analysis_options.yaml analyzer: - strong-mode: true \ No newline at end of file + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/mustache/example/main.dart b/packages/mustache/example/main.dart index 30467e60..d94023b5 100644 --- a/packages/mustache/example/main.dart +++ b/packages/mustache/example/main.dart @@ -3,9 +3,9 @@ import 'package:angel_mustache/angel_mustache.dart'; import 'package:file/file.dart'; import 'package:file/local.dart'; -const FileSystem fs = const LocalFileSystem(); +const FileSystem fs = LocalFileSystem(); -configureServer(Angel app) async { +void configureServer(Angel app) async { // Run the plug-in await app.configure(mustache(fs.directory('views'))); diff --git a/packages/mustache/lib/angel_mustache.dart b/packages/mustache/lib/angel_mustache.dart index ce758fa2..b231ef92 100644 --- a/packages/mustache/lib/angel_mustache.dart +++ b/packages/mustache/lib/angel_mustache.dart @@ -1,32 +1,38 @@ library angel_mustache; +import 'dart:async'; + import 'package:angel_framework/angel_framework.dart'; import 'package:file/file.dart'; -import 'package:mustache4dart/mustache4dart.dart' show render; +import 'package:mustache_template/mustache_template.dart' as viewer; import 'package:path/path.dart' as p; import 'src/cache.dart'; import 'src/mustache_context.dart'; -mustache(Directory viewsDirectory, - {String fileExtension: '.mustache', String partialsPath: './partials'}) { - Directory partialsDirectory = viewsDirectory.fileSystem +Future Function(Angel app) mustache(Directory viewsDirectory, + {String fileExtension = '.mustache', String partialsPath = './partials'}) { + var partialsDirectory = viewsDirectory.fileSystem .directory(p.join(p.fromUri(viewsDirectory.uri), partialsPath)); - MustacheContext context = - new MustacheContext(viewsDirectory, partialsDirectory, fileExtension); + var context = + MustacheContext(viewsDirectory, partialsDirectory, fileExtension); - MustacheViewCache cache = new MustacheViewCache(context); + var cache = MustacheViewCache(context); return (Angel app) async { - app.viewGenerator = (String name, [Map data]) async { - var partialsProvider; - partialsProvider = (String name) { - String template = cache.getPartialSync(name, app); - return render(template, data ?? {}, partial: partialsProvider); + app.viewGenerator = (String name, [Map? data]) async { + //var partialsProvider; + var partialsProvider = (String name) { + var template = cache.getPartialSync(name, app)!; + //return render(template, data ?? {}, partial: partialsProvider); + return viewer.Template(template, name: name); }; - String viewTemplate = await cache.getView(name, app); - return await render(viewTemplate, data ?? {}, partial: partialsProvider); + var viewTemplate = await (cache.getView(name, app)); + //return await render(viewTemplate, data ?? {}, partial: partialsProvider); + var t = viewer.Template(viewTemplate ?? '', + partialResolver: partialsProvider); + return t.renderString(data ?? {}); }; }; } diff --git a/packages/mustache/lib/src/cache.dart b/packages/mustache/lib/src/cache.dart index 6c8f92bd..912306ef 100644 --- a/packages/mustache/lib/src/cache.dart +++ b/packages/mustache/lib/src/cache.dart @@ -6,54 +6,57 @@ import 'package:angel_framework/angel_framework.dart'; import 'package:angel_mustache/src/mustache_context.dart'; class MustacheViewCache { - /** - * The context for which views and partials are - * served from. - */ - MustacheContext context; + /// The context for which views and partials are + /// served from. + MustacheContext? context; - HashMap viewCache = new HashMap(); - HashMap partialCache = new HashMap(); + HashMap viewCache = HashMap(); + HashMap partialCache = HashMap(); MustacheViewCache([this.context]); - Future getView(String viewName, Angel app) async { - if (app.isProduction) { + Future getView(String viewName, Angel app) async { + if (app.environment.isProduction) { if (viewCache.containsKey(viewName)) { return viewCache[viewName]; } } - File viewFile = context.resolveView(viewName); + var viewFile = context?.resolveView(viewName); + if (viewFile == null) { + throw FileSystemException('View "$viewName" was not found.', 'null'); + } if (viewFile.existsSync()) { - String viewTemplate = await viewFile.readAsString(); - if (app.isProduction) { - this.viewCache[viewName] = viewTemplate; + var viewTemplate = await viewFile.readAsString(); + if (app.environment.isProduction) { + viewCache[viewName] = viewTemplate; } return viewTemplate; - } else - throw new FileSystemException( + } else { + throw FileSystemException( 'View "$viewName" was not found.', viewFile.path); + } } - String getPartialSync(String partialName, Angel app) { - if (app.isProduction) { + String? getPartialSync(String partialName, Angel app) { + if (app.environment.isProduction) { if (partialCache.containsKey(partialName)) { return partialCache[partialName]; } } - File partialFile = context.resolvePartial(partialName); + var partialFile = context!.resolvePartial(partialName); if (partialFile.existsSync()) { - String partialTemplate = partialFile.readAsStringSync(); - if (app.isProduction) { - this.partialCache[partialName] = partialTemplate; + var partialTemplate = partialFile.readAsStringSync(); + if (app.environment.isProduction) { + partialCache[partialName] = partialTemplate; } return partialTemplate; - } else - throw new FileSystemException( + } else { + throw FileSystemException( 'View "$partialName" was not found.', partialFile.path); + } } } diff --git a/packages/mustache/lib/src/mustache_context.dart b/packages/mustache/lib/src/mustache_context.dart index 9461f82e..7a56be07 100644 --- a/packages/mustache/lib/src/mustache_context.dart +++ b/packages/mustache/lib/src/mustache_context.dart @@ -1,20 +1,19 @@ import 'package:file/file.dart'; -import 'package:path/path.dart' as path; class MustacheContext { - Directory viewDirectory; + Directory? viewDirectory; - Directory partialDirectory; + Directory? partialDirectory; - String extension; + String? extension; MustacheContext([this.viewDirectory, this.partialDirectory, this.extension]); File resolveView(String viewName) { - return viewDirectory.childFile('${viewName}${extension}'); + return viewDirectory!.childFile('$viewName$extension'); } File resolvePartial(String partialName) { - return partialDirectory.childFile('${partialName}${extension}'); + return partialDirectory!.childFile('$partialName$extension'); } } diff --git a/packages/mustache/pubspec.yaml b/packages/mustache/pubspec.yaml index e7ec8b1f..02879566 100644 --- a/packages/mustache/pubspec.yaml +++ b/packages/mustache/pubspec.yaml @@ -1,16 +1,20 @@ name: angel_mustache -description: Mustache view generator for Angel. -author: thosakwe -homepage: https://github.com/angel-dart/angel_mustache version: 2.0.0 +description: Mustache view generator for Angel. +homepage: https://github.com/angel-dart/angel_mustache +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: angel_framework: #^2.0.0-alpha - path: ../framework - file: ^5.0.0 - mustache4dart: ^3.0.0-dev - path: ^1.0.0 + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + file: ^6.1.2 + mustache_template: ^2.0.0 + path: ^1.8.0 dev_dependencies: - http: ^0.12.2 - test: ^1.15.7 + http: ^0.13.3 + test: ^1.17.8 + pedantic: ^1.11.1 diff --git a/packages/mustache/test/all_test.dart b/packages/mustache/test/all_test.dart index cc5c859f..91e6a2a2 100644 --- a/packages/mustache/test/all_test.dart +++ b/packages/mustache/test/all_test.dart @@ -1,30 +1,31 @@ import 'dart:async'; import 'package:angel_framework/angel_framework.dart'; import 'package:angel_mustache/angel_mustache.dart'; +import 'package:file/file.dart'; import 'package:file/local.dart'; import 'package:test/test.dart'; -main() async { - Angel angel = new Angel(); +void main() async { + var angel = Angel(); await angel.configure(mustache(const LocalFileSystem().directory('./test'))); test('can render templates', () async { - var hello = await angel.viewGenerator('hello', {'name': 'world'}); - var bar = await angel.viewGenerator('foo/bar', {'framework': 'angel'}); + var hello = await angel.viewGenerator!('hello', {'name': 'world'}); + var bar = await angel.viewGenerator!('foo/bar', {'framework': 'angel'}); - expect(hello, equals("Hello, world!")); - expect(bar, equals("angel_framework")); + expect(hello, equals('Hello, world!')); + expect(bar, equals('angel_framework')); }); test('throws if view is not found', () { - expect(new Future(() async { - var fails = await angel.viewGenerator('fail', {'this_should': 'fail'}); + expect(Future(() async { + var fails = await angel.viewGenerator!('fail', {'this_should': 'fail'}); print(fails); - }), throws); + }), throwsA(isA())); }); - test("partials", () async { - var withPartial = await angel.viewGenerator('with-partial'); - expect(withPartial, equals("Hello, world!")); + test('partials', () async { + var withPartial = await angel.viewGenerator!('with-partial'); + expect(withPartial, equals('Hello, world!')); }); } diff --git a/packages/paginate/AUTHORS.md b/packages/paginate/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/paginate/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/paginate/CHANGELOG.md b/packages/paginate/CHANGELOG.md index 6d5318af..f714a45d 100644 --- a/packages/paginate/CHANGELOG.md +++ b/packages/paginate/CHANGELOG.md @@ -1,2 +1,5 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 2.0.0 * Dart2 + Angel2 update. \ No newline at end of file diff --git a/packages/paginate/LICENSE b/packages/paginate/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/paginate/LICENSE +++ b/packages/paginate/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/paginate/analysis_options.yaml b/packages/paginate/analysis_options.yaml new file mode 100644 index 00000000..c230cee7 --- /dev/null +++ b/packages/paginate/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:pedantic/analysis_options.yaml +analyzer: + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/paginate/example/main.dart b/packages/paginate/example/main.dart index eb83cd03..18e129b3 100644 --- a/packages/paginate/example/main.dart +++ b/packages/paginate/example/main.dart @@ -1,11 +1,11 @@ import 'package:angel_paginate/angel_paginate.dart'; -main() { +void main() { var iterable = [1, 2, 3, 4]; - var p = new Paginator(iterable); + var p = Paginator(iterable); // Get the current page (default: page 1) - var page = p.current; + var page = p.current!; print(page.total); print(page.startIndex); print(page.data); // The actual items on this page. diff --git a/packages/paginate/lib/angel_paginate.dart b/packages/paginate/lib/angel_paginate.dart index 34c34a25..64f41b93 100644 --- a/packages/paginate/lib/angel_paginate.dart +++ b/packages/paginate/lib/angel_paginate.dart @@ -1,7 +1,7 @@ /// Efficiently paginates collections of items in an object-oriented manner. class Paginator { final Map> _cache = {}; - PaginationResult _current; + PaginationResult? _current; int _page = 0; /// The collection of items to be paginated. @@ -15,7 +15,7 @@ class Paginator { /// For example, you would only have to paginate page 1 once. Future calls would return a cached version. final bool useCache; - Paginator(this._items, {this.itemsPerPage: 5, this.useCache: true}); + Paginator(this._items, {this.itemsPerPage = 5, this.useCache = true}); /// Returns `true` if there are more items at lesser page indices than the current one. bool get canGoBack => _page > 0; @@ -37,21 +37,23 @@ class Paginator { /// Fetches the current page. This will be cached until [back] or [next] is called. /// /// If [useCache] is `true` (default), then computations will be cached even after the page changes. - PaginationResult get current { - if (_current != null) + PaginationResult? get current { + if (_current != null) { return _current; - else + } else { return _current = _getPage(); + } } PaginationResult _computePage() { var len = _items.length; - var it = _items.skip(_page * (itemsPerPage ?? 5)); + //var it = _items.skip(_page * (itemsPerPage ?? 5)); + var it = _items.skip(_page * (itemsPerPage)); var offset = len - it.length; it = it.take(itemsPerPage); var last = _lastPage(); // print('cur: $_page, last: $last'); - return new _PaginationResultImpl(it, + return _PaginationResultImpl(it, currentPage: _page + 1, previousPage: _page <= 0 ? -1 : _page, nextPage: _page >= last - 1 ? -1 : _page + 2, @@ -63,10 +65,11 @@ class Paginator { } PaginationResult _getPage() { - if (useCache != false) + if (useCache != false) { return _cache.putIfAbsent(_page, () => _computePage()); - else + } else { return _computePage(); + } } int _lastPage() { @@ -110,40 +113,40 @@ class Paginator { /// Stores the result of a pagination. abstract class PaginationResult { factory PaginationResult.fromMap(Map map) => - new _PaginationResultImpl((map['data'] as Iterable).cast(), - currentPage: map['current_page'], - endIndex: map['end_index'], - itemsPerPage: map['items_per_page'], - nextPage: map['next_page'], - previousPage: map['previous_page'], - startIndex: map['start_index'], - total: map['total']); + _PaginationResultImpl((map['data'] as List).cast(), + currentPage: map['current_page'] as int?, + endIndex: map['end_index'] as int?, + itemsPerPage: map['items_per_page'] as int?, + nextPage: map['next_page'] as int?, + previousPage: map['previous_page'] as int?, + startIndex: map['start_index'] as int?, + total: map['total'] as int?); - List get data; + Iterable get data; - int get currentPage; + int? get currentPage; - int get previousPage; + int? get previousPage; - int get nextPage; + int? get nextPage; - int get itemsPerPage; + int? get itemsPerPage; - int get total; + int? get total; - int get startIndex; + int? get startIndex; - int get endIndex; + int? get endIndex; Map toJson(); } class _PaginationResultImpl implements PaginationResult { final Iterable _data; - Iterable _cachedData; + Iterable? _cachedData; @override - final int currentPage; + final int? currentPage; _PaginationResultImpl(this._data, {this.currentPage, @@ -155,25 +158,25 @@ class _PaginationResultImpl implements PaginationResult { this.total}); @override - List get data => _cachedData ?? (_cachedData = new List.from(_data)); + Iterable get data => _cachedData ?? (_cachedData = List.from(_data)); @override - final int endIndex; + final int? endIndex; @override - final int itemsPerPage; + final int? itemsPerPage; @override - final int nextPage; + final int? nextPage; @override - final int previousPage; + final int? previousPage; @override - final int startIndex; + final int? startIndex; @override - final int total; + final int? total; @override Map toJson() { diff --git a/packages/paginate/pubspec.yaml b/packages/paginate/pubspec.yaml index 4e943dce..75c6744e 100644 --- a/packages/paginate/pubspec.yaml +++ b/packages/paginate/pubspec.yaml @@ -1,15 +1,22 @@ name: angel_paginate -version: 2.0.0 +version: 3.0.0 description: Platform-agnostic pagination library, with custom support for the Angel framework. -author: Tobe O homepage: https://github.com/angel-dart/paginate +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework dev_dependencies: - angel_test: #^2.0.0 - path: ../test - logging: ^0.11.0 - test: ^1.15.7 \ No newline at end of file + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + logging: ^1.0.1 + test: ^1.17.8 + pedantic: ^1.11.1 \ No newline at end of file diff --git a/packages/paginate/test/all_test.dart b/packages/paginate/test/all_test.dart index c9ba44be..d96efa4f 100644 --- a/packages/paginate/test/all_test.dart +++ b/packages/paginate/test/all_test.dart @@ -2,7 +2,7 @@ import 'package:test/test.dart'; import 'bounds_test.dart' as bounds; import 'paginate_test.dart' as paginate; -main() { +void main() { group('bounds', bounds.main); group('paginate', paginate.main); } diff --git a/packages/paginate/test/bounds_test.dart b/packages/paginate/test/bounds_test.dart index 22eadf48..49656777 100644 --- a/packages/paginate/test/bounds_test.dart +++ b/packages/paginate/test/bounds_test.dart @@ -11,15 +11,15 @@ final List> mjAlbums = [ {'michael': 'jackson'} ]; -main() { - TestClient client; +void main() { + late TestClient client; setUp(() async { var app = Angel(); app.get('/api/songs', (req, res) { var p = Paginator(mjAlbums, itemsPerPage: mjAlbums.length); - p.goToPage(int.parse(req.queryParameters['page'] ?? '1')); + p.goToPage(int.parse(req.queryParameters['page'] as String? ?? '1')); return p.current; }); @@ -41,7 +41,7 @@ main() { queryParameters: {r'$limit': (mjAlbums.length + 1).toString()})); var page = PaginationResult>.fromMap( - json.decode(response.body)); + json.decode(response.body) as Map); print('page: ${page.toJson()}'); diff --git a/packages/paginate/test/paginate_test.dart b/packages/paginate/test/paginate_test.dart index 4e6b713e..b4d0917a 100644 --- a/packages/paginate/test/paginate_test.dart +++ b/packages/paginate/test/paginate_test.dart @@ -53,7 +53,7 @@ void main() { test('first page', () { var paginator = Paginator(DATA); expect(paginator.pageNumber, 1); - var r = paginator.current; + var r = paginator.current!; print(r.toJson()); expect(r.total, DATA.length); expect(r.itemsPerPage, 5); @@ -62,14 +62,14 @@ void main() { expect(r.nextPage, 2); expect(r.startIndex, 0); expect(r.endIndex, 4); - expect(r.data, DATA.skip(r.startIndex).take(r.itemsPerPage).toList()); + expect(r.data, DATA.skip(r.startIndex!).take(r.itemsPerPage!).toList()); }); }); test('third page', () { var paginator = Paginator(DATA)..goToPage(3); expect(paginator.pageNumber, 3); - var r = paginator.current; + var r = paginator.current!; print(r.toJson()); expect(r.total, DATA.length); expect(r.itemsPerPage, 5); @@ -78,7 +78,7 @@ void main() { expect(r.nextPage, 4); expect(r.startIndex, 10); expect(r.endIndex, 14); - expect(r.data, DATA.skip(r.startIndex).take(r.itemsPerPage).toList()); + expect(r.data, DATA.skip(r.startIndex!).take(r.itemsPerPage!).toList()); paginator.back(); expect(paginator.pageNumber, 2); @@ -87,7 +87,7 @@ void main() { test('last page', () { var paginator = Paginator(DATA); paginator.goToPage(paginator.lastPageNumber); - var r = paginator.current; + var r = paginator.current!; expect(r.total, DATA.length); expect(r.itemsPerPage, 5); expect(r.previousPage, paginator.lastPageNumber - 1); @@ -96,7 +96,7 @@ void main() { expect(r.startIndex, (paginator.lastPageNumber - 1) * 5); expect(r.endIndex, r.startIndex); expect(r.data, [DATA.last]); - expect(r.data, DATA.skip(r.startIndex).take(r.itemsPerPage).toList()); + expect(r.data, DATA.skip(r.startIndex!).take(r.itemsPerPage!).toList()); }); test('dump pages', () { @@ -104,14 +104,14 @@ void main() { print('${paginator.lastPageNumber} page(s) of data:'); do { - print(' * Page #${paginator.pageNumber}: ${paginator.current.data}'); + print(' * Page #${paginator.pageNumber}: ${paginator.current!.data}'); paginator.next(); } while (paginator.canGoForward); }); test('empty collection', () { var paginator = Paginator([]); - var page = paginator.current; + var page = paginator.current!; print(page.toJson()); expect(page.total, 0); diff --git a/packages/poll/AUTHORS.md b/packages/poll/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/poll/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/poll/CHANGELOG.md b/packages/poll/CHANGELOG.md index 6ae2c706..c983dc70 100644 --- a/packages/poll/CHANGELOG.md +++ b/packages/poll/CHANGELOG.md @@ -1,2 +1,5 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 1.0.0 * Created package + tests \ No newline at end of file diff --git a/packages/poll/LICENSE b/packages/poll/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/poll/LICENSE +++ b/packages/poll/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/poll/analysis_options.yaml b/packages/poll/analysis_options.yaml index 518eb901..c230cee7 100644 --- a/packages/poll/analysis_options.yaml +++ b/packages/poll/analysis_options.yaml @@ -1,2 +1,4 @@ +include: package:pedantic/analysis_options.yaml analyzer: - strong-mode: true \ No newline at end of file + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/poll/example/main.dart b/packages/poll/example/main.dart index 8ac5c6da..4b8e2739 100644 --- a/packages/poll/example/main.dart +++ b/packages/poll/example/main.dart @@ -1,11 +1,11 @@ import 'package:angel_client/io.dart'; import 'package:angel_poll/angel_poll.dart'; -main() { - var app = new Rest('http://localhost:3000'); +void main() { + var app = Rest('http://localhost:3000'); - var todos = new ServiceList( - new PollingService( + var todos = ServiceList( + PollingService( // Typically, you'll pass a REST-based service instance here. app.service('api/todos'), diff --git a/packages/poll/lib/angel_poll.dart b/packages/poll/lib/angel_poll.dart index db1b0b8d..095bc4a6 100644 --- a/packages/poll/lib/angel_poll.dart +++ b/packages/poll/lib/angel_poll.dart @@ -41,21 +41,20 @@ class PollingService extends Service { final List _items = []; final List _subs = []; - final StreamController _onIndexed = new StreamController(), - _onRead = new StreamController(), - _onCreated = new StreamController(), - _onModified = new StreamController(), - _onUpdated = new StreamController(), - _onRemoved = new StreamController(); + final StreamController> _onIndexed = StreamController(), + _onRead = StreamController(), + _onCreated = StreamController(), + _onModified = StreamController(), + _onUpdated = StreamController(), + _onRemoved = StreamController(); - Timer _timer; + late Timer _timer; @override Angel get app => inner.app; - // TODO: To revisit this logic @override - Stream get onIndexed => _onIndexed.stream; + Stream> get onIndexed => _onIndexed.stream; @override Stream get onRead => _onRead.stream; @@ -73,16 +72,18 @@ class PollingService extends Service { Stream get onRemoved => _onRemoved.stream; PollingService(this.inner, Duration interval, - {this.checkForCreated: true, - this.checkForModified: true, - this.checkForRemoved: true, - this.idField: 'id', - this.asPaginated: false, - EqualityBy compareId, - this.compareItems: const MapEquality()}) - : compareId = compareId ?? new EqualityBy((map) => map[idField ?? 'id']) { - _timer = new Timer.periodic(interval, (_) { - index().catchError(_onIndexed.addError); + {this.checkForCreated = true, + this.checkForModified = true, + this.checkForRemoved = true, + this.idField = 'id', + this.asPaginated = false, + EqualityBy? compareId, + this.compareItems = const MapEquality()}) + : compareId = compareId ?? EqualityBy((map) => map[idField]) { + _timer = Timer.periodic(interval, (_) { + index().catchError((error) { + _onIndexed.addError(error as Object); + }); }); var streams = { @@ -109,20 +110,21 @@ class PollingService extends Service { Future close() async { _timer.cancel(); _subs.forEach((s) => s.cancel()); - _onIndexed.close(); - _onRead.close(); - _onCreated.close(); - _onModified.close(); - _onUpdated.close(); - _onRemoved.close(); + await _onIndexed.close(); + await _onRead.close(); + await _onCreated.close(); + await _onModified.close(); + await _onUpdated.close(); + await _onRemoved.close(); } // TODO: To revisit this logic @override - Future index([Map params]) { + Future> index([Map? params]) { return inner.index().then((data) { //return asPaginated == true ? data['data'] : data; - return asPaginated == true ? data[0] : data; + //return asPaginated == true ? data[0] : data; + return data!; }); } @@ -132,17 +134,17 @@ class PollingService extends Service { } */ @override - Future remove(id, [Map params]) { + Future remove(id, [Map? params]) { return inner.remove(id, params).then((result) { _items.remove(result); return result; }).catchError(_onRemoved.addError); } - _handleUpdate(result) { - int index = -1; + dynamic _handleUpdate(result) { + var index = -1; - for (int i = 0; i < _items.length; i++) { + for (var i = 0; i < _items.length; i++) { if (compareId.equals(_items[i], result)) { index = i; break; @@ -157,7 +159,7 @@ class PollingService extends Service { } @override - Future update(id, data, [Map params]) { + Future update(id, data, [Map? params]) { return inner .update(id, data, params) .then(_handleUpdate) @@ -165,7 +167,7 @@ class PollingService extends Service { } @override - Future modify(id, data, [Map params]) { + Future modify(id, data, [Map? params]) { return inner .modify(id, data, params) .then(_handleUpdate) @@ -173,7 +175,7 @@ class PollingService extends Service { } @override - Future create(data, [Map params]) { + Future create(data, [Map? params]) { return inner.create(data, params).then((result) { _items.add(result); return result; @@ -181,18 +183,19 @@ class PollingService extends Service { } @override - Future read(id, [Map params]) { + Future read(id, [Map? params]) { return inner.read(id, params); } - void _handleIndexed(data) { - var items = asPaginated == true ? data['data'] : data; - bool changesComputed = false; + void _handleIndexed(List data) { + //var items = asPaginated == true ? data['data'] : data; + var items = data; + var changesComputed = false; if (checkForCreated != false) { var newItems = {}; - for (int i = 0; i < items.length; i++) { + for (var i = 0; i < items.length; i++) { var item = items[i]; if (!_items.any((i) => compareId.equals(i, item))) { @@ -202,7 +205,7 @@ class PollingService extends Service { newItems.forEach((index, item) { _items.insert(index, item); - _onCreated.add(item); + _onCreated.add([item]); }); changesComputed = newItems.isNotEmpty; @@ -211,7 +214,7 @@ class PollingService extends Service { if (checkForRemoved != false) { var removedItems = {}; - for (int i = 0; i < _items.length; i++) { + for (var i = 0; i < _items.length; i++) { var item = _items[i]; if (!items.any((i) => compareId.equals(i, item))) { @@ -221,7 +224,7 @@ class PollingService extends Service { removedItems.forEach((index, item) { _items.removeAt(index); - _onRemoved.add(item); + _onRemoved.add([item]); }); changesComputed = changesComputed || removedItems.isNotEmpty; @@ -231,7 +234,7 @@ class PollingService extends Service { var modifiedItems = {}; for (var item in items) { - for (int i = 0; i < _items.length; i++) { + for (var i = 0; i < _items.length; i++) { var localItem = _items[i]; if (compareId.equals(item, localItem)) { @@ -244,7 +247,7 @@ class PollingService extends Service { } modifiedItems.forEach((index, item) { - _onModified.add(_items[index] = item); + _onModified.add([_items[index] = item]); }); changesComputed = changesComputed || modifiedItems.isNotEmpty; @@ -253,8 +256,8 @@ class PollingService extends Service { if (!changesComputed) { _items ..clear() - ..addAll(items); - _onIndexed.add(items); + ..add(items); + _onIndexed.add([items]); } } } diff --git a/packages/poll/pubspec.yaml b/packages/poll/pubspec.yaml index d56bd24d..cceafd0d 100644 --- a/packages/poll/pubspec.yaml +++ b/packages/poll/pubspec.yaml @@ -1,16 +1,23 @@ name: angel_poll -version: 1.0.0 +version: 2.0.0 description: package:angel_client support for "realtime" interactions with Angel via long polling. -author: Tobe O +publish_to: none environment: - sdk: ">=2.7.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' homepage: https://github.com/angel-dart/poll dependencies: angel_client: # ^1.0.0 - path: ../client - async: ">=1.10.0 <3.0.0" - collection: ^1.14.12 + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/client + async: ^2.7.0 + collection: ^1.15.0 dev_dependencies: - angel_test: # ^1.1.0 - path: ../test - test: ^1.15.7 \ No newline at end of file + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + test: ^1.17.8 + pedantic: ^1.11.1 \ No newline at end of file diff --git a/packages/poll/test/all_test.dart b/packages/poll/test/all_test.dart index 32840006..f709af1e 100644 --- a/packages/poll/test/all_test.dart +++ b/packages/poll/test/all_test.dart @@ -1,4 +1,5 @@ import 'package:angel_framework/angel_framework.dart' as srv; +import 'package:angel_container/mirrors.dart'; import 'package:angel_poll/angel_poll.dart'; import 'package:angel_test/angel_test.dart'; import 'package:async/async.dart'; @@ -6,13 +7,18 @@ import 'package:logging/logging.dart'; import 'package:test/test.dart'; void main() { - srv.Service store; - TestClient client; - PollingService pollingService; + late srv.Service store; + late TestClient client; + late PollingService pollingService; + + var created; + late StreamQueue onCreated; + late StreamQueue onModified; + late StreamQueue onRemoved; setUp(() async { - var app = new srv.Angel(); - app.logger = new Logger.detached('angel_poll') + var app = srv.Angel(reflector: MirrorsReflector()); + app.logger = Logger.detached('angel_poll') ..onRecord.listen((rec) { print(rec); if (rec.error != null) { @@ -23,43 +29,37 @@ void main() { store = app.use( '/api/todos', - new srv.MapService( + srv.MapService( autoIdAndDateFields: false, ), ); client = await connectTo(app); - pollingService = new PollingService( + pollingService = PollingService( client.service('api/todos'), const Duration(milliseconds: 100), ); + + onCreated = StreamQueue(pollingService.onCreated); + onModified = StreamQueue(pollingService.onModified); + onRemoved = StreamQueue(pollingService.onRemoved); + + created = await store.create({ + 'id': '0', + 'text': 'Clean your room', + 'completed': false, + }); }); - tearDown(() => client.close()); + tearDown(() { + onCreated.cancel(); + onModified.cancel(); + onRemoved.cancel(); + client.close(); + }); group('events', () { - var created; - StreamQueue onCreated, onModified, onRemoved; - - setUp(() async { - onCreated = new StreamQueue(pollingService.onCreated); - onModified = new StreamQueue(pollingService.onModified); - onRemoved = new StreamQueue(pollingService.onRemoved); - - created = await store.create({ - 'id': '0', - 'text': 'Clean your room', - 'completed': false, - }); - }); - - tearDown(() { - onCreated.cancel(); - onModified.cancel(); - onRemoved.cancel(); - }); - test('fires indexed', () async { var indexed = await pollingService.index(); print(indexed); @@ -80,7 +80,7 @@ void main() { var result = await onModified.next; print(result); - expect(result, new Map.from(created)..['text'] = 'go to school'); + expect(result, Map.from({'': created})..['text'] = 'go to school'); }); test('manual modify', () async { @@ -91,7 +91,7 @@ void main() { var result = await onModified.next; print(result); - expect(result, new Map.from(created)..['text'] = 'eat'); + expect(result, Map.from({'': created})..['text'] = 'eat'); }); test('fires removed', () async { diff --git a/packages/redis/AUTHORS.md b/packages/redis/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/redis/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/redis/CHANGELOG.md b/packages/redis/CHANGELOG.md index b23475f1..e27f0900 100644 --- a/packages/redis/CHANGELOG.md +++ b/packages/redis/CHANGELOG.md @@ -1,2 +1,5 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 1.0.0 * First version. \ No newline at end of file diff --git a/packages/redis/LICENSE b/packages/redis/LICENSE index 8f65b579..f8e6088a 100644 --- a/packages/redis/LICENSE +++ b/packages/redis/LICENSE @@ -1,6 +1,6 @@ -MIT License (MIT) +MIT License -Copyright (c) 2021 dukefirehawk.com +Copyright (c) 2018 The Angel Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/redis/analysis_options.yaml b/packages/redis/analysis_options.yaml new file mode 100644 index 00000000..c230cee7 --- /dev/null +++ b/packages/redis/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:pedantic/analysis_options.yaml +analyzer: + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/redis/example/main.dart b/packages/redis/example/main.dart index c5614d23..3f070ba6 100644 --- a/packages/redis/example/main.dart +++ b/packages/redis/example/main.dart @@ -1,17 +1,18 @@ import 'package:angel_redis/angel_redis.dart'; import 'package:resp_client/resp_client.dart'; import 'package:resp_client/resp_commands.dart'; +import 'package:resp_client/resp_server.dart'; -main() async { +void main() async { var connection = await connectSocket('localhost'); - var client = new RespClient(connection); - var service = new RedisService(new RespCommands(client), prefix: 'example'); + var client = RespClient(connection); + var service = RedisService(RespCommandsTier2(client), prefix: 'example'); // Create an object await service.create({'id': 'a', 'hello': 'world'}); // Read it... - var read = await service.read('a'); + var read = await (service.read('a')); print(read['hello']); // Delete it. diff --git a/packages/redis/lib/src/redis_service.dart b/packages/redis/lib/src/redis_service.dart index 1651a73d..0b15f42a 100644 --- a/packages/redis/lib/src/redis_service.dart +++ b/packages/redis/lib/src/redis_service.dart @@ -6,92 +6,99 @@ import 'package:resp_client/resp_commands.dart'; /// An Angel service that reads and writes JSON within a Redis store. class RedisService extends Service> { - final RespCommands respCommands; + final RespCommandsTier2 respCommands; /// An optional string prefixed to keys before they are inserted into Redis. /// /// Consider using this if you are using several different Redis collections /// within a single application. - final String prefix; + final String? prefix; RedisService(this.respCommands, {this.prefix}); - String _applyPrefix(String id) => prefix == null ? id : '$prefix:$id'; + String? _applyPrefix(String? id) => prefix == null ? id : '$prefix:$id'; @override Future>> index( - [Map params]) async { + [Map? params]) async { var result = - await respCommands.client.writeArrayOfBulk(['KEYS', _applyPrefix('*')]); + //await respCommands.client.writeArrayOfBulk(['KEYS', _applyPrefix('*')]); + await respCommands.tier1.tier0.execute(['KEYS', _applyPrefix('*')]); var keys = result.payload.map((RespType s) => s.payload) as Iterable; if (keys.isEmpty) return []; - result = await respCommands.client.writeArrayOfBulk(['MGET']..addAll(keys)); - return result.payload - .map>( - (RespType s) => json.decode(s.payload) as Map) - .toList(); + //result = await respCommands.client.writeArrayOfBulk(['MGET']..addAll(keys)); + result = await respCommands.tier1.tier0.execute(['MGET', ...keys]); + + if (result.isArray) { + return (result as List) + .map>((RespType s) => + json.decode(s.payload as String) as Map) + .toList(); + } else { + // TODO: To be reviewed for handling none array objects + return [json.decode(result.payload as String) as Map]; + } } @override Future> read(String id, - [Map params]) async { - var value = await respCommands.get(_applyPrefix(id)); + [Map? params]) async { + var value = await respCommands.get(_applyPrefix(id)!); if (value == null) { - throw new AngelHttpException.notFound( - message: 'No record found for ID $id'); + throw AngelHttpException.notFound(message: 'No record found for ID $id'); } else { - return json.decode(value); + return json.decode(value) as Map; } } @override - Future> create(Map data, - [Map params]) async { - String id; - if (data['id'] != null) - id = data['id'] as String; - else { - var keyVar = await respCommands.client - .writeArrayOfBulk(['INCR', _applyPrefix('angel_redis:id')]); + Future> create(Map? data, + [Map? params]) async { + String? id; + if (data!['id'] != null) { + id = data['id'] as String?; + } else { + var keyVar = await respCommands.tier1.tier0 + .execute(['INCR', _applyPrefix('angel_redis:id')]); id = keyVar.payload.toString(); - data = new Map.from(data)..['id'] = id; + data = Map.from(data)..['id'] = id; } - await respCommands.set(_applyPrefix(id), json.encode(data)); + await respCommands.set(_applyPrefix(id)!, json.encode(data)); return data; } @override - Future> modify(String id, Map data, - [Map params]) async { - var input = await read(id); - input.addAll(data); + Future> modify(String id, Map? data, + [Map? params]) async { + var input = await (read(id)); + input.addAll(data!); return await update(id, input, params); } @override - Future> update(String id, Map data, - [Map params]) async { - data = new Map.from(data)..['id'] = id; - await respCommands.set(_applyPrefix(id), json.encode(data)); + Future> update(String id, Map? data, + [Map? params]) async { + data = Map.from(data!)..['id'] = id; + await respCommands.set(_applyPrefix(id)!, json.encode(data)); return data; } @override Future> remove(String id, - [Map params]) async { - var client = respCommands.client; - await client.writeArrayOfBulk(['MULTI']); - await client.writeArrayOfBulk(['GET', _applyPrefix(id)]); - await client.writeArrayOfBulk(['DEL', _applyPrefix(id)]); - var result = await client.writeArrayOfBulk(['EXEC']); + [Map? params]) async { + var client = respCommands.tier1.tier0; + await client.execute(['MULTI']); + await client.execute(['GET', _applyPrefix(id)]); + await client.execute(['DEL', _applyPrefix(id)]); + var result = await client.execute(['EXEC']); var str = result.payload[0] as RespBulkString; - if (str.payload == null) - throw new AngelHttpException.notFound( - message: 'No record found for ID $id'); - else - return json.decode(str.payload); + if (str.payload == null) { + throw AngelHttpException.notFound(message: 'No record found for ID $id'); + } else { + return json.decode(str.payload!) as Map; + } } } diff --git a/packages/redis/pubspec.yaml b/packages/redis/pubspec.yaml index a339cb30..bdbb3420 100644 --- a/packages/redis/pubspec.yaml +++ b/packages/redis/pubspec.yaml @@ -1,15 +1,22 @@ name: angel_redis -version: 1.0.0 +version: 2.0.0 description: An Angel service provider for Redis. Works well for caching volatile data. -author: Tobe O homepage: https://github.com/angel-dart/redis +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - angel_http_exception: #^1.0.0 - path: ../http_exception - resp_client: ^0.1.6 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + angel_http_exception: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/http_exception + resp_client: ^1.2.0 dev_dependencies: - test: ^1.15.7 + test: ^1.17.8 + pedantic: ^1.11.1 diff --git a/packages/redis/test/all_test.dart b/packages/redis/test/all_test.dart index 72f7aed2..531b7b76 100644 --- a/packages/redis/test/all_test.dart +++ b/packages/redis/test/all_test.dart @@ -2,15 +2,16 @@ import 'package:angel_http_exception/angel_http_exception.dart'; import 'package:angel_redis/angel_redis.dart'; import 'package:resp_client/resp_client.dart'; import 'package:resp_client/resp_commands.dart'; +import 'package:resp_client/resp_server.dart'; import 'package:test/test.dart'; -main() async { - RespServerConnection connection; - RedisService service; +void main() async { + late RespServerConnection connection; + late RedisService service; setUp(() async { connection = await connectSocket('localhost'); - service = RedisService(RespCommands(RespClient(connection)), + service = RedisService(RespCommandsTier2(RespClient(connection)), prefix: 'angel_redis_test'); }); @@ -36,7 +37,7 @@ main() async { test('create without id', () async { var input = {'bar': 'baz'}; - var output = await service.create(input); + var output = await (service.create(input)); print(output); expect(output.keys, contains('id')); expect(output, containsPair('bar', 'baz')); diff --git a/packages/relations/AUTHORS.md b/packages/relations/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/relations/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/relations/CHANGELOG.md b/packages/relations/CHANGELOG.md new file mode 100644 index 00000000..9a5a22f6 --- /dev/null +++ b/packages/relations/CHANGELOG.md @@ -0,0 +1,5 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + +# 1.0.0 +* Initial checkin \ No newline at end of file diff --git a/packages/relations/LICENSE b/packages/relations/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/relations/LICENSE +++ b/packages/relations/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/relations/analysis_options.yaml b/packages/relations/analysis_options.yaml new file mode 100644 index 00000000..c230cee7 --- /dev/null +++ b/packages/relations/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:pedantic/analysis_options.yaml +analyzer: + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/relations/lib/src/belongs_to.dart b/packages/relations/lib/src/belongs_to.dart index 25b06c0e..6972801e 100644 --- a/packages/relations/lib/src/belongs_to.dart +++ b/packages/relations/lib/src/belongs_to.dart @@ -12,51 +12,44 @@ import 'no_service.dart'; /// * [localKey]: `userId` /// * [foreignKey]: `id` HookedServiceEventListener belongsTo(Pattern servicePath, - {String as, - String foreignKey, - String localKey, - getForeignKey(obj), - assignForeignObject(foreign, obj)}) { - String localId = localKey; + {String? as, + String? foreignKey, + String? localKey, + Function(dynamic obj)? getForeignKey, + Function(dynamic foreign, dynamic obj)? assignForeignObject}) { + var localId = localKey; var foreignName = - as?.isNotEmpty == true ? as : pluralize.singular(servicePath.toString()); + as?.isNotEmpty == true ? as! : pluralize.singular(servicePath.toString()); - if (localId == null) { - localId = foreignName + 'Id'; - // print('No local key provided for belongsTo, defaulting to \'$localId\'.'); - } + localId ??= foreignName + 'Id'; return (HookedServiceEvent e) async { var ref = e.getService(servicePath); if (ref == null) throw noService(servicePath); - _getForeignKey(obj) { - if (getForeignKey != null) + dynamic _getForeignKey(obj) { + if (getForeignKey != null) { return getForeignKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[localId]; - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[localId]; - else if (localId == null || localId == 'userId') + } else if (localId == null || localId == 'userId') { return obj.userId; - else - return reflect(obj).getField(new Symbol(localId)).reflectee; + } else { + return reflect(obj).getField(Symbol(localId)).reflectee; + } } - _assignForeignObject(foreign, obj) { - if (assignForeignObject != null) + dynamic _assignForeignObject(foreign, obj) { + if (assignForeignObject != null) { return assignForeignObject(foreign, obj); - else if (obj is Map) + } else if (obj is Map) { obj[foreignName] = foreign; - //TODO: Undefined class - //else if (obj is Extensible) - // obj.properties[foreignName] = foreign; - else - reflect(obj).setField(new Symbol(foreignName), foreign); + } else { + reflect(obj).setField(Symbol(foreignName), foreign); + } } - _normalize(obj) async { + Future _normalize(obj) async { if (obj != null) { var id = await _getForeignKey(obj); var indexed = await ref.index({ @@ -73,8 +66,10 @@ HookedServiceEventListener belongsTo(Pattern servicePath, } if (e.result is Iterable) { - await Future.wait(e.result.map(_normalize)); - } else + //await Future.wait(e.result.map(_normalize)); + await e.result.map(_normalize); + } else { await _normalize(e.result); + } }; } diff --git a/packages/relations/lib/src/belongs_to_many.dart b/packages/relations/lib/src/belongs_to_many.dart index e0f078bf..65b65840 100644 --- a/packages/relations/lib/src/belongs_to_many.dart +++ b/packages/relations/lib/src/belongs_to_many.dart @@ -12,51 +12,44 @@ import 'no_service.dart'; /// * [foreignKey]: `userId` /// * [localKey]: `id` HookedServiceEventListener belongsToMany(Pattern servicePath, - {String as, - String foreignKey, - String localKey, - getForeignKey(obj), - assignForeignObject(List foreign, obj)}) { - String localId = localKey; + {String? as, + String? foreignKey, + String? localKey, + Function(dynamic obj)? getForeignKey, + Function(dynamic foreign, dynamic obj)? assignForeignObject}) { + var localId = localKey; var foreignName = - as?.isNotEmpty == true ? as : pluralize.plural(servicePath.toString()); + as?.isNotEmpty == true ? as! : pluralize.plural(servicePath.toString()); - if (localId == null) { - localId = foreignName + 'Id'; - // print('No local key provided for belongsToMany, defaulting to \'$localId\'.'); - } + localId ??= foreignName + 'Id'; return (HookedServiceEvent e) async { var ref = e.getService(servicePath); if (ref == null) throw noService(servicePath); - _getForeignKey(obj) { - if (getForeignKey != null) + dynamic _getForeignKey(obj) { + if (getForeignKey != null) { return getForeignKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[localId]; - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[localId]; - else if (localId == null || localId == 'userId') + } else if (localId == null || localId == 'userId') { return obj.userId; - else - return reflect(obj).getField(new Symbol(localId)).reflectee; + } else { + return reflect(obj).getField(Symbol(localId)).reflectee; + } } - _assignForeignObject(foreign, obj) { - if (assignForeignObject != null) - return assignForeignObject(foreign, obj); - else if (obj is Map) + dynamic _assignForeignObject(foreign, obj) { + if (assignForeignObject != null) { + return assignForeignObject(foreign as List?, obj); + } else if (obj is Map) { obj[foreignName] = foreign; - //TODO: Undefined class - //else if (obj is Extensible) - // obj.properties[foreignName] = foreign; - else - reflect(obj).setField(new Symbol(foreignName), foreign); + } else { + reflect(obj).setField(Symbol(foreignName), foreign); + } } - _normalize(obj) async { + Future _normalize(obj) async { if (obj != null) { var id = await _getForeignKey(obj); var indexed = await ref.index({ @@ -73,8 +66,10 @@ HookedServiceEventListener belongsToMany(Pattern servicePath, } if (e.result is Iterable) { - await Future.wait(e.result.map(_normalize)); - } else + //await Future.wait(e.result.map(_normalize)); + await e.result.map(_normalize); + } else { await _normalize(e.result); + } }; } diff --git a/packages/relations/lib/src/has_many.dart b/packages/relations/lib/src/has_many.dart index 1ab1d745..cca4e9e6 100644 --- a/packages/relations/lib/src/has_many.dart +++ b/packages/relations/lib/src/has_many.dart @@ -12,51 +12,47 @@ import 'no_service.dart'; /// * [foreignKey]: `userId` /// * [localKey]: `id` HookedServiceEventListener hasMany(Pattern servicePath, - {String as, - String foreignKey, - String localKey, - getLocalKey(obj), - assignForeignObjects(foreign, obj)}) { + {String? as, + String? foreignKey, + String? localKey, + Function(dynamic obj)? getLocalKey, + Function(dynamic foreign, dynamic obj)? assignForeignObjects}) { return (HookedServiceEvent e) async { var ref = e.getService(servicePath); var foreignName = as?.isNotEmpty == true ? as : pluralize.plural(servicePath.toString()); if (ref == null) throw noService(servicePath); - _getLocalKey(obj) { - if (getLocalKey != null) + dynamic _getLocalKey(obj) { + if (getLocalKey != null) { return getLocalKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[localKey ?? 'id']; - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[localKey ?? 'id']; - else if (localKey == null || localKey == 'id') + } else if (localKey == null || localKey == 'id') { return obj.id; - else - return reflect(obj).getField(new Symbol(localKey ?? 'id')).reflectee; + } else { + return reflect(obj).getField(Symbol(localKey)).reflectee; + } } - _assignForeignObjects(foreign, obj) { - if (assignForeignObjects != null) + dynamic _assignForeignObjects(foreign, obj) { + if (assignForeignObjects != null) { return assignForeignObjects(foreign, obj); - else if (obj is Map) + } else if (obj is Map) { obj[foreignName] = foreign; - //TODO: Undefined class - //else if (obj is Extensible) - // obj.properties[foreignName] = foreign; - else - reflect(obj).setField(new Symbol(foreignName), foreign); + } else { + reflect(obj).setField(Symbol(foreignName!), foreign); + } } - _normalize(obj) async { + Future _normalize(obj) async { if (obj != null) { var id = await _getLocalKey(obj); var indexed = await ref.index({ 'query': {foreignKey ?? 'userId': id} }); - if (indexed == null || indexed is! List || indexed.isNotEmpty != true) { + if (indexed is! List || indexed.isNotEmpty != true) { await _assignForeignObjects([], obj); } else { await _assignForeignObjects(indexed, obj); @@ -65,8 +61,10 @@ HookedServiceEventListener hasMany(Pattern servicePath, } if (e.result is Iterable) { - await Future.wait(e.result.map(_normalize)); - } else + //await Future.wait(e.result.map(_normalize)); + await e.result.map(_normalize); + } else { await _normalize(e.result); + } }; } diff --git a/packages/relations/lib/src/has_many_through.dart b/packages/relations/lib/src/has_many_through.dart index c2028b30..23a6ed1d 100644 --- a/packages/relations/lib/src/has_many_through.dart +++ b/packages/relations/lib/src/has_many_through.dart @@ -5,14 +5,14 @@ import 'plural.dart' as pluralize; import 'no_service.dart'; HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath, - {String as, - String localKey, - String pivotKey, - String foreignKey, - getLocalKey(obj), - getPivotKey(obj), - getForeignKey(obj), - assignForeignObjects(foreign, obj)}) { + {String? as, + String? localKey, + String? pivotKey, + String? foreignKey, + Function(dynamic obj)? getLocalKey, + Function(dynamic obj)? getPivotKey, + Function(dynamic obj)? getForeignKey, + Function(dynamic foreign, dynamic obj)? assignForeignObjects}) { var foreignName = as?.isNotEmpty == true ? as : pluralize.plural(servicePath.toString()); @@ -20,58 +20,52 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath, var pivotService = e.getService(pivotPath); var foreignService = e.getService(servicePath); - if (pivotService == null) + if (pivotService == null) { throw noService(pivotPath); - else if (foreignService == null) throw noService(servicePath); + } else if (foreignService == null) throw noService(servicePath); - _assignForeignObjects(foreign, obj) { - if (assignForeignObjects != null) + dynamic _assignForeignObjects(foreign, obj) { + if (assignForeignObjects != null) { return assignForeignObjects(foreign, obj); - else if (obj is Map) + } else if (obj is Map) { obj[foreignName] = foreign; - //TODO: Undefined class - //else if (obj is Extensible) - // obj.properties[foreignName] = foreign; - else - reflect(obj).setField(new Symbol(foreignName), foreign); + } else { + reflect(obj).setField(Symbol(foreignName!), foreign); + } } - _getLocalKey(obj) { - if (getLocalKey != null) + dynamic _getLocalKey(obj) { + if (getLocalKey != null) { return getLocalKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[localKey ?? 'id']; - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[localKey ?? 'id']; - else if (localKey == null || localKey == 'id') + } else if (localKey == null || localKey == 'id') { return obj.id; - else - return reflect(obj).getField(new Symbol(localKey ?? 'id')).reflectee; + } else { + return reflect(obj).getField(Symbol(localKey)).reflectee; + } } - _getPivotKey(obj) { - if (getPivotKey != null) + dynamic _getPivotKey(obj) { + if (getPivotKey != null) { return getPivotKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[pivotKey ?? 'id']; - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[pivotKey ?? 'id']; - else if (pivotKey == null || pivotKey == 'id') + } else if (pivotKey == null || pivotKey == 'id') { return obj.id; - else - return reflect(obj).getField(new Symbol(pivotKey ?? 'id')).reflectee; + } else { + return reflect(obj).getField(Symbol(pivotKey)).reflectee; + } } - _normalize(obj) async { + Future _normalize(obj) async { // First, resolve pivot var id = await _getLocalKey(obj); var indexed = await pivotService.index({ 'query': {pivotKey ?? 'userId': id} }); - if (indexed == null || indexed is! List || indexed.isNotEmpty != true) { + if (indexed is! List || indexed.isNotEmpty != true) { await _assignForeignObjects([], obj); } else { // Now, resolve from foreign service @@ -81,9 +75,7 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath, 'query': {foreignKey ?? 'postId': id} }); - if (indexed == null || - indexed is! List || - indexed.isNotEmpty != true) { + if (indexed is! List || indexed.isNotEmpty != true) { await _assignForeignObjects([], pivot); } else { await _assignForeignObjects(indexed, pivot); @@ -96,8 +88,10 @@ HookedServiceEventListener hasManyThrough(String servicePath, String pivotPath, } if (e.result is Iterable) { - await Future.wait(e.result.map(_normalize)); - } else + //await Future.wait(e.result.map(_normalize)); + await e.result.map(_normalize); + } else { await _normalize(e.result); + } }; } diff --git a/packages/relations/lib/src/has_one.dart b/packages/relations/lib/src/has_one.dart index 0556bf1a..d463e823 100644 --- a/packages/relations/lib/src/has_one.dart +++ b/packages/relations/lib/src/has_one.dart @@ -12,11 +12,11 @@ import 'no_service.dart'; /// * [foreignKey]: `userId` /// * [localKey]: `id` HookedServiceEventListener hasOne(Pattern servicePath, - {String as, - String foreignKey, - String localKey, - getLocalKey(obj), - assignForeignObject(foreign, obj)}) { + {String? as, + String? foreignKey, + String? localKey, + Function(dynamic obj)? getLocalKey, + Function(dynamic foreign, dynamic obj)? assignForeignObject}) { return (HookedServiceEvent e) async { var ref = e.getService(servicePath); var foreignName = as?.isNotEmpty == true @@ -24,34 +24,29 @@ HookedServiceEventListener hasOne(Pattern servicePath, : pluralize.singular(servicePath.toString()); if (ref == null) throw noService(servicePath); - _getLocalKey(obj) { - if (getLocalKey != null) + dynamic _getLocalKey(obj) { + if (getLocalKey != null) { return getLocalKey(obj); - else if (obj is Map) + } else if (obj is Map) { return obj[localKey ?? 'id']; - - //TODO: Undefined class - //else if (obj is Extensible) - // return obj.properties[localKey ?? 'id']; - else if (localKey == null || localKey == 'id') + } else if (localKey == null || localKey == 'id') { return obj.id; - else - return reflect(obj).getField(new Symbol(localKey ?? 'id')).reflectee; + } else { + return reflect(obj).getField(Symbol(localKey)).reflectee; + } } - _assignForeignObject(foreign, obj) { - if (assignForeignObject != null) + dynamic _assignForeignObject(foreign, obj) { + if (assignForeignObject != null) { return assignForeignObject(foreign, obj); - else if (obj is Map) + } else if (obj is Map) { obj[foreignName] = foreign; - //TODO: Undefined class - //else if (obj is Extensible) - // obj.properties[foreignName] = foreign; - else - reflect(obj).setField(new Symbol(foreignName), foreign); + } else { + reflect(obj).setField(Symbol(foreignName!), foreign); + } } - _normalize(obj) async { + Future _normalize(obj) async { if (obj != null) { var id = await _getLocalKey(obj); @@ -59,7 +54,7 @@ HookedServiceEventListener hasOne(Pattern servicePath, 'query': {foreignKey ?? 'userId': id} }); - if (indexed == null || indexed is! List || indexed.isNotEmpty != true) { + if (indexed is! List || indexed.isNotEmpty != true) { await _assignForeignObject(null, obj); } else { var child = indexed.first; @@ -69,8 +64,10 @@ HookedServiceEventListener hasOne(Pattern servicePath, } if (e.result is Iterable) { - await Future.wait(e.result.map(_normalize)); - } else + //await Future.wait(e.result.map(_normalize)); + await e.result.map(_normalize); + } else { await _normalize(e.result); + } }; } diff --git a/packages/relations/lib/src/no_service.dart b/packages/relations/lib/src/no_service.dart index e9d78658..df8eb3c4 100644 --- a/packages/relations/lib/src/no_service.dart +++ b/packages/relations/lib/src/no_service.dart @@ -1,2 +1,2 @@ ArgumentError noService(Pattern path) => - new ArgumentError("No service exists at path '$path'."); \ No newline at end of file + ArgumentError("No service exists at path '$path'."); diff --git a/packages/relations/lib/src/plural.dart b/packages/relations/lib/src/plural.dart index 972d2fdd..2c94bb89 100644 --- a/packages/relations/lib/src/plural.dart +++ b/packages/relations/lib/src/plural.dart @@ -1,21 +1,23 @@ String singular(String path) { var str = path.trim().split('/').where((str) => str.isNotEmpty).last; - if (str.endsWith('ies')) + if (str.endsWith('ies')) { return str.substring(0, str.length - 3) + 'y'; - else if (str.endsWith('s')) + } else if (str.endsWith('s')) { return str.substring(0, str.length - 1); - else + } else { return str; + } } String plural(String path) { var str = path.trim().split('/').where((str) => str.isNotEmpty).last; - if (str.endsWith('y')) + if (str.endsWith('y')) { return str.substring(0, str.length - 1) + 'ies'; - else if (str.endsWith('s')) + } else if (str.endsWith('s')) { return str; - else + } else { return str + 's'; + } } diff --git a/packages/relations/pubspec.yaml b/packages/relations/pubspec.yaml index 7198f434..c76cb5dd 100644 --- a/packages/relations/pubspec.yaml +++ b/packages/relations/pubspec.yaml @@ -1,14 +1,21 @@ -author: Tobe O +name: angel_relations +version: 2.0.0 description: Database-agnostic relations between Angel services. homepage: "https://github.com/angel-dart/relations.git" -name: angel_relations -version: 1.0.1 +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^1.0.0-dev - path: ../framework + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework dev_dependencies: - angel_seeder: #^1.0.0 - path: ../seeder - test: ^1.15.7 + angel_seeder: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/seeder + test: ^1.17.8 + pedantic: ^1.11.1 diff --git a/packages/relations/test/belongs_to_test.dart b/packages/relations/test/belongs_to_test.dart index 23afefdc..a1118a0e 100644 --- a/packages/relations/test/belongs_to_test.dart +++ b/packages/relations/test/belongs_to_test.dart @@ -4,8 +4,8 @@ import 'package:angel_seeder/angel_seeder.dart'; import 'package:test/test.dart'; import 'common.dart'; -main() { - Angel app; +void main() { + late Angel app; setUp(() async { app = Angel()..use('/authors', MapService())..use('/books', MapService()); @@ -30,22 +30,22 @@ main() { }); test('index', () async { - var books = await app.findService('books').index(); + var books = await app.findService('books')!.index(); print(books); expect(books, allOf(isList, isNotEmpty)); - for (Map book in books) { + for (var book in books.whereType()) { expect(book.keys, contains('author')); - Map author = book['author']; + var author = book['author'] as Map; expect(author['id'], equals(book['authorId'])); } }); test('create', () async { var warAndPeace = await app - .findService('books') + .findService('books')! .create(Book(title: 'War and Peace').toJson()); print(warAndPeace); diff --git a/packages/relations/test/common.dart b/packages/relations/test/common.dart index 478fa683..1e2969b0 100644 --- a/packages/relations/test/common.dart +++ b/packages/relations/test/common.dart @@ -6,13 +6,13 @@ import 'package:angel_framework/angel_framework.dart'; class CustomMapService extends Service { final List _items = []; - Iterable tailor(Iterable items, Map params) { + Iterable tailor(Iterable items, Map? params) { if (params == null) return items; var r = items; if (params != null && params['query'] is Map) { - Map query = params['query']; + var query = params['query'] as Map; for (var key in query.keys) { r = r.where((m) => m[key] == query[key]); @@ -23,30 +23,30 @@ class CustomMapService extends Service { } @override - index([params]) async => tailor(_items, params).toList(); + Future> index([params]) async => tailor(_items, params).toList(); @override - read(id, [Map params]) async { + Future read(id, [Map? params]) async { return tailor(_items, params).firstWhere((m) => m['id'] == id, - orElse: () => throw new AngelHttpException.notFound()); + orElse: (() => throw AngelHttpException.notFound()) as Map Function()?); } @override - create(data, [params]) async { - Map d = data is Map ? data : jsonDecode(data); + Future create(data, [params]) async { + var d = data is Map ? data : (jsonDecode(data as String) as Map?)!; d['id'] = _items.length.toString(); _items.add(d); return d; } @override - remove(id, [params]) async { + Future remove(id, [params]) async { if (id == null) _items.clear(); } } class Author { - String id, name; + String? id, name; Author({this.id, this.name}); @@ -54,7 +54,7 @@ class Author { } class Book { - String authorId, title; + String? authorId, title; Book({this.authorId, this.title}); @@ -62,8 +62,8 @@ class Book { } class Chapter { - String bookId, title; - int pageCount; + String? bookId, title; + int? pageCount; Chapter({this.bookId, this.title, this.pageCount}); } diff --git a/packages/relations/test/has_many_test.dart b/packages/relations/test/has_many_test.dart index a52cea7c..0796d04e 100644 --- a/packages/relations/test/has_many_test.dart +++ b/packages/relations/test/has_many_test.dart @@ -4,8 +4,8 @@ import 'package:angel_seeder/angel_seeder.dart'; import 'package:test/test.dart'; import 'common.dart'; -main() { - Angel app; +void main() { + late Angel app; setUp(() async { app = Angel()..use('/authors', MapService())..use('/books', MapService()); @@ -32,15 +32,15 @@ main() { }); test('index', () async { - var authors = await app.findService('authors').index(); + var authors = await app.findService('authors')!.index(); print(authors); expect(authors, allOf(isList, isNotEmpty)); - for (Map author in authors) { + for (var author in authors.whereType()) { expect(author.keys, contains('books')); - List books = author['books']; + var books = author['books'] as List; for (var book in books) { expect(book['authorId'], equals(author['id'])); @@ -50,7 +50,7 @@ main() { test('create', () async { var tolstoy = await app - .findService('authors') + .findService('authors')! .create(Author(name: 'Leo Tolstoy').toJson()); print(tolstoy); diff --git a/packages/relations/test/has_one_test.dart b/packages/relations/test/has_one_test.dart index cd313fc8..fc127ed8 100644 --- a/packages/relations/test/has_one_test.dart +++ b/packages/relations/test/has_one_test.dart @@ -4,8 +4,8 @@ import 'package:angel_seeder/angel_seeder.dart'; import 'package:test/test.dart'; import 'common.dart'; -main() { - Angel app; +void main() { + late Angel app; setUp(() async { app = Angel()..use('/authors', MapService())..use('/books', MapService()); @@ -31,15 +31,15 @@ main() { }); test('index', () async { - var authors = await app.findService('authors').index(); + var authors = await app.findService('authors')!.index(); print(authors); expect(authors, allOf(isList, isNotEmpty)); - for (Map author in authors) { + for (Map author in authors.whereType()) { expect(author.keys, contains('book')); - Map book = author['book']; + var book = author['book'] as Map; print('Author: $author'); print('Book: $book'); expect(book['authorId'], equals(author['id'])); @@ -48,7 +48,7 @@ main() { test('create', () async { var tolstoy = await app - .findService('authors') + .findService('authors')! .create(Author(name: 'Leo Tolstoy').toJson()); print(tolstoy); diff --git a/packages/rethink/AUTHORS.md b/packages/rethink/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/rethink/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/rethink/CHANGELOG.md b/packages/rethink/CHANGELOG.md index 3c801a88..ef08d73e 100644 --- a/packages/rethink/CHANGELOG.md +++ b/packages/rethink/CHANGELOG.md @@ -1,3 +1,6 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 1.1.0 * Moved to `package:rethinkdb_driver` * Fixed references to old hooked event names. \ No newline at end of file diff --git a/packages/rethink/LICENSE b/packages/rethink/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/rethink/LICENSE +++ b/packages/rethink/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/rethink/analysis_options.yaml b/packages/rethink/analysis_options.yaml new file mode 100644 index 00000000..c230cee7 --- /dev/null +++ b/packages/rethink/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:pedantic/analysis_options.yaml +analyzer: + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/rethink/lib/src/rethink_service.dart b/packages/rethink/lib/src/rethink_service.dart index c6ad9063..3ed955ee 100644 --- a/packages/rethink/lib/src/rethink_service.dart +++ b/packages/rethink/lib/src/rethink_service.dart @@ -5,7 +5,7 @@ import 'package:json_god/json_god.dart' as god; import 'package:rethinkdb_dart/rethinkdb_dart.dart'; // Extends a RethinkDB query. -typedef RqlQuery QueryCallback(RqlQuery query); +typedef QueryCallback = RqlQuery Function(RqlQuery query); /// Queries a single RethinkDB table or query. class RethinkService extends Service { @@ -33,47 +33,50 @@ class RethinkService extends Service { final RqlQuery table; RethinkService(this.connection, this.table, - {this.allowRemoveAll: false, - this.allowQuery: true, - this.debug: false, - this.listenForChanges: true}) - : super() {} + {this.allowRemoveAll = false, + this.allowQuery = true, + this.debug = false, + this.listenForChanges = true}) + : super(); RqlQuery buildQuery(RqlQuery initialQuery, Map params) { - if (params != null) + if (params != null) { params['broadcast'] = params.containsKey('broadcast') ? params['broadcast'] : (listenForChanges != true); + } var q = _getQueryInner(initialQuery, params); - if (params?.containsKey('reql') == true && params['reql'] is QueryCallback) - q = params['reql'](q); + if (params?.containsKey('reql') == true && + params['reql'] is QueryCallback) { + q = params['reql'](q) as RqlQuery; + } return q ?? initialQuery; } RqlQuery _getQueryInner(RqlQuery query, Map params) { - if (params == null || !params.containsKey('query')) + if (params == null || !params.containsKey('query')) { return query; - else { - if (params['query'] is RqlQuery) - return params['query']; - else if (params['query'] is QueryCallback) - return params['query'](table); - else if (params['query'] is! Map || allowQuery != true) + } else { + if (params['query'] is RqlQuery) { + return params['query'] as RqlQuery; + } else if (params['query'] is QueryCallback) { + return params['query'](table) as RqlQuery; + } else if (params['query'] is! Map || allowQuery != true) { return query; - else { - Map q = params['query']; + } else { + var q = params['query'] as Map; return q.keys.fold(query, (out, key) { var val = q[key]; if (val is RequestContext || val is ResponseContext || key == 'provider' || - val is Providers) + val is Providers) { return out; - else { + } else { return out.filter({key.toString(): val}); } }); @@ -84,34 +87,40 @@ class RethinkService extends Service { Future _sendQuery(RqlQuery query) async { var result = await query.run(connection); - if (result is Cursor) + if (result is Cursor) { return await result.toList(); - else if (result is Map && result['generated_keys'] is List) { - if (result['generated_keys'].length == 1) + } else if (result is Map && result['generated_keys'] is List) { + if (result['generated_keys'].length == 1) { return await read(result['generated_keys'].first); - return await Future.wait(result['generated_keys'].map(read)); - } else + } + //return await Future.wait(result['generated_keys'].map(read)); + return await result['generated_keys'].map(read); + } else { return result; + } } - _serialize(data) { - if (data is Map) + dynamic _serialize(data) { + if (data is Map) { return data; - else if (data is Iterable) + } else if (data is Iterable) { return data.map(_serialize).toList(); - else + } else { return god.serializeObject(data); + } } - _squeeze(data) { - if (data is Map) + dynamic _squeeze(data) { + if (data is Map) { return data.keys.fold({}, (map, k) => map..[k.toString()] = data[k]); - else if (data is Iterable) + } else if (data is Iterable) { return data.map(_squeeze).toList(); - else + } else { return data; + } } + @override void onHooked(HookedService hookedService) { if (listenForChanges == true) { listenToQuery(table, hookedService); @@ -119,31 +128,32 @@ class RethinkService extends Service { } Future listenToQuery(RqlQuery query, HookedService hookedService) async { - Feed feed = await query.changes({'include_types': true}).run(connection); + var feed = + await query.changes({'include_types': true}).run(connection) as Feed; feed.listen((Map event) { - String type = event['type']?.toString(); + var type = event['type']?.toString(); var newVal = event['new_val'], oldVal = event['old_val']; if (type == 'add') { // Create hookedService.fireEvent( hookedService.afterCreated, - new HookedServiceEvent( + HookedServiceEvent( true, null, null, this, HookedServiceEvent.created, result: newVal)); } else if (type == 'change') { // Update hookedService.fireEvent( hookedService.afterCreated, - new HookedServiceEvent( + HookedServiceEvent( true, null, null, this, HookedServiceEvent.updated, result: newVal, id: oldVal['id'], data: newVal)); } else if (type == 'remove') { // Remove hookedService.fireEvent( hookedService.afterCreated, - new HookedServiceEvent( + HookedServiceEvent( true, null, null, this, HookedServiceEvent.removed, result: oldVal, id: oldVal['id'])); } @@ -165,15 +175,15 @@ class RethinkService extends Service { //print('Found for $id: $found'); if (found == null) { - throw new AngelHttpException.notFound( - message: 'No record found for ID $id'); - } else + throw AngelHttpException.notFound(message: 'No record found for ID $id'); + } else { return found; + } } @override Future create(data, [Map params]) async { - if (table is! Table) throw new AngelHttpException.methodNotAllowed(); + if (table is! Table) throw AngelHttpException.methodNotAllowed(); var d = _serialize(data); var q = table as Table; @@ -189,10 +199,11 @@ class RethinkService extends Service { try { await read(d['id'], params); } on AngelHttpException catch (e) { - if (e.statusCode == 404) + if (e.statusCode == 404) { return await create(data, params); - else + } else { rethrow; + } } } @@ -209,10 +220,11 @@ class RethinkService extends Service { try { await read(d['id'], params); } on AngelHttpException catch (e) { - if (e.statusCode == 404) + if (e.statusCode == 404) { return await create(data, params); - else + } else { rethrow; + } } } diff --git a/packages/rethink/pubspec.yaml b/packages/rethink/pubspec.yaml index cb4d8452..902bc317 100644 --- a/packages/rethink/pubspec.yaml +++ b/packages/rethink/pubspec.yaml @@ -1,19 +1,35 @@ name: angel_rethink -version: 1.1.0 +version: 2.0.0 description: RethinkDB-enabled services for the Angel framework. -author: Tobe O +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: ">=2.10.0 <3.0.0" homepage: https://github.com/angel-dart/rethink dependencies: - angel_framework: #^1.1.0 - path: ../framework - json_god: ^2.0.0-beta + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + json_god: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/json_god rethinkdb_dart: ^2.3.2+6 dev_dependencies: - angel_client: #^1.1.0 - path: ../client - angel_test: #^1.1.0 - path: ../test - logging: ^0.11.3 - test: ^1.15.7 \ No newline at end of file + angel_client: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/client + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + logging: ^1.0.0 + test: ^1.15.7 + pedantic: ^1.11.1 +dependency_overrides: + crypto: ^3.0.0 \ No newline at end of file diff --git a/packages/security/AUTHORS.md b/packages/security/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/security/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/security/CHANGELOG.md b/packages/security/CHANGELOG.md index 3aaa1f19..d6ce5745 100644 --- a/packages/security/CHANGELOG.md +++ b/packages/security/CHANGELOG.md @@ -1,3 +1,6 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 2.0.0-alpha.1 * Make `ServiceRateLimiter` more fail-proof. diff --git a/packages/security/LICENSE b/packages/security/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/security/LICENSE +++ b/packages/security/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/security/example/cookie_signer.dart b/packages/security/example/cookie_signer.dart index 2ec1d8c3..9c7ec421 100644 --- a/packages/security/example/cookie_signer.dart +++ b/packages/security/example/cookie_signer.dart @@ -11,7 +11,8 @@ void main() async { Logger.root.onRecord.listen(prettyLog); // Create an app, and HTTP driver. - var app = Angel(logger: Logger('cookie_signer')), http = AngelHttp(app); + var app = Angel(logger: Logger('cookie_signer')); + var http = AngelHttp(app); // Create a cookie signer. Uses an SHA256 Hmac by default. var signer = CookieSigner.fromStringKey( @@ -37,7 +38,7 @@ void main() async { // here we will use it to log invalid cookies. app.get('/cookies', (req, res) { var verifiedCookies = signer.readCookies(req, onInvalidCookie: (cookie) { - app.logger.warning('Invalid cookie: $cookie'); + app.logger!.warning('Invalid cookie: $cookie'); }); res.writeln('${verifiedCookies.length} verified cookie(s)'); res.writeln('${req.cookies.length} total unverified cookie(s)'); diff --git a/packages/security/example/rate_limit.dart b/packages/security/example/rate_limit.dart index d715a9e0..60d52465 100644 --- a/packages/security/example/rate_limit.dart +++ b/packages/security/example/rate_limit.dart @@ -9,7 +9,8 @@ void main() async { Logger.root.onRecord.listen(prettyLog); // Create an app, and HTTP driver. - var app = Angel(logger: Logger('rate_limit')), http = AngelHttp(app); + var app = Angel(logger: Logger('rate_limit')); + var http = AngelHttp(app); // Create a simple in-memory rate limiter that limits users to 5 // queries per 30 seconds. diff --git a/packages/security/example/rate_limit_redis.dart b/packages/security/example/rate_limit_redis.dart index 73668d77..504bdfe5 100644 --- a/packages/security/example/rate_limit_redis.dart +++ b/packages/security/example/rate_limit_redis.dart @@ -4,6 +4,7 @@ import 'package:angel_production/angel_production.dart'; import 'package:angel_security/angel_security.dart'; import 'package:resp_client/resp_client.dart'; import 'package:resp_client/resp_commands.dart'; +import 'package:resp_client/resp_server.dart'; // We run this through angel_production, so that we can have // multiple instances, all using the same Redis queue. @@ -19,8 +20,8 @@ void configureServer(Angel app) async { // Our Redis store will be used to manage windows. var connection = await connectSocket('localhost'); var client = RespClient(connection); - var service = - RedisService(RespCommands(client), prefix: 'rate_limit_redis_example'); + var service = RedisService(RespCommandsTier2(client), + prefix: 'rate_limit_redis_example'); var rateLimiter = ServiceRateLimiter( 10, Duration(seconds: 30), service, (req, res) => req.ip); @@ -32,7 +33,7 @@ void configureServer(Angel app) async { // Basic routes. app ..get('/', (req, res) { - var instance = req.container.make(); + var instance = req.container!.make()!; res.writeln('This is instance ${instance.id}.'); }) ..fallback((req, res) => throw AngelHttpException.notFound()); diff --git a/packages/security/lib/src/cookie_signer.dart b/packages/security/lib/src/cookie_signer.dart index 4d9c81de..d49ea282 100644 --- a/packages/security/lib/src/cookie_signer.dart +++ b/packages/security/lib/src/cookie_signer.dart @@ -14,14 +14,14 @@ class CookieSigner { /// Creates an [hmac] from an array of [keyBytes] and a /// [hash] (defaults to [sha256]). - CookieSigner(List keyBytes, {Hash hash}) + CookieSigner(List keyBytes, {Hash? hash}) : hmac = Hmac(hash ?? sha256, keyBytes); CookieSigner.fromHmac(this.hmac); /// Creates an [hmac] from a string [key] and a /// [hash] (defaults to [sha256]). - factory CookieSigner.fromStringKey(String key, {Hash hash}) { + factory CookieSigner.fromStringKey(String key, {Hash? hash}) { return CookieSigner(utf8.encode(key), hash: hash); } @@ -33,7 +33,7 @@ class CookieSigner { /// If an [onInvalidCookie] callback is passed, then it will /// be invoked for each unsigned or improperly-signed cookie. List readCookies(RequestContext req, - {void Function(Cookie) onInvalidCookie}) { + {void Function(Cookie)? onInvalidCookie}) { return req.cookies.fold([], (out, cookie) { var data = getCookiePayloadAndSignature(cookie.value); if (data == null || (data[1] != computeCookieSignature(data[0]))) { @@ -66,7 +66,7 @@ class CookieSigner { /// Otherwise, returns a list with a length of 2, where /// the item at index `0` is the payload, and the item at /// index `1` is the signature. - List getCookiePayloadAndSignature(String cookieValue) { + List? getCookiePayloadAndSignature(String cookieValue) { var dot = cookieValue.indexOf('.'); if (dot <= 0) { return null; diff --git a/packages/security/lib/src/csrf_filter.dart b/packages/security/lib/src/csrf_filter.dart index df0e8938..c7abd87b 100644 --- a/packages/security/lib/src/csrf_filter.dart +++ b/packages/security/lib/src/csrf_filter.dart @@ -14,6 +14,7 @@ class CsrfFilter { CsrfFilter(this.cookieSigner); Future readCsrfToken(RequestContext req) async { - + // TODO: To be reviewed + return CsrfToken(req.hostname); } } diff --git a/packages/security/lib/src/helmet.dart b/packages/security/lib/src/helmet.dart index 7cababd9..f99e82cf 100644 --- a/packages/security/lib/src/helmet.dart +++ b/packages/security/lib/src/helmet.dart @@ -1,5 +1 @@ -import 'package:angel_framework/angel_framework.dart'; - -class Helmet { - -} \ No newline at end of file +class Helmet {} diff --git a/packages/security/lib/src/in_memory_rate_limiter.dart b/packages/security/lib/src/in_memory_rate_limiter.dart index d545b8b6..298652b1 100644 --- a/packages/security/lib/src/in_memory_rate_limiter.dart +++ b/packages/security/lib/src/in_memory_rate_limiter.dart @@ -12,7 +12,7 @@ class InMemoryRateLimiter extends RateLimiter { InMemoryRateLimiter( int maxPointsPerWindow, Duration windowDuration, this.getUser, - {String errorMessage}) + {String? errorMessage}) : super(maxPointsPerWindow, windowDuration, errorMessage: errorMessage); @override diff --git a/packages/security/lib/src/rate_limiter.dart b/packages/security/lib/src/rate_limiter.dart index fb8b99cd..4ceb748e 100644 --- a/packages/security/lib/src/rate_limiter.dart +++ b/packages/security/lib/src/rate_limiter.dart @@ -26,8 +26,8 @@ abstract class RateLimiter { final String errorMessage; RateLimiter(this.maxPointsPerWindow, this.windowDuration, - {String errorMessage}) - : this.errorMessage = errorMessage ?? 'Rate limit exceeded.'; + {String? errorMessage}) + : errorMessage = errorMessage ?? 'Rate limit exceeded.'; /// Computes the current window in which the user is acting. /// @@ -68,7 +68,7 @@ abstract class RateLimiter { 'x-ratelimit-limit': window.pointLimit.toString(), 'x-ratelimit-remaining': window.remainingPoints.toString(), 'x-ratelimit-reset': - (window.resetTime.millisecondsSinceEpoch ~/ 1000).toString(), + (window.resetTime!.millisecondsSinceEpoch ~/ 1000).toString(), }); } @@ -83,7 +83,7 @@ abstract class RateLimiter { /// Whatever is returned here will be returned in [handleRequest]. FutureOr rejectRequest(RequestContext req, ResponseContext res, RateLimitingWindow window, DateTime currentTime) { - var retryAfter = window.resetTime.difference(currentTime); + var retryAfter = window.resetTime!.difference(currentTime); res.headers['retry-after'] = retryAfter.inSeconds.toString(); throw AngelHttpException(null, message: errorMessage, statusCode: 429); } @@ -134,16 +134,21 @@ abstract class RateLimiter { // user over the rate limit. else if (currentWindow.pointsConsumed >= maxPointsPerWindow) { await sendWindowInformation(req, res, currentWindow); - var result = await rejectRequest(req, res, currentWindow, now); - if (result != null) return result; + await rejectRequest(req, res, currentWindow, now); + //var result = await rejectRequest(req, res, currentWindow, now); + //if (result != null) return result; return false; } else { // Add the cost of the current endpoint, and update the window. var cost = await getEndpointCost(req, res, currentWindow); - currentWindow - ..pointsConsumed += cost - ..remainingPoints -= cost; - if (currentWindow.remainingPoints < 0) { + currentWindow.pointsConsumed += cost; + var remaining = currentWindow.remainingPoints; + if (remaining == null) { + currentWindow.remainingPoints = 0; + } else { + currentWindow.remainingPoints = remaining - cost; + } + if (currentWindow.remainingPoints! < 0) { currentWindow.remainingPoints = 0; } await updateCurrentWindow(req, res, currentWindow, now); diff --git a/packages/security/lib/src/rate_limiting_window.dart b/packages/security/lib/src/rate_limiting_window.dart index 07fff1b1..36aea3aa 100644 --- a/packages/security/lib/src/rate_limiting_window.dart +++ b/packages/security/lib/src/rate_limiting_window.dart @@ -15,27 +15,27 @@ class RateLimitingWindow { /// /// This field is typically only set by the [RateLimiter] middleware, /// and is therefore optional in the constructor. - int pointLimit; + int? pointLimit; /// The amount of points the user can consume before hitting the /// rate limit for the current window. /// /// This field is typically only set by the [RateLimiter] middleware, /// and is therefore optional in the constructor. - int remainingPoints; + int? remainingPoints; /// The time at which the window will reset. /// /// This field is typically only set by the [RateLimiter] middleware, /// and is therefore optional in the constructor. - DateTime resetTime; + DateTime? resetTime; RateLimitingWindow(this.user, this.startTime, this.pointsConsumed, {this.pointLimit, this.remainingPoints, this.resetTime}); factory RateLimitingWindow.fromJson(Map map) { return RateLimitingWindow( - map['user'] as User, + (map['user'] as User?)!, DateTime.parse(map['start_time'] as String), int.parse(map['points_consumed'] as String)); } diff --git a/packages/security/lib/src/service_rate_limiter.dart b/packages/security/lib/src/service_rate_limiter.dart index f3bb1e4f..c009747e 100644 --- a/packages/security/lib/src/service_rate_limiter.dart +++ b/packages/security/lib/src/service_rate_limiter.dart @@ -14,7 +14,7 @@ class ServiceRateLimiter extends RateLimiter { ServiceRateLimiter( int maxPointsPerWindow, Duration windowDuration, this.service, this.getId, - {String errorMessage}) + {String? errorMessage}) : super(maxPointsPerWindow, windowDuration, errorMessage: errorMessage); @override diff --git a/packages/security/pubspec.yaml b/packages/security/pubspec.yaml index a7d1f723..03554664 100644 --- a/packages/security/pubspec.yaml +++ b/packages/security/pubspec.yaml @@ -1,25 +1,47 @@ name: angel_security -version: 2.0.0-alpha.1 +version: 3.0.0 description: Angel infrastructure for improving security, rate limiting, and more. -author: Tobe O homepage: https://github.com/angel-dart/security +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0 - path: ../framework - crypto: ^2.0.0 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + crypto: ^3.0.1 dev_dependencies: - angel_auth: #^2.0.0 - path: ../auth - angel_production: #^1.0.0 - path: ../production - angel_redis: #^1.0.0 - path: ../redis - angel_test: #^2.0.0 - path: ../test - angel_validate: #^2.0.0 - path: ../validate - pedantic: ^1.0.0 - pretty_logging: ^1.0.0 - test: ^1.15.7 + angel_auth: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/auth + angel_production: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/production + angel_redis: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/redis + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + angel_validate: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/validate + pretty_logging: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/pretty_logging + pedantic: ^1.11.1 + test: ^1.17.8 diff --git a/packages/seeder/AUTHORS.md b/packages/seeder/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/seeder/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/seeder/CHANGELOG.md b/packages/seeder/CHANGELOG.md new file mode 100644 index 00000000..9a5a22f6 --- /dev/null +++ b/packages/seeder/CHANGELOG.md @@ -0,0 +1,5 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + +# 1.0.0 +* Initial checkin \ No newline at end of file diff --git a/packages/seeder/LICENSE b/packages/seeder/LICENSE index 8f65b579..b593ac86 100644 --- a/packages/seeder/LICENSE +++ b/packages/seeder/LICENSE @@ -1,4 +1,4 @@ -MIT License (MIT) +MIT License Copyright (c) 2021 dukefirehawk.com @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/seeder/analysis_options.yaml b/packages/seeder/analysis_options.yaml new file mode 100644 index 00000000..c230cee7 --- /dev/null +++ b/packages/seeder/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:pedantic/analysis_options.yaml +analyzer: + strong-mode: + implicit-casts: false \ No newline at end of file diff --git a/packages/seeder/lib/angel_seeder.dart b/packages/seeder/lib/angel_seeder.dart index 0927b05c..87d14e50 100644 --- a/packages/seeder/lib/angel_seeder.dart +++ b/packages/seeder/lib/angel_seeder.dart @@ -4,24 +4,25 @@ import 'package:faker/faker.dart'; export 'package:faker/faker.dart'; /// Generates data using a [Faker]. -typedef FakerCallback(Faker faker); +typedef FakerCallback = Function(Faker faker); /// Used to seed nested objects. -typedef SeederCallback(T created, - seed(Pattern path, SeederConfiguration configuration, {bool verbose})); +typedef SeederCallback = Function(T created, + Function(Pattern path, SeederConfiguration configuration, {bool? verbose})); /// Seeds the given service in development. AngelConfigurer seed( Pattern servicePath, SeederConfiguration configuration, { - bool verbose: false, + bool verbose = false, }) { return (Angel app) async { if (configuration.runInProduction != true) return; - if (!app.services.containsKey(servicePath)) - throw new ArgumentError( + if (!app.services.containsKey(servicePath)) { + throw ArgumentError( "App does not contain a service at path '$servicePath'."); + } if (configuration.disabled == true) { print("Service '$servicePath' will not be seeded."); @@ -29,7 +30,7 @@ AngelConfigurer seed( } var service = app.findService(servicePath); - var faker = new Faker(); + var faker = Faker(); Map _buildTemplate(Map data) { return data.keys.fold({}, (map, key) { @@ -39,23 +40,26 @@ AngelConfigurer seed( return map..[key] = value(faker); } else if (value is Function) { return map..[key] = value(); - } else if (value is Map) + } else if (value is Map) { return map..[key] = _buildTemplate(value); - else + } else { return map..[key] = value; + } }); } - _buildSeeder(Service service, {bool verbose}) { + Future Function(SeederConfiguration configuration) _buildSeeder( + Service? service, + {bool? verbose}) { return (SeederConfiguration configuration) async { - if (configuration.delete == true) await service.remove(null); + if (configuration.delete == true) await service!.remove(null); - int count = configuration.count ?? 1; - var rnd = new Random(); + var count = configuration.count; + var rnd = Random(); if (count < 1) count = 1; - for (int i = 0; i < count; i++) { - _gen(template) async { + for (var i = 0; i < count; i++) { + Future _gen(template) async { var data = template; if (data is Map) { @@ -64,13 +68,13 @@ AngelConfigurer seed( data = template(faker); } - var params = {}..addAll(configuration.params ?? {}); - var result = await service.create(data, params); + var params = {}..addAll(configuration.params); + var result = await service!.create(data, params); if (configuration.callback != null) { - await configuration.callback(result, + await configuration.callback!(result, (Pattern path, SeederConfiguration configuration, - {bool verbose}) { + {bool? verbose}) { return _buildSeeder(app.findService(path), verbose: verbose == true)(configuration); }); @@ -79,17 +83,19 @@ AngelConfigurer seed( if (configuration.template != null) { await _gen(configuration.template); - } else if (configuration.templates?.isNotEmpty == true) { + } else if (configuration.templates.isNotEmpty == true) { var template = configuration.templates .elementAt(rnd.nextInt(configuration.templates.length)); await _gen(template); - } else - throw new ArgumentError( + } else { + throw ArgumentError( 'Configuration for service \'$servicePath\' must define at least one template.'); + } } - if (verbose == true) + if (verbose == true) { print('Created $count object(s) in service \'$servicePath\'.'); + } }; } @@ -100,7 +106,7 @@ AngelConfigurer seed( /// Configures the seeder. class SeederConfiguration { /// Optional callback on creation. - final SeederCallback callback; + final SeederCallback? callback; /// Number of objects to seed. final int count; @@ -112,7 +118,7 @@ class SeederConfiguration { final bool disabled; /// Optional service parameters to be passed. - final Map params; + final Map params; /// Unless this is `true`, the seeder will not run in production. final bool runInProduction; @@ -125,11 +131,11 @@ class SeederConfiguration { SeederConfiguration( {this.callback, - this.count: 1, - this.delete: true, - this.disabled: false, - this.params: const {}, - this.runInProduction: false, + this.count = 1, + this.delete = true, + this.disabled = false, + this.params = const {}, + this.runInProduction = false, this.template, - this.templates: const []}); + this.templates = const []}); } diff --git a/packages/seeder/pubspec.yaml b/packages/seeder/pubspec.yaml index c7e1503d..b34f1790 100644 --- a/packages/seeder/pubspec.yaml +++ b/packages/seeder/pubspec.yaml @@ -1,13 +1,17 @@ name: angel_seeder +version: 2.0.0 description: Straightforward data seeder for Angel services. -version: 1.0.2 -author: Tobe O +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' homepage: https://github.com/angel-dart/seeder dependencies: - angel_framework: #^1.0.0-dev - path: ../framework - faker: ^1.3.0 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + faker: ^2.0.0 dev_dependencies: - test: ^1.15.7 + test: ^1.17.8 + pedantic: ^1.11.1 diff --git a/packages/seeder/test/all_test.dart b/packages/seeder/test/all_test.dart index a6682495..9cecfa97 100644 --- a/packages/seeder/test/all_test.dart +++ b/packages/seeder/test/all_test.dart @@ -1,21 +1,23 @@ import 'dart:async'; import 'package:angel_framework/angel_framework.dart'; +import 'package:angel_container/mirrors.dart'; import 'package:angel_seeder/angel_seeder.dart'; import 'package:test/test.dart'; -main() { +void main() { test('create one', () async { - var app = new Angel()..use('/todos', new TodoService()); + var app = Angel(reflector: MirrorsReflector()) + ..use('/todos', TodoService()); await app.configure(seed( 'todos', - new SeederConfiguration(delete: false, count: 10, template: { + SeederConfiguration(delete: false, count: 10, template: { 'text': (Faker faker) => 'Clean your room, ${faker.person.name()}!', 'completed': false }))); - var todos = await app.findService('todos').index(); + var todos = await app.findService('todos')!.index(); print('Todos: \n${todos.map((todo) => " - $todo").join("\n")}'); expect(todos, isList); @@ -27,7 +29,7 @@ class TodoService extends Service { final List todos = []; @override - index([params]) => myData(); + Future> index([params]) => myData(); Future> myData() { var completer = Completer>(); @@ -36,29 +38,32 @@ class TodoService extends Service { } @override - create(data, [params]) async { + Future create(data, [params]) async { if (data is Todo) { todos.add(data..id = todos.length.toString()); return data; } else if (data is Map) { - todos.add(new Todo.fromJson(data)..id = todos.length.toString()); + todos.add(Todo.fromJson(data)..id = todos.length.toString()); return data; - } else - throw new AngelHttpException.badRequest(); + } else { + throw AngelHttpException.badRequest(); + } } } class Todo extends Model { - final String text; - final bool completed; + final String? text; + final bool? completed; - Todo({String id, this.text, this.completed: false}) { + Todo({String? id, this.text, this.completed: false}) { this.id = id; } - factory Todo.fromJson(Map data) => new Todo( - id: data['id'], text: data['text'], completed: data['completed']); + factory Todo.fromJson(Map data) => Todo( + id: data['id'] as String?, + text: data['text'] as String?, + completed: data['completed'] as bool?); @override - toString() => '${completed ? "Complete" : "Incomplete"}: $text'; + String toString() => '${completed! ? "Complete" : "Incomplete"}: $text'; } diff --git a/packages/sembast/AUTHORS.md b/packages/sembast/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/sembast/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/sembast/CHANGELOG.md b/packages/sembast/CHANGELOG.md index 9195900b..646bb12b 100644 --- a/packages/sembast/CHANGELOG.md +++ b/packages/sembast/CHANGELOG.md @@ -1,3 +1,6 @@ +# 2.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 1.0.1 * Fix flaw where clients could remove all records, even if `allowRemoveAll` were `false`. diff --git a/packages/sembast/LICENSE b/packages/sembast/LICENSE index 8f65b579..f8e6088a 100644 --- a/packages/sembast/LICENSE +++ b/packages/sembast/LICENSE @@ -1,6 +1,6 @@ -MIT License (MIT) +MIT License -Copyright (c) 2021 dukefirehawk.com +Copyright (c) 2018 The Angel Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/sembast/example/main.dart b/packages/sembast/example/main.dart index 8bb6357b..3d715e31 100644 --- a/packages/sembast/example/main.dart +++ b/packages/sembast/example/main.dart @@ -4,7 +4,7 @@ import 'package:angel_sembast/angel_sembast.dart'; import 'package:logging/logging.dart'; import 'package:sembast/sembast_io.dart'; -main() async { +void main() async { var app = Angel(); var db = await databaseFactoryIo.openDatabase('todos.db'); diff --git a/packages/sembast/lib/angel_sembast.dart b/packages/sembast/lib/angel_sembast.dart index b0c00b9b..e00ad88a 100644 --- a/packages/sembast/lib/angel_sembast.dart +++ b/packages/sembast/lib/angel_sembast.dart @@ -15,18 +15,18 @@ class SembastService extends Service> { final bool allowQuery; SembastService(this.database, - {String store, this.allowRemoveAll = false, this.allowQuery = true}) - : this.store = intMapStoreFactory.store(store), + {String? store, this.allowRemoveAll = false, this.allowQuery = true}) + : store = intMapStoreFactory.store(store), super(); - Finder _makeQuery([Map params]) { + Finder? _makeQuery([Map? params]) { params = Map.from(params ?? {}); - Filter out; + Filter? out; var sort = []; // You can pass a Finder as 'query': if (params['query'] is Finder) { - return params['query'] as Finder; + return params['query'] as Finder?; } for (var key in params.keys) { @@ -37,12 +37,12 @@ class SembastService extends Service> { if (v is! Map) { sort.add(SortOrder(v.toString(), true)); } else { - var m = v as Map; + var m = v; m.forEach((k, sorter) { if (sorter is SortOrder) { sort.add(sorter); } else if (sorter is String) { - sort.add(SortOrder(k.toString(), sorter == "-1")); + sort.add(SortOrder(k.toString(), sorter == '-1')); } else if (sorter is num) { sort.add(SortOrder(k.toString(), sorter == -1)); } @@ -60,7 +60,7 @@ class SembastService extends Service> { if (out == null) { out = filter; } else { - out = Filter.or([out, filter]); + out = Filter.or([out!, filter]); } } }); @@ -72,29 +72,35 @@ class SembastService extends Service> { } Map _withId(Map data, String id) => - Map.from(data ?? {})..['id'] = id; + Map.from(data)..['id'] = id; @override Future> findOne( - [Map params, + [Map? params, String errorMessage = 'No record was found matching the given query.']) async { - return (await store.findFirst(database, finder: _makeQuery(params)))?.value; + var result = + (await store.findFirst(database, finder: _makeQuery(params)))?.value; + if (result == null) { + return {}; + } + + return result; } @override Future>> index( - [Map params]) async { + [Map? params]) async { var records = await store.find(database, finder: _makeQuery(params)); return records - .where((r) => r.value != null) + //.where((r) => r.value != null) .map((r) => _withId(r.value, r.key.toString())) .toList(); } @override Future> read(String id, - [Map params]) async { + [Map? params]) async { var record = await store.record(int.parse(id)).getSnapshot(database); if (record == null) { @@ -106,7 +112,7 @@ class SembastService extends Service> { @override Future> create(Map data, - [Map params]) async { + [Map? params]) async { return await database.transaction((txn) async { var key = await store.add(txn, data); var id = key.toString(); @@ -116,7 +122,7 @@ class SembastService extends Service> { @override Future> modify(String id, Map data, - [Map params]) async { + [Map? params]) async { return await database.transaction((txn) async { var record = store.record(int.parse(id)); data = await record.put(txn, data, merge: true); @@ -126,7 +132,7 @@ class SembastService extends Service> { @override Future> update(String id, Map data, - [Map params]) async { + [Map? params]) async { return await database.transaction((txn) async { var record = store.record(int.parse(id)); data = await record.put(txn, data); @@ -135,8 +141,8 @@ class SembastService extends Service> { } @override - Future> remove(String id, - [Map params]) async { + Future> remove(String? id, + [Map? params]) async { if (id == null || id == 'null') { // Remove everything... if (!(allowRemoveAll == true || diff --git a/packages/sembast/pubspec.yaml b/packages/sembast/pubspec.yaml index e0c8f3e3..aa556b69 100644 --- a/packages/sembast/pubspec.yaml +++ b/packages/sembast/pubspec.yaml @@ -1,18 +1,24 @@ name: angel_sembast +version: 2.0.0 description: package:sembast-powered CRUD services for the Angel framework. homepage: https://github.com/angel-dart/sembast -version: 1.0.1 -author: Tobe O +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - sembast: ^1.19.0-dev.2 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + sembast: ^3.1.0+2 dev_dependencies: - angel_http_exception: #^1.0.0 - path: ../http_exception - logging: - pedantic: ^1.0.0 - test: ^1.15.7 + angel_http_exception: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/http_exception + logging: ^1.0.1 + pedantic: ^1.11.1 + test: ^1.17.8 diff --git a/packages/sembast/test/all_test.dart b/packages/sembast/test/all_test.dart index a8968efc..5d383c62 100644 --- a/packages/sembast/test/all_test.dart +++ b/packages/sembast/test/all_test.dart @@ -3,15 +3,15 @@ import 'package:angel_framework/angel_framework.dart'; import 'package:angel_http_exception/angel_http_exception.dart'; import 'package:angel_sembast/angel_sembast.dart'; import 'package:sembast/sembast.dart'; -import 'package:sembast/sembast_memory.dart'; +import 'package:sembast/sembast_io.dart'; import 'package:test/test.dart'; void main() async { - Database database; - SembastService service; + late Database database; + late SembastService service; setUp(() async { - database = await memoryDatabaseFactory.openDatabase('test.db'); + database = await databaseFactoryIo.openDatabase('test.db'); service = SembastService(database); }); @@ -62,7 +62,7 @@ void main() async { test('remove', () async { var input = await service.create({'bar': 'baz'}); - var id = input['id'] as String; + var id = input['id'] as String?; expect(await service.remove(id), input); expect(await StoreRef.main().record(id).get(database), isNull); }); @@ -82,13 +82,13 @@ void main() async { throwsA(const TypeMatcher())); expect( () => service.remove(null, {'provider': Providers.rest}), - throwsA(predicate((x) => x is AngelHttpException && x.statusCode == 403, + throwsA(predicate((dynamic x) => x is AngelHttpException && x.statusCode == 403, 'throws forbidden'))); expect(() => service.remove('null', {'provider': Providers.rest}), throwsA(const TypeMatcher())); expect( () => service.remove('null', {'provider': Providers.rest}), - throwsA(predicate((x) => x is AngelHttpException && x.statusCode == 403, + throwsA(predicate((dynamic x) => x is AngelHttpException && x.statusCode == 403, 'throws forbidden'))); }); diff --git a/packages/seo/AUTHORS.md b/packages/seo/AUTHORS.md new file mode 100644 index 00000000..ac95ab58 --- /dev/null +++ b/packages/seo/AUTHORS.md @@ -0,0 +1,12 @@ +Primary Authors +=============== + +* __[Thomas Hii](dukefirehawk.apps@gmail.com)__ + + Thomas is the current maintainer of the code base. He has refactored and migrated the + code base to support NNBD. + +* __[Tobe O](thosakwe@gmail.com)__ + + Tobe has written much of the original code prior to NNBD migration. He has moved on and + is no longer involved with the project. diff --git a/packages/seo/CHANGELOG.md b/packages/seo/CHANGELOG.md index 5371b09c..782aa377 100644 --- a/packages/seo/CHANGELOG.md +++ b/packages/seo/CHANGELOG.md @@ -1,3 +1,6 @@ +# 3.0.0 +* Migrated to support Dart SDK 2.12.x NNBD + # 2.0.0 * Angel 2 updates. diff --git a/packages/seo/LICENSE b/packages/seo/LICENSE index 8f65b579..f8e6088a 100644 --- a/packages/seo/LICENSE +++ b/packages/seo/LICENSE @@ -1,6 +1,6 @@ -MIT License (MIT) +MIT License -Copyright (c) 2021 dukefirehawk.com +Copyright (c) 2018 The Angel Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/packages/seo/analysis_options.yaml b/packages/seo/analysis_options.yaml index eae1e42a..c230cee7 100644 --- a/packages/seo/analysis_options.yaml +++ b/packages/seo/analysis_options.yaml @@ -1,3 +1,4 @@ +include: package:pedantic/analysis_options.yaml analyzer: strong-mode: implicit-casts: false \ No newline at end of file diff --git a/packages/seo/example/main.dart b/packages/seo/example/main.dart index cbf11339..9bd25ecf 100644 --- a/packages/seo/example/main.dart +++ b/packages/seo/example/main.dart @@ -6,14 +6,14 @@ import 'package:angel_static/angel_static.dart'; import 'package:file/local.dart'; import 'package:http_parser/http_parser.dart'; -main() async { - var app = new Angel(); +void main() async { + var app = Angel(); var fs = const LocalFileSystem(); - var http = new AngelHttp(app); + var http = AngelHttp(app); // You can wrap a [VirtualDirectory] var vDir = inlineAssetsFromVirtualDirectory( - new VirtualDirectory( + VirtualDirectory( app, fs, source: fs.directory('web'), @@ -32,11 +32,11 @@ main() async { var indexHtml = fs.directory('web').childFile('index.html'); var contents = await indexHtml.readAsString(); res - ..contentType = new MediaType('text', 'html', {'charset': 'utf-8'}) - ..buffer.add(utf8.encode(contents)); + ..contentType = MediaType('text', 'html', {'charset': 'utf-8'}) + ..buffer!.add(utf8.encode(contents)); }); - app.fallback((req, res) => throw new AngelHttpException.notFound()); + app.fallback((req, res) => throw AngelHttpException.notFound()); var server = await http.startServer('127.0.0.1', 3000); print('Listening at http://${server.address.address}:${server.port}'); diff --git a/packages/seo/lib/src/inline_assets.dart b/packages/seo/lib/src/inline_assets.dart index 95d5fab4..3d70362d 100644 --- a/packages/seo/lib/src/inline_assets.dart +++ b/packages/seo/lib/src/inline_assets.dart @@ -19,11 +19,11 @@ RequestHandler inlineAssets(Directory assetDirectory) { if (!res.isOpen || !res.isBuffered || res.contentType.mimeType != 'text/html') { - return new Future.value(true); + return Future.value(true); } else { - var doc = html.parse(utf8.decode(res.buffer.takeBytes())); + var doc = html.parse(utf8.decode(res.buffer!.takeBytes())); return inlineAssetsIntoDocument(doc, assetDirectory).then((_) { - res.buffer.add(utf8.encode(doc.outerHtml)); + res.buffer!.add(utf8.encode(doc.outerHtml)); return false; }); } @@ -39,29 +39,29 @@ RequestHandler inlineAssets(Directory assetDirectory) { /// In this case, "internal resources" refers to a URI *without* a scheme, i.e. `/site.css` or /// `foo/bar/baz.js`. VirtualDirectory inlineAssetsFromVirtualDirectory(VirtualDirectory vDir) => - new _InlineAssets(vDir); + _InlineAssets(vDir); /// Replaces `link` and `script` tags within a [doc] with the static contents they would otherwise trigger an HTTP request to. /// /// Powers both [inlineAssets] and [inlineAssetsFromVirtualDirectory]. Future inlineAssetsIntoDocument( - html.Document doc, Directory assetDirectory) async { + html.Document doc, Directory? assetDirectory) async { var linksWithRel = doc.head ?.getElementsByTagName('link') - ?.where((link) => link.attributes['rel'] == 'stylesheet') ?? + .where((link) => link.attributes['rel'] == 'stylesheet') ?? []; for (var link in linksWithRel) { if (link.attributes.containsKey('data-no-inline')) { link.attributes.remove('data-no-inline'); } else { - var uri = Uri.parse(link.attributes['href']); + var uri = Uri.parse(link.attributes['href']!); if (uri.scheme.isEmpty) { - var styleFile = assetDirectory.childFile(uri.path); + var styleFile = assetDirectory!.childFile(uri.path); if (await styleFile.exists()) { - var style = new html.Element.tag('style') + var style = html.Element.tag('style') ..innerHtml = await styleFile.readAsString(); link.replaceWith(style); } @@ -77,10 +77,10 @@ Future inlineAssetsIntoDocument( if (script.attributes.containsKey('data-no-inline')) { script.attributes.remove('data-no-inline'); } else { - var uri = Uri.parse(script.attributes['src']); + var uri = Uri.parse(script.attributes['src']!); if (uri.scheme.isEmpty) { - var scriptFile = assetDirectory.childFile(uri.path); + var scriptFile = assetDirectory!.childFile(uri.path); if (await scriptFile.exists()) { script.attributes.remove('src'); script.innerHtml = await scriptFile.readAsString(); diff --git a/packages/seo/pubspec.yaml b/packages/seo/pubspec.yaml index 3903330c..ff9dbf1e 100644 --- a/packages/seo/pubspec.yaml +++ b/packages/seo/pubspec.yaml @@ -1,21 +1,31 @@ name: angel_seo -description: Helper infrastructure for building SEO-friendly Web backends in Angel. -author: Tobe O -homepage: https://github.com/angel-dart/seo version: 2.0.0 +description: Helper infrastructure for building SEO-friendly Web backends in Angel. +homepage: https://github.com/angel-dart/seo +publish_to: none environment: - sdk: ">=2.10.0 <2.12.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - angel_framework: #^2.0.0-alpha - path: ../framework - angel_static: #^2.0.0-alpha - path: ../static - file: ^5.0.0 - html: ^0.13.0 - http_parser: ^3.0.0 - path: ^1.0.0 + angel_framework: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/framework + angel_static: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/static + file: ^6.1.2 + html: ^0.15.0 + http_parser: ^4.0.0 + path: ^1.8.0 dev_dependencies: - angel_test: #^2.0.0-alpha - path: ../test - logging: - test: ^1.15.7 \ No newline at end of file + angel_test: + git: + url: https://github.com/dukefirehawk/angel.git + ref: sdk-2.12.x_nnbd + path: packages/test + logging: ^1.0.1 + test: ^1.17.8 + pedantic: ^1.11.1 \ No newline at end of file diff --git a/packages/seo/test/inline_assets_test.dart b/packages/seo/test/inline_assets_test.dart index 669ef7c8..19429cc6 100644 --- a/packages/seo/test/inline_assets_test.dart +++ b/packages/seo/test/inline_assets_test.dart @@ -19,7 +19,7 @@ void main() { res ..useBuffer() ..contentType = MediaType.parse('text/html; charset=utf-8') - ..buffer.add(contents); + ..buffer!.add(contents); }); app.responseFinalizers.add(inlineAssets(dir)); @@ -34,11 +34,11 @@ void main() { } /// Typedef for backwards-compatibility with Dart 1. -typedef void InlineAssetTest(Angel app, Directory dir); +typedef InlineAssetTest = void Function(Angel app, Directory dir); void Function() inlineAssetsTests(InlineAssetTest f) { return () { - TestClient client; + late TestClient client; setUp(() async { var app = Angel(); @@ -49,7 +49,7 @@ void Function() inlineAssetsTests(InlineAssetTest f) { for (var path in contents.keys) { var file = fs.file(path); - await file.writeAsString(contents[path].trim()); + await file.writeAsString(contents[path]!.trim()); } app.logger = Logger('angel_seo') @@ -63,10 +63,11 @@ void Function() inlineAssetsTests(InlineAssetTest f) { tearDown(() => client.close()); group('sends html', () { - html.Document doc; + late html.Document doc; setUp(() async { - var res = await client.get('/', headers: {'accept': 'text/html'}); + var res = + await client.get(Uri.parse('/'), headers: {'accept': 'text/html'}); print(res.body); doc = html.parse(res.body); }); @@ -78,18 +79,18 @@ void Function() inlineAssetsTests(InlineAssetTest f) { test('populates a