From b652a7fc9fa23b35aed74a01d76036a1bc7d2b25 Mon Sep 17 00:00:00 2001 From: Victor Berchet Date: Fri, 22 Jul 2016 16:18:31 -0700 Subject: [PATCH] chore: remove obsolete files (#10240) --- gulpfile.js.old | 1583 ------ modules/@angular/README.dart.md | 6 - modules/@angular/common/common.dart | 1 - .../src/directives/observable_list_diff.dart | 63 - .../directives/normalize_validator.dart | 20 - .../@angular/common/src/pipes/date_pipe.ts | 3 - .../directives/observable_list_diff_spec.dart | 102 - modules/@angular/common/test/spies.dart | 14 - modules/@angular/compiler/core_private.dart | 1 - modules/@angular/compiler/private_export.dart | 1 - modules/@angular/compiler/src/assertions.dart | 3 - .../@angular/compiler/src/url_resolver.dart | 69 - .../test/directive_lifecycle_spec.dart | 148 - .../test/metadata_resolver_fixture.dart | 9 - .../test/schema/schema_extractor.dart | 5 - modules/@angular/compiler/test/spies.dart | 7 - modules/@angular/core/core.dart | 26 - modules/@angular/core/private_export.dart | 17 - .../src/change_detection/pipe_transform.dart | 33 - modules/@angular/core/src/di/decorators.dart | 52 - modules/@angular/core/src/di/forward_ref.dart | 15 - .../@angular/core/src/di/provider_util.dart | 20 - .../@angular/core/src/linker/query_list.dart | 44 - modules/@angular/core/src/metadata.dart | 228 - .../@angular/core/src/profile/wtf_impl.dart | 96 - .../@angular/core/src/profile/wtf_init.dart | 14 - .../debug_reflection_capabilities.dart | 63 - .../core/src/reflection/reflection.dart | 59 - .../reflection/reflection_capabilities.dart | 458 -- .../@angular/core/src/reflection/types.dart | 5 - modules/@angular/core/src/util.dart | 4 - .../@angular/core/src/util/decorators.dart | 1 - .../@angular/core/src/zone/ng_zone_impl.dart | 226 - .../core/test/change_detection/iterable.dart | 6 - .../@angular/core/test/di/binding_spec.dart | 60 - .../dom/html5lib_adapter.server.spec.dart | 34 - modules/@angular/core/test/dom/shim_spec.dart | 5 - .../core/test/facade/observable_spec.dart | 5 - .../test/forward_ref_integration_spec.dart | 6 - .../test/linker/integration_dart_spec.dart | 275 - .../core/test/metadata/decorators_spec.dart | 5 - .../core/test/profile/wtf_impl_spec.dart | 18 - .../test/reflection/reflector_common.dart | 34 - modules/@angular/core/test/spies.dart | 19 - .../core/test/util/decorators_spec.dart | 5 - modules/@angular/core/testing/async.dart | 4 - modules/@angular/core/testing/fake_async.dart | 103 - modules/@angular/core/testing/lang_utils.dart | 10 - modules/@angular/core/testing/testing.dart | 3 - .../core/testing/testing_internal.dart | 69 - .../@angular/docs/web_workers/web_workers.md | 81 +- .../ts/async_pipe/async_pipe_example.dart | 2 - .../pipes/ts/date_pipe/date_pipe_example.dart | 2 - modules/@angular/facade/src/async.dart | 132 - .../facade/src/base_wrapped_exception.dart | 17 - modules/@angular/facade/src/browser.dart | 32 - modules/@angular/facade/src/collection.dart | 287 - modules/@angular/facade/src/exceptions.dart | 50 - modules/@angular/facade/src/intl.dart | 57 - modules/@angular/facade/src/lang.dart | 373 -- modules/@angular/facade/src/math.dart | 24 - modules/@angular/facade/src/promise.dart | 58 - .../@angular/facade/test/async_dart_spec.dart | 106 - modules/@angular/forms/common.dart | 1 - .../src/directives/normalize_validator.dart | 20 - modules/@angular/forms/test/spies.dart | 14 - .../src/browser/location/history.dart | 3 - .../src/browser/tools/tools.dart | 39 - .../test/browser/tools/spies.dart | 26 - .../platform-server/compiler_private.dart | 1 - modules/@angular/platform-server/index.dart | 2 - .../platform-server/platform-server.dart | 1 - .../platform_browser_private.dart | 1 - .../src/abstract_html_adapter.dart | 457 -- .../platform-server/src/html_adapter.dart | 25 - .../platform-server/src/parse5_adapter.dart | 3 - .../platform-server/testing/server.dart | 1 - modules/@angular/pubspec.yaml | 35 - .../router-deprecated/core_private.dart | 1 - .../router-deprecated/src/interfaces.ts | 1 - .../src/lifecycle/lifecycle_annotations.dart | 8 - .../lifecycle/route_lifecycle_reflector.dart | 38 - .../route_config/route_config_decorator.dart | 3 - .../src/route_config/route_config_impl.ts | 2 - .../route_config/route_config_normalizer.dart | 30 - .../src/route_definition.dart | 11 - .../test/route_config/route_config_spec.dart | 9 - .../router-deprecated/test/spies.dart | 20 - .../benchmarks/e2e_test/compiler_perf.dart | 3 - modules/benchmarks/e2e_test/costs_perf.dart | 3 - modules/benchmarks/e2e_test/di_perf.dart | 3 - .../benchmarks/e2e_test/largetable_perf.dart | 3 - .../e2e_test/naive_infinite_scroll_perf.dart | 3 - .../e2e_test/naive_infinite_scroll_spec.dart | 3 - .../benchmarks/e2e_test/page_load_perf.dart | 3 - .../benchmarks/e2e_test/selector_perf.dart | 3 - .../benchmarks/e2e_test/static_tree_perf.dart | 3 - modules/benchmarks/e2e_test/tree_perf.dart | 3 - modules/benchmarks/pubspec.yaml | 38 - .../benchmarks/src/page_load/page_load.dart | 0 .../playground/e2e_test/async/async_spec.dart | 3 - .../hash_routing/hash_location_spec.dart | 3 - .../hello_world/hello_world_spec.dart | 3 - .../playground/e2e_test/http/http_spec.dart | 3 - .../playground/e2e_test/jsonp/jsonp_spec.dart | 3 - .../e2e_test/key_events/key_events_spec.dart | 3 - .../model_driven_forms_spec.dart | 3 - .../order_management_spec.dart | 3 - .../person_management_spec.dart | 3 - .../e2e_test/relative_assets/assets_spec.dart | 3 - .../e2e_test/routing/routing_spec.dart | 3 - .../routing_deprecated_spec.dart | 3 - .../e2e_test/sourcemap/sourcemap_spec.dart | 3 - modules/playground/e2e_test/svg/svg_spec.dart | 3 - .../template_driven_forms_spec.dart | 3 - .../web_workers/input/input_spec.dart | 3 - .../kitchen_sink/kitchen_sink_spec.dart | 3 - .../message_broker/message_broker_spec.dart | 3 - .../web_workers/router/router_spec.dart | 3 - .../e2e_test/web_workers/todo/todo_spec.dart | 3 - .../e2e_test/zippy_component/zippy_spec.dart | 3 - modules/playground/pubspec.yaml | 81 - .../src/relative_assets/app/my_cmp.dart | 9 - modules/playground/src/upgrade/index.dart | 5 - .../web_workers/images/background_index.dart | 13 - .../src/web_workers/images/file_api.dart | 9 - .../src/web_workers/images/index.dart | 11 - .../web_workers/images/services/bitmap.dart | 23 - .../web_workers/input/background_index.dart | 11 - .../src/web_workers/input/index.dart | 9 - .../kitchen_sink/background_index.dart | 11 - .../src/web_workers/kitchen_sink/index.dart | 9 - .../message_broker/background_index.dart | 11 - .../src/web_workers/message_broker/index.dart | 23 - .../web_workers/router/background_index.dart | 13 - .../src/web_workers/router/index.dart | 12 - .../web_workers/todo/background_index.dart | 11 - .../src/web_workers/todo/index.dart | 9 - .../web_workers/todo/index_web_socket.dart | 24 - .../src/web_workers/todo/server_index.dart | 34 - .../webdriver_async.server.spec.dart | 56 - scripts/ci-lite/install.sh | 2 - scripts/ci/build_dart.sh | 12 - scripts/ci/build_dart_ddc.sh | 170 - scripts/ci/dart_ddc/pubspec_for_ddc.js | 25 - scripts/ci/env_dart.sh | 101 - scripts/ci/install_dart.sh | 31 - scripts/ci/test_dart.sh | 12 - scripts/ci/test_e2e_dart.sh | 34 - scripts/ci/test_server_dart.sh | 38 - scripts/publish/pub_prepare.sh | 25 - scripts/publish/pub_publish.sh | 38 - scripts/publish/pubspec_cleaner.js | 35 - tools/build/create_dart_test_main.js | 21 - tools/build/dart.js | 46 - tools/build/dartanalyzer.js | 235 - tools/build/dartapidocs.js | 37 - tools/build/proto.js | 123 - tools/build/protoc-gen-dart | 5015 ----------------- tools/build/protoc.js | 18 - tools/build/pubbuild.js | 78 - tools/build/pubget.js | 36 - tools/build/pubserve.js | 14 - tools/build/pubtest.js | 51 - tools/build/run_server_dart_tests.js | 51 - tools/build/rundartpackage.js | 44 - 166 files changed, 1 insertion(+), 12836 deletions(-) delete mode 100644 gulpfile.js.old delete mode 100644 modules/@angular/README.dart.md delete mode 100644 modules/@angular/common/common.dart delete mode 100644 modules/@angular/common/src/directives/observable_list_diff.dart delete mode 100644 modules/@angular/common/src/forms-deprecated/directives/normalize_validator.dart delete mode 100644 modules/@angular/common/test/directives/observable_list_diff_spec.dart delete mode 100644 modules/@angular/common/test/spies.dart delete mode 100644 modules/@angular/compiler/core_private.dart delete mode 100644 modules/@angular/compiler/private_export.dart delete mode 100644 modules/@angular/compiler/src/assertions.dart delete mode 100644 modules/@angular/compiler/src/url_resolver.dart delete mode 100644 modules/@angular/compiler/test/directive_lifecycle_spec.dart delete mode 100644 modules/@angular/compiler/test/metadata_resolver_fixture.dart delete mode 100644 modules/@angular/compiler/test/schema/schema_extractor.dart delete mode 100644 modules/@angular/compiler/test/spies.dart delete mode 100644 modules/@angular/core/core.dart delete mode 100644 modules/@angular/core/private_export.dart delete mode 100644 modules/@angular/core/src/change_detection/pipe_transform.dart delete mode 100644 modules/@angular/core/src/di/decorators.dart delete mode 100644 modules/@angular/core/src/di/forward_ref.dart delete mode 100644 modules/@angular/core/src/di/provider_util.dart delete mode 100644 modules/@angular/core/src/linker/query_list.dart delete mode 100644 modules/@angular/core/src/metadata.dart delete mode 100644 modules/@angular/core/src/profile/wtf_impl.dart delete mode 100644 modules/@angular/core/src/profile/wtf_init.dart delete mode 100644 modules/@angular/core/src/reflection/debug_reflection_capabilities.dart delete mode 100644 modules/@angular/core/src/reflection/reflection.dart delete mode 100644 modules/@angular/core/src/reflection/reflection_capabilities.dart delete mode 100644 modules/@angular/core/src/reflection/types.dart delete mode 100644 modules/@angular/core/src/util.dart delete mode 100644 modules/@angular/core/src/util/decorators.dart delete mode 100644 modules/@angular/core/src/zone/ng_zone_impl.dart delete mode 100644 modules/@angular/core/test/change_detection/iterable.dart delete mode 100644 modules/@angular/core/test/di/binding_spec.dart delete mode 100644 modules/@angular/core/test/dom/html5lib_adapter.server.spec.dart delete mode 100644 modules/@angular/core/test/dom/shim_spec.dart delete mode 100644 modules/@angular/core/test/facade/observable_spec.dart delete mode 100644 modules/@angular/core/test/forward_ref_integration_spec.dart delete mode 100644 modules/@angular/core/test/linker/integration_dart_spec.dart delete mode 100644 modules/@angular/core/test/metadata/decorators_spec.dart delete mode 100644 modules/@angular/core/test/profile/wtf_impl_spec.dart delete mode 100644 modules/@angular/core/test/reflection/reflector_common.dart delete mode 100644 modules/@angular/core/test/spies.dart delete mode 100644 modules/@angular/core/test/util/decorators_spec.dart delete mode 100644 modules/@angular/core/testing/async.dart delete mode 100644 modules/@angular/core/testing/fake_async.dart delete mode 100644 modules/@angular/core/testing/lang_utils.dart delete mode 100644 modules/@angular/core/testing/testing.dart delete mode 100644 modules/@angular/core/testing/testing_internal.dart delete mode 100644 modules/@angular/examples/core/pipes/ts/async_pipe/async_pipe_example.dart delete mode 100644 modules/@angular/examples/core/pipes/ts/date_pipe/date_pipe_example.dart delete mode 100644 modules/@angular/facade/src/async.dart delete mode 100644 modules/@angular/facade/src/base_wrapped_exception.dart delete mode 100644 modules/@angular/facade/src/browser.dart delete mode 100644 modules/@angular/facade/src/collection.dart delete mode 100644 modules/@angular/facade/src/exceptions.dart delete mode 100644 modules/@angular/facade/src/intl.dart delete mode 100644 modules/@angular/facade/src/lang.dart delete mode 100644 modules/@angular/facade/src/math.dart delete mode 100644 modules/@angular/facade/src/promise.dart delete mode 100644 modules/@angular/facade/test/async_dart_spec.dart delete mode 100644 modules/@angular/forms/common.dart delete mode 100644 modules/@angular/forms/src/directives/normalize_validator.dart delete mode 100644 modules/@angular/forms/test/spies.dart delete mode 100644 modules/@angular/platform-browser/src/browser/location/history.dart delete mode 100644 modules/@angular/platform-browser/src/browser/tools/tools.dart delete mode 100644 modules/@angular/platform-browser/test/browser/tools/spies.dart delete mode 100644 modules/@angular/platform-server/compiler_private.dart delete mode 100644 modules/@angular/platform-server/index.dart delete mode 100644 modules/@angular/platform-server/platform-server.dart delete mode 100644 modules/@angular/platform-server/platform_browser_private.dart delete mode 100644 modules/@angular/platform-server/src/abstract_html_adapter.dart delete mode 100644 modules/@angular/platform-server/src/html_adapter.dart delete mode 100644 modules/@angular/platform-server/src/parse5_adapter.dart delete mode 100644 modules/@angular/platform-server/testing/server.dart delete mode 100644 modules/@angular/pubspec.yaml delete mode 100644 modules/@angular/router-deprecated/core_private.dart delete mode 100644 modules/@angular/router-deprecated/src/lifecycle/lifecycle_annotations.dart delete mode 100644 modules/@angular/router-deprecated/src/lifecycle/route_lifecycle_reflector.dart delete mode 100644 modules/@angular/router-deprecated/src/route_config/route_config_decorator.dart delete mode 100644 modules/@angular/router-deprecated/src/route_config/route_config_normalizer.dart delete mode 100644 modules/@angular/router-deprecated/src/route_definition.dart delete mode 100644 modules/@angular/router-deprecated/test/route_config/route_config_spec.dart delete mode 100644 modules/@angular/router-deprecated/test/spies.dart delete mode 100644 modules/benchmarks/e2e_test/compiler_perf.dart delete mode 100644 modules/benchmarks/e2e_test/costs_perf.dart delete mode 100644 modules/benchmarks/e2e_test/di_perf.dart delete mode 100644 modules/benchmarks/e2e_test/largetable_perf.dart delete mode 100644 modules/benchmarks/e2e_test/naive_infinite_scroll_perf.dart delete mode 100644 modules/benchmarks/e2e_test/naive_infinite_scroll_spec.dart delete mode 100644 modules/benchmarks/e2e_test/page_load_perf.dart delete mode 100644 modules/benchmarks/e2e_test/selector_perf.dart delete mode 100644 modules/benchmarks/e2e_test/static_tree_perf.dart delete mode 100644 modules/benchmarks/e2e_test/tree_perf.dart delete mode 100644 modules/benchmarks/pubspec.yaml delete mode 100644 modules/benchmarks/src/page_load/page_load.dart delete mode 100644 modules/playground/e2e_test/async/async_spec.dart delete mode 100644 modules/playground/e2e_test/hash_routing/hash_location_spec.dart delete mode 100644 modules/playground/e2e_test/hello_world/hello_world_spec.dart delete mode 100644 modules/playground/e2e_test/http/http_spec.dart delete mode 100644 modules/playground/e2e_test/jsonp/jsonp_spec.dart delete mode 100644 modules/playground/e2e_test/key_events/key_events_spec.dart delete mode 100644 modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.dart delete mode 100644 modules/playground/e2e_test/order_management/order_management_spec.dart delete mode 100644 modules/playground/e2e_test/person_management/person_management_spec.dart delete mode 100644 modules/playground/e2e_test/relative_assets/assets_spec.dart delete mode 100644 modules/playground/e2e_test/routing/routing_spec.dart delete mode 100644 modules/playground/e2e_test/routing_deprecated/routing_deprecated_spec.dart delete mode 100644 modules/playground/e2e_test/sourcemap/sourcemap_spec.dart delete mode 100644 modules/playground/e2e_test/svg/svg_spec.dart delete mode 100644 modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.dart delete mode 100644 modules/playground/e2e_test/web_workers/input/input_spec.dart delete mode 100644 modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.dart delete mode 100644 modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.dart delete mode 100644 modules/playground/e2e_test/web_workers/router/router_spec.dart delete mode 100644 modules/playground/e2e_test/web_workers/todo/todo_spec.dart delete mode 100644 modules/playground/e2e_test/zippy_component/zippy_spec.dart delete mode 100644 modules/playground/pubspec.yaml delete mode 100644 modules/playground/src/relative_assets/app/my_cmp.dart delete mode 100644 modules/playground/src/upgrade/index.dart delete mode 100644 modules/playground/src/web_workers/images/background_index.dart delete mode 100644 modules/playground/src/web_workers/images/file_api.dart delete mode 100644 modules/playground/src/web_workers/images/index.dart delete mode 100644 modules/playground/src/web_workers/images/services/bitmap.dart delete mode 100644 modules/playground/src/web_workers/input/background_index.dart delete mode 100644 modules/playground/src/web_workers/input/index.dart delete mode 100644 modules/playground/src/web_workers/kitchen_sink/background_index.dart delete mode 100644 modules/playground/src/web_workers/kitchen_sink/index.dart delete mode 100644 modules/playground/src/web_workers/message_broker/background_index.dart delete mode 100644 modules/playground/src/web_workers/message_broker/index.dart delete mode 100644 modules/playground/src/web_workers/router/background_index.dart delete mode 100644 modules/playground/src/web_workers/router/index.dart delete mode 100644 modules/playground/src/web_workers/todo/background_index.dart delete mode 100644 modules/playground/src/web_workers/todo/index.dart delete mode 100644 modules/playground/src/web_workers/todo/index_web_socket.dart delete mode 100644 modules/playground/src/web_workers/todo/server_index.dart delete mode 100644 modules/playground/test/benchpress/webdriver_async.server.spec.dart delete mode 100755 scripts/ci/build_dart.sh delete mode 100755 scripts/ci/build_dart_ddc.sh delete mode 100644 scripts/ci/dart_ddc/pubspec_for_ddc.js delete mode 100755 scripts/ci/env_dart.sh delete mode 100755 scripts/ci/install_dart.sh delete mode 100755 scripts/ci/test_dart.sh delete mode 100755 scripts/ci/test_e2e_dart.sh delete mode 100755 scripts/ci/test_server_dart.sh delete mode 100755 scripts/publish/pub_prepare.sh delete mode 100755 scripts/publish/pub_publish.sh delete mode 100644 scripts/publish/pubspec_cleaner.js delete mode 100644 tools/build/create_dart_test_main.js delete mode 100644 tools/build/dart.js delete mode 100644 tools/build/dartanalyzer.js delete mode 100644 tools/build/dartapidocs.js delete mode 100644 tools/build/proto.js delete mode 100755 tools/build/protoc-gen-dart delete mode 100644 tools/build/protoc.js delete mode 100644 tools/build/pubbuild.js delete mode 100644 tools/build/pubget.js delete mode 100644 tools/build/pubserve.js delete mode 100644 tools/build/pubtest.js delete mode 100644 tools/build/run_server_dart_tests.js delete mode 100644 tools/build/rundartpackage.js diff --git a/gulpfile.js.old b/gulpfile.js.old deleted file mode 100644 index 4deb8ea86b..0000000000 --- a/gulpfile.js.old +++ /dev/null @@ -1,1583 +0,0 @@ -'use strict'; - -// THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE -// This is to ensure that we catch env issues before we error while requiring other dependencies. -require('./tools/check-environment')( - {requiredNpmVersion: '>=3.5.3 <4.0.0', requiredNodeVersion: '>=5.4.1 <6.0.0'}); - - -var fse = require('fs-extra'); -var gulp = require('gulp'); -var gulpPlugins = require('gulp-load-plugins')(); -var merge = require('merge'); -var merge2 = require('merge2'); -var minimist = require('minimist'); -var os = require('os'); -var path = require('path'); -var runSequence = require('run-sequence'); -var shell = require('gulp-shell'); - -var licenseWrap = require('./tools/build/licensewrap'); -var analytics = require('./tools/analytics/analytics'); -var pubget = require('./tools/build/pubget'); -var linknodemodules = require('./tools/build/linknodemodules'); -var pubbuild = require('./tools/build/pubbuild'); -var jsserve = require('./tools/build/jsserve'); -var pubserve = require('./tools/build/pubserve'); -var runServerDartTests = require('./tools/build/run_server_dart_tests'); -var util = require('./tools/build/util'); -var buildRouter = require('./modules/angular1_router/build'); -var shouldLog = require('./tools/build/logging'); -var dartSdk = require('./tools/build/dart'); -var browserProvidersConf = require('./browser-providers.conf.js'); - - - -var cliArgs = minimist(process.argv.slice(2)); - -if (cliArgs.projects) { - // normalize for analytics - cliArgs.projects.split(',').sort().join(','); -} - -// --projects=angular2 => {angular2: true} -var allProjects = - 'angular1_router,angular2,benchmarks,benchmarks_external,benchpress,playground,payload_tests,bundle_deps'; -var cliArgsProjects = (cliArgs.projects || allProjects) - .split(',') - .reduce((map, projectName) => { - map[projectName] = true; - return map; - }, {}); -var generateEs6 = !cliArgs.projects; - -function printModulesWarning() { - if (!cliArgs.projects && !process.env.CI) { - // if users didn't specify projects to build, tell them why and how they should - console.warn( - "Pro Tip: Did you know that you can speed up your build by specifying project name(s)?"); - console.warn(" It's like pressing the turbo button in the old days, but better!"); - console.warn(" Examples: --project=angular2 or --project=angular2"); - } -} - - -// Make it easy to quiet down portions of the build. -// --logs=all -> log everything (This is the default) -// --logs=quiet -> log nothing -// --logs= -> log listed items. -// -// Not all commands support optional logging, feel free -// to add support by adding a new key to this list, -// and toggling output from the command based on it. -var logs = {dartfmt: shouldLog('dartfmt')}; - -// dynamic require in build.tools so we can bootstrap TypeScript compilation -function throwToolsBuildMissingError() { - throw new Error('ERROR: build.tools task should have been run before using angularBuilder'); -} - -var angularBuilder = { - rebuildBrowserDevTree: throwToolsBuildMissingError, - rebuildBrowserProdTree: throwToolsBuildMissingError, - rebuildNodeTree: throwToolsBuildMissingError, - rebuildDartTree: throwToolsBuildMissingError, - uninitialized: true -}; - - -function sequenceComplete(done) { - return function(err) { - if (err) { - var error = new Error('build sequence failed'); - error.showStack = false; - done(error); - } else { - done(); - } - }; -} - - -var treatTestErrorsAsFatal = true; - -function runJasmineTests(globs, done) { - var fork = require('child_process').fork; - var args = ['--'].concat(globs); - - fork('./dist/tools/cjs-jasmine', args, {stdio: 'inherit'}) - .on('close', function jasmineCloseHandler(exitCode) { - if (exitCode && treatTestErrorsAsFatal) { - var err = new Error('Jasmine tests failed'); - // Mark the error for gulp similar to how gulp-utils.PluginError does it. - // The stack is not useful in this context. - err.showStack = false; - done(err); - } else { - done(); - } - }); -} - -// Note: when DART_SDK is not found, all gulp tasks ending with `.dart` will be skipped. -var DART_SDK = dartSdk.detect(gulp); - -// ----------------------- -// configuration - -var CONFIG = { - dest: { - js: { - all: 'dist/js', - dev: {es6: 'dist/js/dev/es6', es5: 'dist/js/dev/es5'}, - prod: {es6: 'dist/js/prod/es6', es5: 'dist/js/prod/es5'}, - cjs: 'dist/js/cjs', - dart2js: 'dist/js/dart2js', - dart_dev_compiler: 'dist/js/ddc' - }, - dart: 'dist/dart', - docs: 'dist/docs', - docs_angular_io: 'dist/angular.io', - bundles: {all: 'dist/build', benchpress: 'dist/build/benchpress_bundle/'} - } -}; - -var ANGULAR2_BUNDLE_CONFIG = [ - 'angular2/common', - 'angular2/core', - 'angular2/compiler', - 'angular2/instrumentation', - 'angular2/platform/browser', - 'angular2/platform/common_dom' -]; - -var NG2_BUNDLE_CONTENT = ANGULAR2_BUNDLE_CONFIG.join(' + ') + ' - rxjs/*'; -var HTTP_BUNDLE_CONTENT = 'angular2/http - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); -var ROUTER_BUNDLE_CONTENT = 'angular2/router + angular2/router/router_link_dsl - rxjs/* - ' + - ANGULAR2_BUNDLE_CONFIG.join(' - '); -var ALT_ROUTER_BUNDLE_CONTENT = - 'angular2/alt_router - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); -var TESTING_BUNDLE_CONTENT = - 'angular2/testing + angular2/http/testing + angular2/router/testing + angular2/platform/testing/browser - rxjs/* - ' + - ANGULAR2_BUNDLE_CONFIG.join(' - '); -var UPGRADE_BUNDLE_CONTENT = 'angular2/upgrade - rxjs/* - ' + ANGULAR2_BUNDLE_CONFIG.join(' - '); - -var BENCHPRESS_BUNDLE_CONFIG = { - entries: ['./dist/js/cjs/benchpress/index.js'], - packageJson: './dist/js/cjs/benchpress/package.json', - includes: ['angular2'], - excludes: ['reflect-metadata', 'selenium-webdriver', 'zone.js'], - ignore: [], - dest: CONFIG.dest.bundles.benchpress -}; - -var PAYLOAD_TESTS_CONFIG = { - ts: { - bundleName: 'app-bundle-deps.min.js', - cases: ['hello_world'], - dist: function(caseName, packaging) { - return path.join(__dirname, CONFIG.dest.js.prod.es5, 'payload_tests', caseName, - 'ts/' + packaging); - }, - systemjs: {sizeLimits: {'uncompressed': 880 * 1024, 'gzip level=9': 170 * 1024}}, - webpack: {sizeLimits: {'uncompressed': 560 * 1024, 'gzip level=9': 130 * 1024}} - } -}; - -// ------------ -// clean - -gulp.task('build/clean.tools', (done) => fse.remove(path.join('dist', 'tools'), done)); - -gulp.task('build/clean.js', (done) => fse.remove(CONFIG.dest.js.all, done)); - -gulp.task('build/clean.dart', (done) => fse.remove(CONFIG.dest.dart, done)); - -gulp.task('build/clean.docs', (done) => fse.remove(CONFIG.dest.docs, done)); - -gulp.task('build/clean.docs_angular_io', (done) => fse.remove(CONFIG.dest.docs_angular_io, done)); - -gulp.task('build/clean.bundles', (done) => fse.remove(CONFIG.dest.bundles.all, done)); - -gulp.task('build/clean.bundles.benchpress', - (done) => fse.remove(CONFIG.dest.bundles.benchpress, done)); - -// ------------ -// transpile - -gulp.task('build/tree.dart', ['build/clean.dart', 'build.tools'], - function(done) { runSequence('!build/tree.dart', sequenceComplete(done)); }); - - -gulp.task('!build/tree.dart', - function() { return angularBuilder.rebuildDartTree(cliArgsProjects); }); - - -// ------------ -// pubspec - -// Run a top-level `pub get` for this project. -gulp.task('pubget.dart', pubget.dir(gulp, gulpPlugins, {dir: '.', command: DART_SDK.PUB})); - -// Run `pub get` only on the angular2 dir of CONFIG.dest.dart -gulp.task('!build/pubget.angular2.dart', - pubget.dir(gulp, gulpPlugins, - {dir: path.join(CONFIG.dest.dart, 'angular2'), command: DART_SDK.PUB})); - -// Run `pub get` over CONFIG.dest.dart -gulp.task('build/pubspec.dart', - pubget.subDir(gulp, gulpPlugins, {dir: CONFIG.dest.dart, command: DART_SDK.PUB})); - - -// This is a hacky way to work around dart's pub that creates `packages` symlink in every directory -// that contains a dart file with the main method. For our tests this means that every test -// subfolder -// has a link to the root `packages` directory which causes Karma to sift through 80k files during -// each `karma run` invocation. -// -// Since these directories are not needed for karma tests to run, it's safe to delete them without -// breaking any functionality. -// -// See #2437 for more info. -gulp.task('!build/remove-pub-symlinks', function(done) { - var exec = require('child_process').exec; - - if (process.platform == 'win32') { - done(); - return; - } - - exec('find dist/dart/angular2/test/ -name packages | xargs rm -r', - function(error, stdout, stderr) { - if (error) { - done(stderr); - return; - } - done(); - }); -}); - -// ------------ -// dartanalyzer - - -gulp.task('build/analyze.dart', () => { - var dartanalyzer = require('./tools/build/dartanalyzer'); - - return dartanalyzer(gulp, gulpPlugins, {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER}); -}); - - -gulp.task('build/analyze.ddc.dart', () => { - var dartanalyzer = require('./tools/build/dartanalyzer'); - - return dartanalyzer(gulp, gulpPlugins, - {dest: CONFIG.dest.dart, command: DART_SDK.ANALYZER, use_ddc: true}); -}); - - -gulp.task('build/check.apidocs.dart', () => { - var dartapidocs = require('./tools/build/dartapidocs'); - - return dartapidocs(gulp, gulpPlugins, - {dest: CONFIG.dest.dart, output: os.tmpdir(), command: DART_SDK.DARTDOCGEN}); -}); - - -// ------------ -// pubbuild -// WARNING: this task is very slow (~15m as of July 2015) - -gulp.task( - 'build/pubbuild.dart', - pubbuild.subdirs(gulp, gulpPlugins, - {src: CONFIG.dest.dart, dest: CONFIG.dest.js.dart2js, command: DART_SDK.PUB})); - -// ------------ -// formatting - -function doCheckFormat() { - var clangFormat = require('clang-format'); - var gulpFormat = require('gulp-clang-format'); - - return gulp.src([ - 'modules/**/*.ts', - 'tools/**/*.ts', - '!**/typings/**/*.d.ts', - // workaround https://github.com/angular/clang-format/issues/28 - '!tools/compiler_cli/src/main.ts', - 'gulpfile.js' - ]) - .pipe(gulpFormat.checkFormat('file', clangFormat)); -} - -gulp.task('check-format', function() { - return doCheckFormat().on('warning', function(e) { - console.log("NOTE: this will be promoted to an ERROR in the continuous build"); - }); -}); - -gulp.task('enforce-format', function() { - return doCheckFormat().on('warning', function(e) { - console.log("ERROR: You forgot to run clang-format on your change."); - console.log("See https://github.com/angular/angular/blob/master/DEVELOPER.md#clang-format"); - process.exit(1); - }); -}); - -gulp.task('lint', ['build.tools'], function() { - var tslint = require('gulp-tslint'); - // Built-in rules are at - // https://github.com/palantir/tslint#supported-rules - var tslintConfig = require('./tslint.json'); - return gulp.src(['modules/angular2/src/**/*.ts', '!modules/angular2/src/testing/**']) - .pipe(tslint({ - tslint: require('tslint').default, - configuration: tslintConfig, - rulesDirectory: 'dist/tools/tslint' - })) - .pipe(tslint.report('prose', {emitError: true})); -}); - -// ------------ -// check circular dependencies in Node.js context -gulp.task('build/checkCircularDependencies', function(done) { - var madge = require('madge'); - - var dependencyObject = madge([CONFIG.dest.js.dev.es5], { - format: 'cjs', - extensions: ['.js'], - onParseFile: function(data) { data.src = data.src.replace(/\/\* circular \*\//g, "//"); } - }); - var circularDependencies = dependencyObject.circular().getArray(); - if (circularDependencies.length > 0) { - console.log(circularDependencies); - process.exit(1); - } - done(); -}); - -function jsServeDev() { - return jsserve(gulp, gulpPlugins, {path: CONFIG.dest.js.dev.es5, port: 8000})(); -} - -function jsServeProd() { - return jsserve(gulp, gulpPlugins, {path: CONFIG.dest.js.prod.es5, port: 8001})(); -} - -function jsServeDartJs() { - return jsserve(gulp, gulpPlugins, {path: CONFIG.dest.js.dart2js, port: 8002})(); -} - -function jsServeDartDevCompiler() { - return jsserve(gulp, gulpPlugins, {path: CONFIG.dest.js.dart_dev_compiler, port: 8003})(); -} - -function proxyServeDart() { - return jsserve(gulp, gulpPlugins, { - port: 8002, - proxies: [ - {route: '/playground', url: 'http://localhost:8004'}, - {route: '/benchmarks_external', url: 'http://localhost:8008'}, - {route: '/benchmarks', url: 'http://localhost:8006'} - ] - })(); -} - -// ------------------ -// web servers -gulp.task('serve.js.dev', ['build.js.dev', 'build.js.cjs'], function(neverDone) { - var watch = require('./tools/build/watch'); - - watch('modules/**', {ignoreInitial: true}, '!broccoli.js.dev'); - jsServeDev(); -}); - -gulp.task('serve.js.prod', jsServeProd); - -gulp.task('serve.e2e.dev', ['build.js.dev', 'build.js.cjs'], function(neverDone) { - var watch = require('./tools/build/watch'); - - watch('modules/**', {ignoreInitial: true}, ['!broccoli.js.dev', '!build.js.cjs']); - jsServeDev(); -}); - -gulp.task('serve.e2e.prod', ['build.js.prod', 'build.js.cjs'], function(neverDone) { - var watch = require('./tools/build/watch'); - - watch('modules/**', {ignoreInitial: true}, ['!broccoli.js.prod', '!build.js.cjs']); - jsServeProd(); -}); - -gulp.task('serve.js.dart2js', jsServeDartJs); - -gulp.task('serve.js.ddc', jsServeDartDevCompiler); - -gulp.task('!proxyServeDart', proxyServeDart); - -gulp.task('serve.dart', function(done) { - runSequence( - [ - '!proxyServeDart', - 'serve/playground.dart', - 'serve/benchmarks.dart', - 'serve/benchmarks_external.dart' - ], - done); -}); - -gulp.task('serve/playground.dart', - pubserve(gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/playground', port: 8004})); - -gulp.task('serve/benchmarks.dart', - pubserve(gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks', port: 8006})); - -gulp.task( - 'serve/benchmarks_external.dart', - pubserve(gulp, gulpPlugins, - {command: DART_SDK.PUB, path: CONFIG.dest.dart + '/benchmarks_external', port: 8008})); - -gulp.task('serve.e2e.dart', ['build.js.cjs'], function(neverDone) { - var watch = require('./tools/build/watch'); - - // Note: we are not using build.dart as the dart analyzer takes too long... - watch('modules/**', {ignoreInitial: true}, ['!build/tree.dart', '!build.js.cjs']); - runSequence('build/packages.dart', 'build/pubspec.dart', 'serve.dart'); -}); - - -// ------------------ -// CI tests suites - -function execProcess(name, args, done) { - var exec = require('child_process').exec; - - var cmd = process.platform === 'win32' ? 'node_modules\\.bin\\' + name + ' ' : - 'node node_modules/.bin/' + name + ' '; - cmd += args; - exec(cmd, done); -} -function runKarma(configFile, done) { - execProcess('karma', 'run ' + configFile, function(e, stdout) { - // ignore errors, we don't want to fail the build in the interactive (non-ci) mode - // karma server will print all test failures - done(); - }); -} - -// Gulp-typescript doesn't work with typescript@next: -// https://github.com/ivogabe/gulp-typescript/issues/331 -function runTsc(project, done) { - execProcess('tsc', '-p ' + project, function(e, stdout, stderr) { - if (e) { - console.log(stdout); - console.error(stderr); - done(e); - } else { - done(); - } - }); -} - -gulp.task('test.js', function(done) { - runSequence('test.compiler_cli', 'test.unit.tools/ci', 'test.transpiler.unittest', - 'test.unit.js/ci', 'test.unit.cjs/ci', 'test.typings', 'check-public-api', - sequenceComplete(done)); -}); - -gulp.task('test.dart', function(done) { - runSequence('versions.dart', 'test.transpiler.unittest', 'test.unit.dart/ci', - sequenceComplete(done)); -}); - -gulp.task('versions.dart', function() { dartSdk.logVersion(DART_SDK); }); - -// Reuse the Travis scripts -// TODO: rename test_*.sh to test_all_*.sh -gulp.task('test.all.js', shell.task(['./scripts/ci/test_js.sh'])); -gulp.task('test.all.dart', shell.task(['./scripts/ci/test_dart.sh'])); - -// karma tests -// These tests run in the browser and are allowed to access -// HTML DOM APIs. -function getBrowsersFromCLI(provider, isDart) { - var isProvider = false; - var rawInput = - cliArgs.browsers ? cliArgs.browsers : (isDart ? 'DartiumWithWebPlatform' : 'Chrome'); - var inputList = rawInput.replace(' ', '').split(','); - var outputList = []; - for (var i = 0; i < inputList.length; i++) { - var input = inputList[i]; - var karmaChromeLauncher = require('karma-chrome-launcher'); - if (browserProvidersConf.customLaunchers.hasOwnProperty(input) || - karmaChromeLauncher.hasOwnProperty("launcher:" + input)) { - // In case of non-sauce browsers, or browsers defined in karma-chrome-launcher (Chrome, - // ChromeCanary and Dartium): - // overrides everything, ignoring other options - outputList = [input]; - isProvider = false; - break; - } else if (provider && - browserProvidersConf.customLaunchers.hasOwnProperty(provider + "_" + - input.toUpperCase())) { - isProvider = true; - outputList.push(provider + "_" + input.toUpperCase()); - } else if (provider && provider == 'SL' && - browserProvidersConf.sauceAliases.hasOwnProperty(input.toUpperCase())) { - outputList = outputList.concat(browserProvidersConf.sauceAliases[input.toUpperCase()]); - isProvider = true; - } else if (provider && provider == 'BS' && - browserProvidersConf.browserstackAliases.hasOwnProperty(input.toUpperCase())) { - outputList = outputList.concat(browserProvidersConf.browserstackAliases[input.toUpperCase()]); - isProvider = true; - } else { - throw new Error('ERROR: unknown browser found in getBrowsersFromCLI()'); - } - } - return { - browsersToRun: - outputList.filter(function(item, pos, self) { return self.indexOf(item) == pos; }), - isProvider: isProvider - }; -} - -gulp.task('test.unit.js', ['build.js.dev'], function(neverDone) { - var watch = require('./tools/build/watch'); - - printModulesWarning(); - runSequence('!test.unit.js/karma-server', function() { - watch('modules/**', {ignoreInitial: true}, ['!broccoli.js.dev', '!test.unit.js/karma-run']); - }); -}); - -gulp.task('watch.js.dev', ['build.js.dev'], function(neverDone) { - var watch = require('./tools/build/watch'); - - printModulesWarning(); - watch('modules/**', ['!broccoli.js.dev']); -}); - -gulp.task('test.unit.js.sauce', ['build.js.dev'], function(done) { - printModulesWarning(); - var browserConf = getBrowsersFromCLI('SL'); - if (browserConf.isProvider) { - launchKarmaWithExternalBrowsers(['dots'], browserConf.browsersToRun, done); - } else { - throw new Error('ERROR: no Saucelabs browsers provided, add them with the --browsers option'); - } -}); - -gulp.task('test.unit.js.browserstack', ['build.js.dev'], function(done) { - printModulesWarning(); - var browserConf = getBrowsersFromCLI('BS'); - if (browserConf.isProvider) { - launchKarmaWithExternalBrowsers(['dots'], browserConf.browsersToRun, done); - } else { - throw new Error( - 'ERROR: no Browserstack browsers provided, add them with the --browsers option'); - } -}); - -function launchKarmaWithExternalBrowsers(reporters, browsers, done) { - var karma = require('karma'); - - new karma.Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - browserNoActivityTimeout: 240000, - captureTimeout: 120000, - reporters: reporters, - browsers: browsers - }, - function(err) { - done(); - process.exit(err ? 1 : 0); - }) - .start(); -} - -gulp.task('!test.unit.js/karma-server', function(done) { - var karma = require('karma'); - - var watchStarted = false; - var server = new karma.Server({configFile: __dirname + '/karma-js.conf.js'}); - server.on('run_complete', function() { - if (!watchStarted) { - watchStarted = true; - done(); - } - }); - server.start(); -}); - - -gulp.task('!test.unit.js/karma-run', function(done) { - // run the run command in a new process to avoid duplicate logging by both server and runner from - // a single process - runKarma('karma-js.conf.js', done); -}); - -gulp.task('test.unit.router', function(neverDone) { - var watch = require('./tools/build/watch'); - - runSequence('!test.unit.router/karma-server', function() { - watch('modules/**', ['buildRouter.dev', '!test.unit.router/karma-run']); - }); -}); - -gulp.task('!test.unit.router/karma-server', function() { - var karma = require('karma'); - - new karma.Server({configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}) - .start(); -}); - - -gulp.task('!test.unit.router/karma-run', function(done) { - var karma = require('karma'); - - karma.runner.run({configFile: __dirname + '/modules/angular1_router/karma-router.conf.js'}, - function(exitCode) { - // ignore exitCode, we don't want to fail the build in the interactive (non-ci) - // mode - // karma will print all test failures - done(); - }); -}); - -gulp.task('buildRouter.dev', function() { - var modulesSrcDir = __dirname + '/modules'; - var distDir = __dirname + '/dist'; - buildRouter(modulesSrcDir, distDir); -}); - -gulp.task('test.unit.dart', function(done) { - printModulesWarning(); - runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); - - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } - // treatTestErrorsAsFatal = false; - - watch(['modules/angular2/**'], - ['!build/tree.dart', '!test.unit.dart/run/angular2']); - }); -}); - -// Dart Payload Size Test -// This test will fail if the size of our hello_world app goes beyond one of -// these values when compressed at the specified level. -// Measure in bytes. -var _DART_PAYLOAD_SIZE_LIMITS = {'uncompressed': 320 * 1024, 'gzip level=9': 90 * 1024}; -gulp.task('test.payload.dart/ci', function(done) { - runSequence('build/packages.dart', '!pubget.payload.dart', '!pubbuild.payload.dart', - '!checkAndReport.payload.dart', done); -}); - -gulp.task('!pubget.payload.dart', - pubget.dir(gulp, gulpPlugins, - {dir: 'modules_dart/payload/hello_world', command: DART_SDK.PUB})); - -gulp.task('!pubbuild.payload.dart', - pubbuild.single(gulp, gulpPlugins, - {command: DART_SDK.PUB, src: 'modules_dart/payload/hello_world'})); - -gulp.task('!checkAndReport.payload.dart', function() { - var reportSize = require('./tools/analytics/reportsize'); - return reportSize('modules_dart/payload/hello_world/build/web/*.dart.js', - {failConditions: _DART_PAYLOAD_SIZE_LIMITS, prefix: 'hello_world'}); -}); - -// JS payload size tracking -gulp.task('test.payload.js/ci', function(done) { - runSequence('build.payload.js', '!checkAndReport.payload.js', sequenceComplete(done)); -}); - -gulp.task('build.payload.js', ['build.js'], function(done) { - runSequence('!build.payload.js.webpack', '!build.payload.js.systemjs', sequenceComplete(done)); -}); - -gulp.task('!build.payload.js.webpack', function() { - var webpack = require('./tools/build/webpack/promiseify'); - - var ES5_PROD_ROOT = __dirname + '/' + CONFIG.dest.js.prod.es5; - - return Promise.all(PAYLOAD_TESTS_CONFIG.ts.cases.map(function(caseName) { - var CASE_PATH = PAYLOAD_TESTS_CONFIG.ts.dist(caseName, 'webpack'); - - return webpack({ - // bundle app + framework - entry: CASE_PATH + '/index.js', - output: {path: CASE_PATH, filename: "app-bundle.js"}, - resolve: { - extensions: ['', '.js'], - packageAlias: '', // option added to ignore "broken" package.json in our dist folder - root: [ES5_PROD_ROOT] - } - }) - .then(function() { // pad bundle with mandatory dependencies - return new Promise(function(resolve, reject) { - gulp.src([ - 'node_modules/zone.js/dist/zone.js', - 'node_modules/zone.js/dist/long-stack-trace-zone.js', - 'node_modules/reflect-metadata/Reflect.js', - CASE_PATH + '/app-bundle.js' - ]) - .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) - .pipe(gulpPlugins.uglify()) - .pipe(gulp.dest(CASE_PATH)) - .on('end', resolve) - .on('error', reject); - }); - }); - })); -}); - -gulp.task('!build.payload.js.systemjs', function() { - var bundler = require('./tools/build/bundle'); - - return Promise.all(PAYLOAD_TESTS_CONFIG.ts.cases.map(function(caseName) { - var CASE_PATH = PAYLOAD_TESTS_CONFIG.ts.dist(caseName, 'systemjs'); - - return bundler - .bundle( - { - paths: {'index': CASE_PATH + '/index.js'}, - meta: {'angular2/core': {build: false}, 'angular2/platform/browser': {build: false}} - }, - 'index', CASE_PATH + '/index.register.js', {}) - .then(function() { - return new Promise(function(resolve, reject) { - gulp.src([ - 'node_modules/systemjs/dist/system.src.js', - 'dist/js/prod/es5/bundle/angular2-polyfills.js', - 'dist/js/prod/es5/bundle/angular2.js', - 'dist/js/prod/es5//rxjs/bundles/Rx.js', - CASE_PATH + '/index.register.js', - 'tools/build/systemjs/payload_tests_import.js' - ]) - .pipe(gulpPlugins.concat(PAYLOAD_TESTS_CONFIG.ts.bundleName)) - .pipe(gulpPlugins.uglify()) - .pipe(gulp.dest(CASE_PATH)) - .on('end', resolve) - .on('error', reject); - }); - }); - })); -}); - -gulp.task('!checkAndReport.payload.js', function() { - var reportSize = require('./tools/analytics/reportsize'); - - function caseSizeStream(caseName, packaging) { - return reportSize(PAYLOAD_TESTS_CONFIG.ts.dist(caseName, packaging) + '/' + - PAYLOAD_TESTS_CONFIG.ts.bundleName, - { - failConditions: PAYLOAD_TESTS_CONFIG.ts[packaging].sizeLimits, - prefix: caseName + '_' + packaging - }); - } - - return PAYLOAD_TESTS_CONFIG.ts.cases.reduce(function(sizeReportingStreams, caseName) { - sizeReportingStreams.add(caseSizeStream(caseName, 'systemjs')); - sizeReportingStreams.add(caseSizeStream(caseName, 'webpack')); - }, merge2()); -}); - -gulp.task('watch.dart.dev', function(done) { - runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!build/remove-pub-symlinks', function(error) { - var watch = require('./tools/build/watch'); - - // if initial build failed (likely due to build or formatting step) then exit - // otherwise karma server doesn't start and we can't continue running properly - if (error) { - done(error); - return; - } - - watch(['modules/angular2/**', 'modules_dart/**'], {ignoreInitial: true}, - ['!build/tree.dart', 'build/pure-packages.dart']); - }); -}); - -gulp.task('test.unit.router/ci', function(done) { - var karma = require('karma'); - - var browserConf = getBrowsersFromCLI(); - new karma.Server( - { - configFile: __dirname + '/modules/angular1_router/karma-router.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - done) - .start(); -}); - -gulp.task('test.unit.js/ci', function(done) { - var karma = require('karma'); - - var browserConf = getBrowsersFromCLI(); - new karma.Server( - { - configFile: __dirname + '/karma-js.conf.js', - singleRun: true, - reporters: ['dots'], - browsers: browserConf.browsersToRun - }, - function(err) { done(); }) - .start(); -}); - -gulp.task('test.unit.js.sauce/ci', function(done) { - var browsers = browserProvidersConf.sauceAliases.CI_REQUIRED; - if (cliArgs.mode && cliArgs.mode == 'saucelabs_optional') { - browsers = browserProvidersConf.sauceAliases.CI_OPTIONAL; - } - launchKarmaWithExternalBrowsers(['dots', 'saucelabs'], browsers, done); -}); - -gulp.task('test.unit.js.browserstack/ci', function(done) { - var browsers = browserProvidersConf.browserstackAliases.CI_REQUIRED; - if (cliArgs.mode && cliArgs.mode == 'browserstack_optional') { - browsers = browserProvidersConf.browserstackAliases.CI_OPTIONAL; - } - launchKarmaWithExternalBrowsers(['dots'], browsers, done); -}); - -gulp.task('test.unit.dart/ci', function(done) { - runSequence('test.dart.dartium_symlink', '!test.unit.dart/run/angular2', - '!test.unit.dart/run/angular2_testing', '!test.unit.dart/run/benchpress', - sequenceComplete(done)); -}); - -// At the moment, dart test requires dartium to be an executable on the path. -// Make a temporary directory and symlink dartium from there (just for this command) -// so that it can run. -// TODO(juliemr): this won't work with windows - remove the hack and make this platform agnostic. -var dartiumTmpdir = path.join(os.tmpdir(), 'dartium' + new Date().getTime().toString()); -var dartiumPathPrefix = 'PATH=$PATH:' + dartiumTmpdir + ' '; -gulp.task( - 'test.dart.dartium_symlink', - shell.task(['mkdir ' + dartiumTmpdir, 'ln -s $DARTIUM_BIN ' + dartiumTmpdir + '/dartium'])); - -gulp.task('!test.unit.dart/run/angular2', function() { - var pubtest = require('./tools/build/pubtest'); - return pubtest({ - dir: path.join(CONFIG.dest.dart, 'angular2'), - dartiumTmpdir: dartiumTmpdir, - command: DART_SDK.PUB, - files: '**/*_spec.dart', - bunchFiles: true, - useExclusiveTests: true - }); -}); - -gulp.task('!test.unit.dart/run/angular2_testing', function() { - var pubtest = require('./tools/build/pubtest'); - - return pubtest({ - dir: path.join(CONFIG.dest.dart, 'angular2_testing'), - dartiumTmpdir: dartiumTmpdir, - command: DART_SDK.PUB, - files: '**/*_test.dart', - useExclusiveTests: true - }); -}); - -gulp.task('!test.unit.dart/run/benchpress', function() { - var pubtest = require('./tools/build/pubtest'); - - return pubtest({ - dir: path.join(CONFIG.dest.dart, 'benchpress'), - dartiumTmpdir: dartiumTmpdir, - command: DART_SDK.PUB, - files: '**/*_spec.dart', - useExclusiveTests: true - }); -}); - -gulp.task('test.unit.cjs/ci', function(done) { - runJasmineTests(['dist/js/cjs/{angular2,benchpress}/test/**/*_spec.js'], done); -}); - -gulp.task('check-public-api', ['build.tools'], - function(done) { runJasmineTests(['dist/tools/public_api_guard/**/*_spec.js'], done); }); - -gulp.task('test.unit.cjs', ['build/clean.js', 'build.tools'], function(neverDone) { - var watch = require('./tools/build/watch'); - - printModulesWarning(); - treatTestErrorsAsFatal = false; - watch('modules/**', ['!build.js.cjs', 'test.unit.cjs/ci']); -}); - -// Use this target to continuously run dartvm unit-tests (such as transformer -// tests) while coding. Note: these tests do not use Karma. -gulp.task('test.unit.dartvm', function(neverDone) { - var watch = require('./tools/build/watch'); - - runSequence('build/tree.dart', 'build/pure-packages.dart', '!build/pubget.angular2.dart', - '!test.unit.dartvm/run', function(error) { - // Watch for changes made in the TS and Dart code under "modules" and - // run ts2dart and test change detector generator prior to rerunning the - // tests. - watch('modules/angular2/**', {ignoreInitial: true}, - ['!build/tree.dart', '!test.unit.dartvm/run']); - - // Watch for changes made in Dart code under "modules_dart", then copy it - // to dist and run test change detector generator prior to retunning the - // tests. - watch('modules_dart/**', {ignoreInitial: true}, - ['build/pure-packages.dart', '!test.unit.dartvm/run']); - }); -}); - -gulp.task('!test.unit.dartvm/run', - runServerDartTests(gulp, gulpPlugins, {dir: 'dist/dart/angular2'})); - - -gulp.task('test.unit.tools/ci', function(done) { - runJasmineTests(['dist/tools/**/*.spec.js', 'tools/**/*.spec.js'], done); -}); - - -gulp.task('test.unit.tools', ['build/clean.tools'], function(neverDone) { - var watch = require('./tools/build/watch'); - treatTestErrorsAsFatal = false; - - watch(['tools/**', '!tools/**/test-fixtures/**'], ['!build.tools', 'test.unit.tools/ci']); -}); - - -// ------------------ -// server tests -// These tests run on the VM on the command-line and are -// allowed to access the file system and network. -gulp.task('test.server.dart', runServerDartTests(gulp, gulpPlugins, {dest: 'dist/dart'})); - -// ----------------- -// test builders -gulp.task('test.transpiler.unittest', - function(done) { runJasmineTests(['tools/transpiler/unittest/**/*.js'], done); }); - -// ----------------- -// Pre-test checks - -gulp.task('pre-test-checks', function(done) { - runSequence('build/checkCircularDependencies', sequenceComplete(done)); -}); - -// ----------------- -// Checks which should fail the build, but should not block us running the tests. -// This task is run in a separate travis worker, so these checks provide faster -// feedback while allowing tests to execute. -gulp.task('static-checks', ['!build.tools'], function(done) { - runSequence( - // We do not run test.typings here because it requires building, which is too slow. - ['enforce-format', 'lint'], sequenceComplete(done)); -}); - - -// ----------------- -// Tests for the typings we deliver for TS users -// -// Typings are contained in individual .d.ts files produced by the compiler, -// distributed in our npm package, and loaded from node_modules by -// the typescript compiler. - -// Make sure the typings tests are isolated, by running in a tempdir -var tmpdir = path.join(os.tmpdir(), 'test.typings', new Date().getTime().toString()); -gulp.task('!pre.test.typings.layoutNodeModule', function() { - return gulp.src(['dist/js/cjs/angular2/**/*', 'node_modules/rxjs/**/*'], {base: 'dist/js/cjs'}) - .pipe(gulp.dest(path.join(tmpdir, 'node_modules'))); -}); - -gulp.task('!pre.test.typings.copyDeps', function() { - return gulp.src( - [ - 'modules/angular2/typings/angular-protractor/*.ts', - 'modules/angular2/typings/jasmine/*.ts', - 'modules/angular2/typings/selenium-webdriver/*.ts', - ], - {base: 'modules/angular2/typings'}) - .pipe(gulp.dest(tmpdir)); -}); - -gulp.task('!pre.test.typings.copyTypingsSpec', function() { - return gulp.src(['modules/angular2/examples/**/*.ts']).pipe(gulp.dest(tmpdir)); -}); - -gulp.task('!test.typings', - [ - '!pre.test.typings.layoutNodeModule', - '!pre.test.typings.copyTypingsSpec', - '!pre.test.typings.copyDeps' - ], - function() { - var tsc = require('gulp-typescript'); - - return gulp.src([tmpdir + '/**/*.ts', '!' + tmpdir + '/node_modules/**/*']) - .pipe(tsc({ - target: 'ES6', - module: 'commonjs', - experimentalDecorators: true, - noImplicitAny: true, - moduleResolution: 'node', - typescript: require('typescript') - })); - }); - -gulp.task('test.typings', ['build.js.cjs'], - function(done) { runSequence('!test.typings', sequenceComplete(done)); }); - -gulp.task('!build.compiler_cli', function(done) { runTsc('tools/compiler_cli/src', done); }); - -gulp.task('!clean.compiler_cli', function(done) { - fse.remove(path.join('dist', 'tools', 'compiler_cli', 'test'), - fse.remove(path.join('tools', 'compiler_cli', 'test', 'src', '*.ngfactory.ts'), - fse.remove(path.join('tools', 'compiler_cli', 'test', 'src', 'a', - '*.ngfactory.ts'), - done))); -}); - -gulp.task('!test.compiler_cli.codegen', function(done) { - try { - require('./dist/tools/compiler_cli/main') - .main("tools/compiler_cli/test") - .then(done) - .catch(function(rej) { done(rej); }); - } catch (err) { - done(err); - } -}); - -gulp.task('!test.compiler_cli.unit', - function(done) { runJasmineTests(['dist/tools/compiler_cli/**/*_spec.js'], done) }); - -// This task overwrites our careful tsickle-lowered Decorators with normal .js emit. -// So it should only be run after asserting on the .js file content. -gulp.task('!test.compiler_cli.verify_codegen', - function(done) { runTsc('tools/compiler_cli/test', done); }); - -// End-to-end test for compiler CLI. -// Calls the compiler using its command-line interface, then compiles the app with the codegen. -// TODO(alexeagle): wire up the playground tests with offline compilation, similar to dart. -gulp.task('test.compiler_cli', ['!build.compiler_cli'], function(done) { - runSequence('!clean.compiler_cli', '!test.compiler_cli.codegen', '!test.compiler_cli.unit', - '!test.compiler_cli.verify_codegen', sequenceComplete(done)); -}); - -// ----------------- -// orchestrated targets - -// Pure Dart packages only contain Dart code and conform to pub package layout. -// These packages need no transpilation. All code is copied over to `dist` -// unmodified and directory structure is preserved. -// -// This task is expected to be run after build/tree.dart -gulp.task('build/pure-packages.dart', function(done) { - runSequence('build/pure-packages.dart/standalone', 'build/pure-packages.dart/license', - 'build/pure-packages.dart/angular2', sequenceComplete(done)); -}); - - -gulp.task('build/pure-packages.dart/standalone', function() { - return gulp.src([ - 'modules_dart/**/*', - '!modules_dart/**/*.proto', - '!modules_dart/**/packages{,/**}', - '!modules_dart/**/.packages', - '!modules_dart/payload{,/**}', - '!modules_dart/transform{,/**}', - ]) - .pipe(gulp.dest(CONFIG.dest.dart)); -}); - -gulp.task('build/pure-packages.dart/license', function() { - return gulp.src(['LICENSE']).pipe(gulp.dest(path.join(CONFIG.dest.dart, 'angular2_testing'))); -}); - - -gulp.task('build/pure-packages.dart/angular2', function() { - return gulp.src([ - 'modules_dart/transform/**/*', - '!modules_dart/transform/**/*.proto', - '!modules_dart/transform/pubspec.yaml', - '!modules_dart/transform/**/packages{,/**}', - ]) - .pipe(gulp.dest(path.join(CONFIG.dest.dart, 'angular2'))); -}); - -// Builds all Dart packages, but does not compile them -gulp.task('build/packages.dart', function(done) { - runSequence('lint_protos.dart', 'pubget.dart', 'build/tree.dart', 'build/pure-packages.dart', - // Run after 'build/tree.dart' because broccoli clears the dist/dart folder - '!build/pubget.angular2.dart', sequenceComplete(done)); -}); - -// Builds and compiles all Dart packages -gulp.task('build.dart', function(done) { - runSequence('build/packages.dart', 'build/pubspec.dart', 'build/analyze.dart', - 'build/check.apidocs.dart', sequenceComplete(done)); -}); - - -// public task to build tools -gulp.task('build.tools', ['build/clean.tools'], - function(done) { runSequence('!build.tools', sequenceComplete(done)); }); - - -// private task to build tools -gulp.task('!build.tools', function() { - var sourcemaps = require('gulp-sourcemaps'); - var tsc = require('gulp-typescript'); - - var stream = gulp.src(['tools/**/*.ts', '!tools/compiler_cli/**']) - .pipe(sourcemaps.init()) - .pipe(tsc({ - target: 'ES5', - module: 'commonjs', - declaration: true, - noImplicitAny: true, - // Don't use the version of typescript that gulp-typescript depends on - // see https://github.com/ivogabe/gulp-typescript#typescript-version - typescript: require('typescript') - })); - stream = - merge2([stream.js.pipe(gulp.dest('dist/tools')), stream.dts.pipe(gulp.dest('dist/tools'))]) - .on('error', - function(error) { - // nodejs doesn't propagate errors from the src stream into the final - // stream so we are - // forwarding the error into the final stream - stream.emit('error', error); - }) - .pipe(sourcemaps.write('.')) - .on('end', function() { - var AngularBuilder = require('./dist/tools/broccoli/angular_builder').AngularBuilder; - angularBuilder = - new AngularBuilder({outputPath: 'dist', dartSDK: DART_SDK, logs: logs}); - }); - - return stream; -}); - -gulp.task('broccoli.js.dev', ['build.tools'], - function(done) { runSequence('!broccoli.js.dev', sequenceComplete(done)); }); - -gulp.task('!broccoli.js.dev', () => angularBuilder.rebuildBrowserDevTree({ - generateEs6: generateEs6, - projects: cliArgsProjects, - noTypeChecks: cliArgs.noTypeChecks, - useBundles: cliArgs.useBundles -})); - -gulp.task('!broccoli.js.prod', () => angularBuilder.rebuildBrowserProdTree({ - generateEs6: generateEs6, - projects: cliArgsProjects, - noTypeChecks: cliArgs.noTypeChecks, - useBundles: cliArgs.useBundles -})); - -gulp.task('build.js.dev', ['build/clean.js'], - function(done) { runSequence('broccoli.js.dev', sequenceComplete(done)); }); - -gulp.task('build.js.prod', ['build.tools'], - function(done) { runSequence('!broccoli.js.prod', sequenceComplete(done)); }); - - -/** - * public task - */ -gulp.task('build.js.cjs', ['build.tools'], - function(done) { runSequence('!build.js.cjs', sequenceComplete(done)); }); - - -var firstBuildJsCjs = true; - -/** - * private task - */ -gulp.task('!build.js.cjs', function() { - return angularBuilder.rebuildNodeTree({ - generateEs6: generateEs6, - projects: cliArgsProjects, - noTypeChecks: cliArgs.noTypeChecks, - useBundles: cliArgs.useBundles - }) - .then(function() { - if (firstBuildJsCjs) { - firstBuildJsCjs = false; - console.log('creating node_modules symlink hack'); - // linknodemodules is all sync - linknodemodules(gulp, gulpPlugins, {dir: CONFIG.dest.js.cjs})(); - } - }); -}); - - -var bundleConfig = { - paths: {"*": "dist/js/prod/es5/*.js"}, - // Files that end up empty after transpilation confuse system-builder - // and need to be explitily listed here. - // TODO: upgrade system builder and find a way to declare all input as cjs. - meta: { - 'angular2/src/router/route_definition': {format: 'cjs'}, - 'angular2/src/common/directives/observable_list_diff': {format: 'cjs'}, - 'angular2/lifecycle_hooks': {format: 'cjs'} - } -}; - -// production build -gulp.task('!bundle.js.prod', ['build.js.prod'], function() { - var bundler = require('./tools/build/bundle'); - var bundlerConfig = {sourceMaps: true}; - - return bundler.bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.js', bundlerConfig) - .then(function() { - return Promise.all([ - bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.js', bundlerConfig), - bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.js', - bundlerConfig), - bundler.bundle(bundleConfig, ALT_ROUTER_BUNDLE_CONTENT, './dist/build/alt_router.js', - bundlerConfig), - bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.js', - bundlerConfig) - ]); - }); -}); - -// minified production build -gulp.task('!bundle.js.min', ['build.js.prod'], function() { - var bundler = require('./tools/build/bundle'); - var bundlerConfig = - {sourceMaps: true, minify: true, mangle: false, uglify: {compress: {keep_fnames: true}}}; - - return bundler.bundle(bundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.min.js', - bundlerConfig) - .then(function() { - return Promise.all([ - bundler.bundle(bundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.min.js', - bundlerConfig), - bundler.bundle(bundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.min.js', - bundlerConfig), - bundler.bundle(bundleConfig, ALT_ROUTER_BUNDLE_CONTENT, './dist/build/alt_router.min.js', - bundlerConfig), - bundler.bundle(bundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.min.js', - bundlerConfig) - ]); - }); -}); - -// development build -gulp.task('!bundle.js.dev', ['build.js.dev'], function() { - var bundler = require('./tools/build/bundle'); - var bundlerConfig = {sourceMaps: true}; - - var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - - return bundler.bundle(devBundleConfig, NG2_BUNDLE_CONTENT, './dist/build/angular2.dev.js', - bundlerConfig) - .then(function() { - return Promise.all([ - bundler.bundle(devBundleConfig, HTTP_BUNDLE_CONTENT, './dist/build/http.dev.js', - bundlerConfig), - bundler.bundle(devBundleConfig, ROUTER_BUNDLE_CONTENT, './dist/build/router.dev.js', - bundlerConfig), - bundler.bundle(devBundleConfig, ALT_ROUTER_BUNDLE_CONTENT, - './dist/build/alt_router.dev.js', bundlerConfig), - bundler.bundle(devBundleConfig, UPGRADE_BUNDLE_CONTENT, './dist/build/upgrade.dev.js', - bundlerConfig) - ]); - }); -}); - -// WebWorker build -gulp.task("!bundle.web_worker.js.dev", ["build.js.dev"], function() { - var bundler = require('./tools/build/bundle'); - var devBundleConfig = merge(true, bundleConfig); - - devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - - return bundler.bundle(devBundleConfig, 'angular2/web_worker/ui', - './dist/build/web_worker/ui.dev.js', {sourceMaps: true}) - .then(function() { - return bundler.bundle(devBundleConfig, 'angular2/web_worker/worker', - './dist/build/web_worker/worker.dev.js', {sourceMaps: true}); - }); -}); - -gulp.task('!bundle.testing', ['build.js.dev'], function() { - var bundler = require('./tools/build/bundle'); - - var devBundleConfig = merge(true, bundleConfig); - devBundleConfig.paths = merge(true, devBundleConfig.paths, {"*": "dist/js/dev/es5/*.js"}); - - return bundler.bundle(devBundleConfig, TESTING_BUNDLE_CONTENT, './dist/js/bundle/testing.dev.js', - {sourceMaps: true}); -}); - -gulp.task('!bundles.js.docs', ['clean'], function() { - return gulp.src('modules/angular2/docs/bundles/*').pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundles.js.umd', ['build.js.dev'], function() { - var webpack = require('./tools/build/webpack/promiseify'); - - function resolveOptions(devOrProd) { - return { - root: __dirname + '/dist/js/' + devOrProd + '/es5', - packageAlias: '' // this option is added to ignore "broken" package.json in our dist folder - }; - } - - function outputOptions(outFileName, devOrProd) { - return { - filename: - 'dist/js/bundle/' + outFileName + '.umd' + (devOrProd === 'dev' ? '.dev' : '') + '.js', - library: 'ng', - libraryTarget: 'umd' - }; - } - - function webPackConf(entryPoints, outFileName, devOrProd) { - return { - entry: entryPoints, - resolve: resolveOptions(devOrProd), - module: {preLoaders: [{test: /\.js$/, loader: 'source-map-loader'}]}, - devtool: devOrProd === 'dev' ? 'inline-source-map' : undefined, - output: outputOptions(outFileName, devOrProd), - externals: { - 'rxjs/Observable': 'umd Rx', - 'rxjs/Subject': 'umd Rx', - 'rxjs/subject/ReplaySubject': { - commonjs: 'rxjs/subject/ReplaySubject', - commonjs2: 'rxjs/subject/ReplaySubject', - amd: 'rxjs/subject/ReplaySubject', - root: ['Rx'] - }, - 'rxjs/operator/take': { - commonjs: 'rxjs/operator/take', - commonjs2: 'rxjs/operator/take', - amd: 'rxjs/operator/take', - root: ['Rx', 'Observable', 'prototype'] - }, - 'rxjs/observable/fromPromise': { - commonjs: 'rxjs/observable/fromPromise', - commonjs2: 'rxjs/observable/fromPromise', - amd: 'rxjs/observable/fromPromise', - root: ['Rx', 'Observable'] - }, - 'rxjs/operator/toPromise': { - commonjs: 'rxjs/operator/toPromise', - commonjs2: 'rxjs/operator/toPromise', - amd: 'rxjs/operator/toPromise', - root: ['Rx', 'Observable', 'prototype'] - } - } - }; - } - - return Promise.all([ - webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', - 'dev')), - webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all.umd.js'], 'angular2-all', - 'prod')), - webpack(webPackConf([__dirname + '/tools/build/webpack/angular2-all-testing.umd.js'], - 'angular2-all-testing', 'dev')) - ]); -}); - -gulp.task('bundles.js.umd.min', ['!bundles.js.umd', '!bundle.ng.polyfills'], function() { - var rename = require('gulp-rename'); - var uglify = require('gulp-uglify'); - - // minify production bundles - return gulp.src(['dist/js/bundle/angular2-polyfills.js', 'dist/js/bundle/angular2-all.umd.js']) - .pipe(uglify()) - .pipe(rename({extname: '.min.js'})) - .pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundle.js.prod.deps', ['!bundle.js.prod'], function() { - var bundler = require('./tools/build/bundle'); - - return merge2(bundler.modify(['dist/build/angular2.js'], 'angular2.js'), - bundler.modify(['dist/build/http.js'], 'http.js'), - bundler.modify(['dist/build/router.js'], 'router.js'), - bundler.modify(['dist/build/alt_router.js'], 'alt_router.js'), - bundler.modify(['dist/build/upgrade.js'], 'upgrade.js')) - .pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundle.js.min.deps', ['!bundle.js.min'], function() { - var bundler = require('./tools/build/bundle'); - var uglify = require('gulp-uglify'); - - return merge2(bundler.modify(['dist/build/angular2.min.js'], 'angular2.min.js'), - bundler.modify(['dist/build/http.min.js'], 'http.min.js'), - bundler.modify(['dist/build/router.min.js'], 'router.min.js'), - bundler.modify(['dist/build/alt_router.min.js'], 'alt_router.min.js'), - bundler.modify(['dist/build/upgrade.min.js'], 'upgrade.min.js')) - .pipe(uglify()) - .pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundle.ng.polyfills', ['clean'], - function() { return addDevDependencies('angular2-polyfills.js'); }); - -var JS_DEV_DEPS = [ - licenseWrap('node_modules/zone.js/LICENSE', true), - 'node_modules/zone.js/dist/zone.js', - 'node_modules/zone.js/dist/long-stack-trace-zone.js', - licenseWrap('node_modules/reflect-metadata/LICENSE', true), - 'node_modules/reflect-metadata/Reflect.js' -]; - - -function addDevDependencies(outputFile) { - var bundler = require('./tools/build/bundle'); - var insert = require('gulp-insert'); - - return bundler.modify(JS_DEV_DEPS.concat(['dist/build/' + outputFile]), outputFile) - .pipe(gulp.dest('dist/js/bundle')); -} - -gulp.task('!bundle.js.dev.deps', ['!bundle.js.dev'], function() { - var bundler = require('./tools/build/bundle'); - - return merge2(bundler.modify(['dist/build/angular2.dev.js'], 'angular2.dev.js'), - bundler.modify(['dist/build/http.dev.js'], 'http.dev.js'), - bundler.modify(['dist/build/router.dev.js'], 'router.dev.js'), - bundler.modify(['dist/build/alt_router.dev.js'], 'alt_router.dev.js'), - bundler.modify(['dist/build/upgrade.dev.js'], 'upgrade.dev.js')) - .pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundle.web_worker.js.dev.deps', ['!bundle.web_worker.js.dev'], function() { - var bundler = require('./tools/build/bundle'); - return merge2(bundler.modify(['dist/build/web_worker/ui.dev.js'], "web_worker/ui.dev.js"), - bundler.modify(['dist/build/web_worker/worker.dev.js'], "web_worker/worker.dev.js")) - .pipe(gulp.dest('dist/js/bundle')); -}); - -gulp.task('!bundle.copy', function() { - return merge2(gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/prod/es5/bundle')), - gulp.src('dist/js/bundle/**').pipe(gulp.dest('dist/js/dev/es5/bundle'))); -}); - -gulp.task('!bundles.js.checksize', function(done) { - var reportSize = require('./tools/analytics/reportsize'); - return reportSize('dist/js/bundle/**/*.js', {printToConsole: ['gzip level=2']}); -}); - -gulp.task('bundles.js', - [ - '!bundle.js.prod.deps', - '!bundle.js.dev.deps', - '!bundle.js.min.deps', - '!bundle.web_worker.js.dev.deps', - 'bundles.js.umd.min', - '!bundle.testing', - '!bundle.ng.polyfills', - '!bundles.js.docs' - ], - function(done) { runSequence('!bundle.copy', '!bundles.js.checksize', done); }); - -gulp.task('build.js', - ['build.js.dev', 'build.js.prod', 'build.js.cjs', 'bundles.js', 'benchpress.bundle']); - -gulp.task('clean', [ - 'build/clean.tools', - 'build/clean.js', - 'build/clean.dart', - 'build/clean.docs', - 'build/clean.bundles' -]); - -gulp.task('build', ['build.js', 'build.dart']); - -// ------------ -// transform codegen -gulp.task('lint_protos.dart', function(done) { - var proto = require('./tools/build/proto'); - - return proto.lint({dir: 'modules_dart/transform/lib/src/transform/common/model/'}, done); -}); - -gulp.task('gen_protos.dart', function(done) { - var proto = require('./tools/build/proto'); - - return proto.generate( - { - dir: 'modules_dart/transform/lib/src/transform/common/model/', - plugin: 'tools/build/protoc-gen-dart' - }, - done); -}); - -// ------------ - -gulp.task('cleanup.builder', function() { return angularBuilder.cleanup(); }); - -gulp.task('benchpress.bundle', ['build/clean.bundles.benchpress', 'build.js.cjs'], function(cb) { - var bundler = require('./tools/build/bundle'); - - bundler.benchpressBundle(BENCHPRESS_BUNDLE_CONFIG.entries, BENCHPRESS_BUNDLE_CONFIG.packageJson, - BENCHPRESS_BUNDLE_CONFIG.includes, BENCHPRESS_BUNDLE_CONFIG.excludes, - BENCHPRESS_BUNDLE_CONFIG.ignore, BENCHPRESS_BUNDLE_CONFIG.dest, cb); -}); - - -// register cleanup listener for ctrl+c/kill used to quit any persistent task (autotest or serve -// tasks) -process.on('SIGINT', function() { - if (!angularBuilder.uninitialized) { - runSequence('cleanup.builder', function() { process.exit(); }); - } else { - process.exit(); - } -}); - - -// register cleanup listener for all non-persistent tasks -var beforeExitRan = false; - -process.on('beforeExit', function() { - if (beforeExitRan) return; - - beforeExitRan = true; - - if (!angularBuilder.uninitialized) { - gulp.start('cleanup.builder'); - } -}); - - -var firstTask = true; - - - -gulp.on('task_start', (e) => { - if (firstTask) { - firstTask = false; - analytics.buildSuccess('gulp ', process.uptime() * 1000); - } - - analytics.buildStart('gulp ' + e.task); -}); -gulp.on('task_stop', (e) => { analytics.buildSuccess('gulp ' + e.task, e.duration * 1000); }); -gulp.on('task_err', (e) => { analytics.buildError('gulp ' + e.task, e.duration * 1000); }); diff --git a/modules/@angular/README.dart.md b/modules/@angular/README.dart.md deleted file mode 100644 index 35cead7711..0000000000 --- a/modules/@angular/README.dart.md +++ /dev/null @@ -1,6 +0,0 @@ -Angular2 -========= - -The sources for this package are in the main [Angular2](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo. This is the repository for the upcoming 2.0 version. If you're looking for the current official version of Angular you should go to [angular/angular.js](https://github.com/angular/angular.js) - -License: Apache MIT 2.0 diff --git a/modules/@angular/common/common.dart b/modules/@angular/common/common.dart deleted file mode 100644 index 1592d948a1..0000000000 --- a/modules/@angular/common/common.dart +++ /dev/null @@ -1 +0,0 @@ -export 'index.dart'; diff --git a/modules/@angular/common/src/directives/observable_list_diff.dart b/modules/@angular/common/src/directives/observable_list_diff.dart deleted file mode 100644 index eb3e929532..0000000000 --- a/modules/@angular/common/src/directives/observable_list_diff.dart +++ /dev/null @@ -1,63 +0,0 @@ -library angular2.directives.observable_list_iterable_diff; - -import 'package:observe/observe.dart' show ObservableList; -import 'package:angular2/core.dart'; -import 'package:angular2/src/core/change_detection/differs/default_iterable_differ.dart'; -import 'dart:async'; - -class ObservableListDiff extends DefaultIterableDiffer { - ChangeDetectorRef _ref; - ObservableListDiff(this._ref); - - bool _updated = true; - ObservableList _collection; - StreamSubscription _subscription; - - onDestroy() { - if (this._subscription != null) { - this._subscription.cancel(); - this._subscription = null; - this._collection = null; - } - } - - DefaultIterableDiffer diff(ObservableList collection) { - if (collection is! ObservableList) { - throw "Cannot change the type of a collection"; - } - - // A new collection instance is passed in. - // - We need to set up a listener. - // - We need to diff collection. - if (!identical(_collection, collection)) { - _collection = collection; - - if (_subscription != null) _subscription.cancel(); - _subscription = collection.changes.listen((_) { - _updated = true; - _ref.markForCheck(); - }); - _updated = false; - return super.diff(collection); - - // An update has been registered since the last change detection check. - // - We reset the flag. - // - We diff the collection. - } else if (_updated) { - _updated = false; - return super.diff(collection); - - // No updates has been registered. - } else { - return null; - } - } -} - -class ObservableListDiffFactory implements IterableDifferFactory { - const ObservableListDiffFactory(); - bool supports(obj) => obj is ObservableList; - IterableDiffer create(ChangeDetectorRef cdRef, [Function trackByFn]) { - return new ObservableListDiff(cdRef); - } -} diff --git a/modules/@angular/common/src/forms-deprecated/directives/normalize_validator.dart b/modules/@angular/common/src/forms-deprecated/directives/normalize_validator.dart deleted file mode 100644 index 510abb3001..0000000000 --- a/modules/@angular/common/src/forms-deprecated/directives/normalize_validator.dart +++ /dev/null @@ -1,20 +0,0 @@ -library angular2.core.forms.normalize_validators; - -import 'package:angular2/src/common/forms/directives/validators.dart' show Validator; - -Function normalizeValidator(dynamic validator){ - if (validator is Validator) { - return (c) => validator.validate(c); - } else { - return validator; - } -} - - -Function normalizeAsyncValidator(dynamic validator){ - if (validator is Validator) { - return (c) => validator.validate(c); - } else { - return validator; - } -} diff --git a/modules/@angular/common/src/pipes/date_pipe.ts b/modules/@angular/common/src/pipes/date_pipe.ts index 421226e909..bac0f10875 100644 --- a/modules/@angular/common/src/pipes/date_pipe.ts +++ b/modules/@angular/common/src/pipes/date_pipe.ts @@ -51,9 +51,6 @@ var defaultLocale: string = 'en-US'; * * In javascript, only the components specified will be respected (not the ordering, * punctuations, ...) and details of the formatting will be dependent on the locale. - * On the other hand in Dart version, you can also include quoted text as well as some extra - * date/time components such as quarter. For more information see: - * https://www.dartdocs.org/documentation/intl/0.13.0/intl/DateFormat-class.html * * `format` can also be one of the following predefined formats: * diff --git a/modules/@angular/common/test/directives/observable_list_diff_spec.dart b/modules/@angular/common/test/directives/observable_list_diff_spec.dart deleted file mode 100644 index b6c4104087..0000000000 --- a/modules/@angular/common/test/directives/observable_list_diff_spec.dart +++ /dev/null @@ -1,102 +0,0 @@ -library angular2.test.directives.observable_list_iterable_diff_spec; - -import 'package:angular2/testing_internal.dart'; -import 'package:observe/observe.dart' show ObservableList; -import 'package:angular2/core.dart' show ChangeDetectorRef; -import 'package:angular2/common.dart' show ObservableListDiffFactory; - -@proxy -class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef {} - -main() { - describe('ObservableListDiff', () { - var factory, changeDetectorRef; - - beforeEach(() { - factory = const ObservableListDiffFactory(); - changeDetectorRef = new SpyChangeDetectorRef(); - }); - - describe("supports", () { - it("should be true for ObservableList", () { - expect(factory.supports(new ObservableList())).toBe(true); - }); - - it("should be false otherwise", () { - expect(factory.supports([1, 2, 3])).toBe(false); - }); - }); - - it("should return itself when called the first time", () { - final d = factory.create(changeDetectorRef); - final c = new ObservableList.from([1, 2]); - expect(d.diff(c)).toBe(d); - }); - - it("should return itself when no changes between the calls", () { - final d = factory.create(changeDetectorRef); - - final c = new ObservableList.from([1, 2]); - - d.diff(c); - - expect(d.diff(c)).toBe(null); - }); - - it("should return the wrapped value once a change has been triggered", - fakeAsync(() { - final d = factory.create(changeDetectorRef); - - final c = new ObservableList.from([1, 2]); - - d.diff(c); - - c.add(3); - - // same value, because we have not detected the change yet - expect(d.diff(c)).toBe(null); - - // now we detect the change - flushMicrotasks(); - expect(d.diff(c)).toBe(d); - })); - - it("should request a change detection check upon receiving a change", - fakeAsync(() { - final d = factory.create(changeDetectorRef); - - final c = new ObservableList.from([1, 2]); - d.diff(c); - - c.add(3); - flushMicrotasks(); - - expect(changeDetectorRef.spy("markForCheck")).toHaveBeenCalledOnce(); - })); - - it("should return the wrapped value after changing a collection", () { - final d = factory.create(changeDetectorRef); - - final c1 = new ObservableList.from([1, 2]); - final c2 = new ObservableList.from([3, 4]); - - expect(d.diff(c1)).toBe(d); - expect(d.diff(c2)).toBe(d); - }); - - it("should not unbsubscribe from the stream of chagnes after changing a collection", - () { - final d = factory.create(changeDetectorRef); - - final c1 = new ObservableList.from([1, 2]); - expect(d.diff(c1)).toBe(d); - - final c2 = new ObservableList.from([3, 4]); - expect(d.diff(c2)).toBe(d); - - // pushing into the first collection has no effect, and we do not see the change - c1.add(3); - expect(d.diff(c2)).toBe(null); - }); - }); -} diff --git a/modules/@angular/common/test/spies.dart b/modules/@angular/common/test/spies.dart deleted file mode 100644 index 6c94ca2246..0000000000 --- a/modules/@angular/common/test/spies.dart +++ /dev/null @@ -1,14 +0,0 @@ -library core.spies; - -import 'package:angular2/common.dart'; -import 'package:angular2/src/core/change_detection/change_detection.dart'; -import 'package:angular2/testing_internal.dart'; - -@proxy -class SpyNgControl extends SpyObject implements NgControl {} - -@proxy -class SpyValueAccessor extends SpyObject implements ControlValueAccessor {} - -@proxy -class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef {} diff --git a/modules/@angular/compiler/core_private.dart b/modules/@angular/compiler/core_private.dart deleted file mode 100644 index 309077433f..0000000000 --- a/modules/@angular/compiler/core_private.dart +++ /dev/null @@ -1 +0,0 @@ -export '../core/private_export.dart'; diff --git a/modules/@angular/compiler/private_export.dart b/modules/@angular/compiler/private_export.dart deleted file mode 100644 index 34220bb3e4..0000000000 --- a/modules/@angular/compiler/private_export.dart +++ /dev/null @@ -1 +0,0 @@ -export './src/core/change_detection/constants.dart' show SelectorMatcher, CssSelector; diff --git a/modules/@angular/compiler/src/assertions.dart b/modules/@angular/compiler/src/assertions.dart deleted file mode 100644 index 243292ea57..0000000000 --- a/modules/@angular/compiler/src/assertions.dart +++ /dev/null @@ -1,3 +0,0 @@ -library angular2.core.util.asserions; - -void assertArrayOfStrings(String identifier, Object value) {} diff --git a/modules/@angular/compiler/src/url_resolver.dart b/modules/@angular/compiler/src/url_resolver.dart deleted file mode 100644 index 7c18a7e93b..0000000000 --- a/modules/@angular/compiler/src/url_resolver.dart +++ /dev/null @@ -1,69 +0,0 @@ -library angular2.src.services.url_resolver; - -import 'package:angular2/src/core/di.dart' show Injectable, Inject, Provider; -import 'package:angular2/src/facade/lang.dart' show isPresent, StringWrapper; -import 'package:angular2/src/core/application_tokens.dart' show PACKAGE_ROOT_URL; - -const _ASSET_SCHEME = 'asset:'; - -UrlResolver createUrlResolverWithoutPackagePrefix() { - return new UrlResolver.withUrlPrefix(null); -} - -UrlResolver createOfflineCompileUrlResolver() { - return new UrlResolver.withUrlPrefix(_ASSET_SCHEME); -} - -const DEFAULT_PACKAGE_URL_PROVIDER = const Provider(PACKAGE_ROOT_URL, useValue: "/packages"); - -@Injectable() -class UrlResolver { - /// This will be the location where 'package:' Urls will resolve. Default is - /// '/packages' - final String _packagePrefix; - - UrlResolver([@Inject(PACKAGE_ROOT_URL) this._packagePrefix]); - - /// Creates a UrlResolver that will resolve 'package:' Urls to a different - /// prefixed location. - const UrlResolver.withUrlPrefix(this._packagePrefix); - - /** - * Resolves the `url` given the `baseUrl`: - * - when the `url` is null, the `baseUrl` is returned, - * - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of - * `baseUrl` and `url`, - * - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is - * returned as is (ignoring the `baseUrl`) - * - * @param {string} baseUrl - * @param {string} url - * @returns {string} the resolved URL - */ - String resolve(String baseUrl, String url) { - Uri uri = Uri.parse(url); - - if (isPresent(baseUrl) && baseUrl.length > 0) { - Uri baseUri = Uri.parse(baseUrl); - uri = baseUri.resolveUri(uri); - } - - var prefix = this._packagePrefix; - if (prefix != null && uri.scheme == 'package') { - if (prefix == _ASSET_SCHEME) { - var pathSegments = uri.pathSegments.toList()..insert(1, 'lib'); - return new Uri(scheme: 'asset', pathSegments: pathSegments).toString(); - } else { - prefix = StringWrapper.stripRight(prefix, '/'); - var path = StringWrapper.stripLeft(uri.path, '/'); - return '$prefix/$path'; - } - } else { - return uri.toString(); - } - } -} - -String getUrlScheme(String url) { - return Uri.parse(url).scheme; -} diff --git a/modules/@angular/compiler/test/directive_lifecycle_spec.dart b/modules/@angular/compiler/test/directive_lifecycle_spec.dart deleted file mode 100644 index e9cd687c2a..0000000000 --- a/modules/@angular/compiler/test/directive_lifecycle_spec.dart +++ /dev/null @@ -1,148 +0,0 @@ -library angular2.test.core.compiler.directive_lifecycle_spec; - -import 'package:angular2/testing_internal.dart'; -import 'package:angular2/src/compiler/directive_lifecycle_reflector.dart'; -import 'package:angular2/src/core/metadata/lifecycle_hooks.dart'; - -main() { - describe('Create DirectiveMetadata', () { - describe('lifecycle', () { - describe("ngOnChanges", () { - it("should be true when the directive has the ngOnChanges method", () { - expect(hasLifecycleHook( - LifecycleHooks.OnChanges, DirectiveImplementingOnChanges)) - .toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook(LifecycleHooks.OnChanges, DirectiveNoHooks)) - .toBe(false); - }); - }); - - describe("ngOnDestroy", () { - it("should be true when the directive has the ngOnDestroy method", () { - expect(hasLifecycleHook( - LifecycleHooks.OnDestroy, DirectiveImplementingOnDestroy)) - .toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook(LifecycleHooks.OnDestroy, DirectiveNoHooks)) - .toBe(false); - }); - }); - - describe("ngOnInit", () { - it("should be true when the directive has the ngOnInit method", () { - expect(hasLifecycleHook( - LifecycleHooks.OnInit, DirectiveImplementingOnInit)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook(LifecycleHooks.OnInit, DirectiveNoHooks)) - .toBe(false); - }); - }); - - describe("ngDoCheck", () { - it("should be true when the directive has the ngDoCheck method", () { - expect(hasLifecycleHook( - LifecycleHooks.DoCheck, DirectiveImplementingOnCheck)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook(LifecycleHooks.DoCheck, DirectiveNoHooks)) - .toBe(false); - }); - }); - - describe("ngAfterContentInit", () { - it("should be true when the directive has the ngAfterContentInit method", - () { - expect(hasLifecycleHook(LifecycleHooks.AfterContentInit, - DirectiveImplementingAfterContentInit)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook( - LifecycleHooks.AfterContentInit, DirectiveNoHooks)).toBe(false); - }); - }); - - describe("ngAfterContentChecked", () { - it("should be true when the directive has the ngAfterContentChecked method", - () { - expect(hasLifecycleHook(LifecycleHooks.AfterContentChecked, - DirectiveImplementingAfterContentChecked)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook( - LifecycleHooks.AfterContentChecked, DirectiveNoHooks)) - .toBe(false); - }); - }); - - describe("ngAfterViewInit", () { - it("should be true when the directive has the ngAfterViewInit method", - () { - expect(hasLifecycleHook(LifecycleHooks.AfterViewInit, - DirectiveImplementingAfterViewInit)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook( - LifecycleHooks.AfterViewInit, DirectiveNoHooks)).toBe(false); - }); - }); - - describe("ngAfterViewChecked", () { - it("should be true when the directive has the ngAfterViewChecked method", - () { - expect(hasLifecycleHook(LifecycleHooks.AfterViewChecked, - DirectiveImplementingAfterViewChecked)).toBe(true); - }); - - it("should be false otherwise", () { - expect(hasLifecycleHook( - LifecycleHooks.AfterViewChecked, DirectiveNoHooks)).toBe(false); - }); - }); - }); - }); -} - -class DirectiveNoHooks {} - -class DirectiveImplementingOnChanges implements OnChanges { - ngOnChanges(_) {} -} - -class DirectiveImplementingOnCheck implements DoCheck { - ngDoCheck() {} -} - -class DirectiveImplementingOnInit implements OnInit { - ngOnInit() {} -} - -class DirectiveImplementingOnDestroy implements OnDestroy { - ngOnDestroy() {} -} - -class DirectiveImplementingAfterContentInit implements AfterContentInit { - ngAfterContentInit() {} -} - -class DirectiveImplementingAfterContentChecked implements AfterContentChecked { - ngAfterContentChecked() {} -} - -class DirectiveImplementingAfterViewInit implements AfterViewInit { - ngAfterViewInit() {} -} - -class DirectiveImplementingAfterViewChecked implements AfterViewChecked { - ngAfterViewChecked() {} -} diff --git a/modules/@angular/compiler/test/metadata_resolver_fixture.dart b/modules/@angular/compiler/test/metadata_resolver_fixture.dart deleted file mode 100644 index bfc85acaee..0000000000 --- a/modules/@angular/compiler/test/metadata_resolver_fixture.dart +++ /dev/null @@ -1,9 +0,0 @@ -library angular2.test.compiler.metadata_resolver_fixture; - -import "package:angular2/core.dart" show Component; - -// This component is not actually malformed; this fixture is here to -// make Dart not complain about a missing import for a test case that only -// matters in an JavaScript app. -@Component(template: "") -class MalformedStylesComponent {} diff --git a/modules/@angular/compiler/test/schema/schema_extractor.dart b/modules/@angular/compiler/test/schema/schema_extractor.dart deleted file mode 100644 index 07a47a3b89..0000000000 --- a/modules/@angular/compiler/test/schema/schema_extractor.dart +++ /dev/null @@ -1,5 +0,0 @@ -/** - * We don't know how to extract schema in dart, so do nothing. - */ -extractSchema(fn(List descriptors)) { -} diff --git a/modules/@angular/compiler/test/spies.dart b/modules/@angular/compiler/test/spies.dart deleted file mode 100644 index 45ed599dfc..0000000000 --- a/modules/@angular/compiler/test/spies.dart +++ /dev/null @@ -1,7 +0,0 @@ -library compiler.spies; - -import 'package:angular2/src/compiler/xhr.dart'; -import 'package:angular2/testing_internal.dart'; - -@proxy -class SpyXHR extends SpyObject implements XHR {} diff --git a/modules/@angular/core/core.dart b/modules/@angular/core/core.dart deleted file mode 100644 index 53f11e47a1..0000000000 --- a/modules/@angular/core/core.dart +++ /dev/null @@ -1,26 +0,0 @@ -library angular2.core; - -export './src/core/angular_entrypoint.dart' show AngularEntrypoint; -export './src/core/metadata.dart'; -export './src/core/util.dart'; -export './src/core/di.dart' hide ForwardRefFn, resolveForwardRef, forwardRef; -export './src/facade/facade.dart'; -export './src/core/application_ref.dart' show createPlatform, assertPlatform, - disposePlatform, getPlatform, - coreLoadAndBootstrap, coreBootstrap, PlatformRef, ApplicationRef; -export './src/core/application_tokens.dart' show APP_ID, - APP_INITIALIZER, - PACKAGE_ROOT_URL, - PLATFORM_INITIALIZER; -export './src/core/zone.dart'; -export './src/core/render.dart'; -export './src/core/linker.dart'; -export './src/core/debug/debug_node.dart' show DebugElement, - DebugNode, - asNativeElements; -export './src/core/testability/testability.dart'; -export './src/core/change_detection.dart'; -export './src/core/platform_directives_and_pipes.dart'; -export './src/core/platform_common_providers.dart'; -export './src/core/application_common_providers.dart'; -export './src/core/reflection/reflection.dart'; diff --git a/modules/@angular/core/private_export.dart b/modules/@angular/core/private_export.dart deleted file mode 100644 index 81eda5e022..0000000000 --- a/modules/@angular/core/private_export.dart +++ /dev/null @@ -1,17 +0,0 @@ -export './src/core/change_detection/constants.dart' show isDefaultChangeDetectionStrategy, CHANGE_DETECTION_STRATEGY_VALUES; -export './src/core/di/reflective_provider.dart' show constructDependencies; -export './src/core/metadata/lifecycle_hooks.dart' show LifecycleHooks, LIFECYCLE_HOOKS_VALUES; -export './src/core/reflection/reflector_reader.dart' show ReflectorReader; -export './src/core/linker/component_resolver.dart' show ReflectorComponentResolver; -export './src/core/linker/element.dart' show AppElement; -export './src/core/linker/view.dart' show AppView; -export './src/core/linker/view_type.dart' show ViewType; -export './src/core/linker/view_utils.dart' show MAX_INTERPOLATION_VALUES, checkBinding, flattenNestedViewRenderNodes, interpolate, ViewUtils; -export './src/core/metadata/view.dart' show VIEW_ENCAPSULATION_VALUES; -export './src/core/linker/debug_context.dart' show DebugContext, StaticNodeDebugInfo; -export './src/core/change_detection/change_detection_util.dart' show devModeEqual, uninitialized, ValueUnwrapper; -export './src/core/render/api.dart' show RenderDebugInfo; -export './src/core/linker/template_ref.dart' show TemplateRef_; -export './src/core/profile/wtf_init.dart' show wtfInit; -export './src/core/reflection/reflection_capabilities.dart' show ReflectionCapabilities; -export './src/util/decorators' show makeDecorator; diff --git a/modules/@angular/core/src/change_detection/pipe_transform.dart b/modules/@angular/core/src/change_detection/pipe_transform.dart deleted file mode 100644 index cc3abbd0da..0000000000 --- a/modules/@angular/core/src/change_detection/pipe_transform.dart +++ /dev/null @@ -1,33 +0,0 @@ -/** - * To create a Pipe, you must implement this interface. - * - * Angular invokes the `transform` method with the value of a binding - * as the first argument, and any parameters as the second argument in list form. - * - * ## Syntax - * - * `value | pipeName[:arg0[:arg1...]]` - * - * ### Example ([live demo](http://plnkr.co/edit/f5oyIked9M2cKzvZNKHV?p=preview)) - * - * The `RepeatPipe` below repeats the value as many times as indicated by the first argument: - * - * ``` - * import {Pipe, PipeTransform} from 'angular2/core'; - * - * @Pipe({name: 'repeat'}) - * export class RepeatPipe implements PipeTransform { - * transform(value: any, times: number) { - * return value.repeat(times); - * } - * } - * ``` - * - * Invoking `{{ 'ok' | repeat:3 }}` in a template produces `okokok`. - * - */ -abstract class PipeTransform { - // Note: Dart does not support varargs, - // so we can't type the `transform` method... - // dynamic transform(dynamic value, List ...args): any; -} diff --git a/modules/@angular/core/src/di/decorators.dart b/modules/@angular/core/src/di/decorators.dart deleted file mode 100644 index 261f4a86c6..0000000000 --- a/modules/@angular/core/src/di/decorators.dart +++ /dev/null @@ -1,52 +0,0 @@ -library angular2.di.decorators; - -import 'metadata.dart'; -export 'metadata.dart'; - -/** - * {@link InjectMetadata}. - * @stable - */ -class Inject extends InjectMetadata { - const Inject(dynamic token) : super(token); -} - -/** - * {@link OptionalMetadata}. - * @stable - */ -class Optional extends OptionalMetadata { - const Optional() : super(); -} - -/** - * {@link InjectableMetadata}. - * @stable - */ -class Injectable extends InjectableMetadata { - const Injectable() : super(); -} - -/** - * {@link SelfMetadata}. - * @stable - */ -class Self extends SelfMetadata { - const Self() : super(); -} - -/** - * {@link HostMetadata}. - * @stable - */ -class Host extends HostMetadata { - const Host() : super(); -} - -/** - * {@link SkipSelfMetadata}. - * @stable - */ -class SkipSelf extends SkipSelfMetadata { - const SkipSelf() : super(); -} diff --git a/modules/@angular/core/src/di/forward_ref.dart b/modules/@angular/core/src/di/forward_ref.dart deleted file mode 100644 index 6f8096b68b..0000000000 --- a/modules/@angular/core/src/di/forward_ref.dart +++ /dev/null @@ -1,15 +0,0 @@ -library angular2.di.forward_ref; - -typedef dynamic ForwardRefFn(); - -/** - * Dart does not have the forward ref problem, so this function is a noop. - */ -forwardRef(ForwardRefFn forwardRefFn) => forwardRefFn(); - -/** - * Lazily retrieve the reference value. - * - * See: {@link forwardRef} - */ -resolveForwardRef(type) => type; diff --git a/modules/@angular/core/src/di/provider_util.dart b/modules/@angular/core/src/di/provider_util.dart deleted file mode 100644 index 9b83032815..0000000000 --- a/modules/@angular/core/src/di/provider_util.dart +++ /dev/null @@ -1,20 +0,0 @@ -import './provider.dart' show Provider; - -bool isProviderLiteral(dynamic obj) { - if (obj is Map) { - Map map = obj as Map; - return map.containsKey('provide'); - } else { - return false; - } -} - -Provider createProvider(dynamic obj) { - Map map = obj as Map; - return new Provider(map['provide'], useClass: map['useClass'], - useValue: map['useValue'], - useExisting: map['useExisting'], - useFactory: map['useFactory'], - deps: map['deps'], - multi: map['multi']); -} diff --git a/modules/@angular/core/src/linker/query_list.dart b/modules/@angular/core/src/linker/query_list.dart deleted file mode 100644 index f470a768f8..0000000000 --- a/modules/@angular/core/src/linker/query_list.dart +++ /dev/null @@ -1,44 +0,0 @@ -library angular2.src.core.compiler.query_list; - -import 'dart:collection'; -import 'package:angular2/src/facade/collection.dart'; -import 'package:angular2/src/facade/async.dart'; - -/** - * See query_list.ts - */ -class QueryList extends Object with IterableMixin { - bool _dirty = true; - List _results = []; - EventEmitter _emitter = new EventEmitter(); - - Iterator get iterator => _results.iterator; - - Stream> get changes => _emitter; - - int get length => _results.length; - T get first => _results.length > 0 ? _results.first : null; - T get last => _results.length > 0 ? _results.last : null; - String toString() { - return _results.toString(); - } - - /** @internal */ - void reset(List newList) { - _results = ListWrapper.flatten(newList); - _dirty = false; - } - - /** @internal */ - void notifyOnChanges() { - _emitter.add(this); - } - - /** @internal **/ - bool get dirty => _dirty; - - /** @internal **/ - void setDirty() { - _dirty = true; - } -} diff --git a/modules/@angular/core/src/metadata.dart b/modules/@angular/core/src/metadata.dart deleted file mode 100644 index 78f4edbff4..0000000000 --- a/modules/@angular/core/src/metadata.dart +++ /dev/null @@ -1,228 +0,0 @@ -library angular2.src.core.metadata; - -import 'package:angular2/src/facade/collection.dart' show List; -import 'package:angular2/src/core/change_detection/change_detection.dart'; -import './metadata/di.dart'; -import './metadata/directives.dart'; -import './metadata/view.dart'; -import './metadata/animations.dart' show AnimationEntryMetadata; - -export './metadata/di.dart'; -export './metadata/directives.dart'; -export './metadata/view.dart' hide VIEW_ENCAPSULATION_VALUES; -export './metadata/lifecycle_hooks.dart' show - AfterContentInit, - AfterContentChecked, - AfterViewInit, - AfterViewChecked, - OnChanges, - OnDestroy, - OnInit, - DoCheck; - -/** - * See: [DirectiveMetadata] for docs. - * @stable - */ -class Directive extends DirectiveMetadata { - const Directive( - {String selector, - List inputs, - List outputs, - @Deprecated('Use `inputs` or `@Input` instead') - List properties, - @Deprecated('Use `outputs` or `@Output` instead') - List events, - Map host, - List providers, - String exportAs, - Map queries}) - : super( - selector: selector, - inputs: inputs, - outputs: outputs, - properties: properties, - events: events, - host: host, - providers: providers, - exportAs: exportAs, - queries: queries); -} - -/** - * See: [ComponentMetadata] for docs. - * @stable - */ -class Component extends ComponentMetadata { - const Component( - {String selector, - List inputs, - List outputs, - @Deprecated('Use `inputs` or `@Input` instead') - List properties, - @Deprecated('Use `outputs` or `@Output` instead') - List events, - Map host, - List providers, - String exportAs, - String moduleId, - Map queries, - List viewProviders, - ChangeDetectionStrategy changeDetection, - String templateUrl, - String template, - dynamic directives, - dynamic pipes, - ViewEncapsulation encapsulation, - List styles, - List styleUrls, - List animations}) - : super( - selector: selector, - inputs: inputs, - outputs: outputs, - properties: properties, - events: events, - host: host, - providers: providers, - exportAs: exportAs, - moduleId: moduleId, - viewProviders: viewProviders, - queries: queries, - changeDetection: changeDetection, - templateUrl: templateUrl, - template: template, - directives: directives, - pipes: pipes, - encapsulation: encapsulation, - styles: styles, - styleUrls: styleUrls, - animations: animations); -} - -/** - * See: [ViewMetadata] for docs. - * @deprecated - */ -class View extends ViewMetadata { - const View( - {String templateUrl, - String template, - dynamic directives, - dynamic pipes, - ViewEncapsulation encapsulation, - List styles, - List styleUrls, - List animations}) - : super( - templateUrl: templateUrl, - template: template, - directives: directives, - pipes: pipes, - encapsulation: encapsulation, - styles: styles, - styleUrls: styleUrls, - animations: animations); -} - -/** - * See: [PipeMetadata] for docs. - * @stable - */ -class Pipe extends PipeMetadata { - const Pipe({name, pure}) : super(name: name, pure: pure); -} - -/** - * See: [AttributeMetadata] for docs. - * @stable - */ -class Attribute extends AttributeMetadata { - const Attribute(String attributeName) : super(attributeName); -} - -/** - * See: [QueryMetadata] for docs. - * @deprecated Use ContentChildren/ContentChild instead - */ -class Query extends QueryMetadata { - const Query(dynamic /*Type | string*/ selector, - {bool descendants: false, dynamic read: null}) - : super(selector, descendants: descendants, read: read); -} - -/** - * See: [ContentChildrenMetadata] for docs. - * @stable - */ -class ContentChildren extends ContentChildrenMetadata { - const ContentChildren(dynamic /*Type | string*/ selector, - {bool descendants: false, dynamic read: null}) - : super(selector, descendants: descendants, read: read); -} - -/** - * See: [ContentChildMetadata] for docs. - * @stable - */ -class ContentChild extends ContentChildMetadata { - const ContentChild(dynamic /*Type | string*/ selector, {dynamic read: null}) : super(selector, read: read); -} - -/** - * See: [ViewQueryMetadata] for docs. - * @deprecated Use ViewChildren/ViewChild instead - */ -class ViewQuery extends ViewQueryMetadata { - const ViewQuery(dynamic /*Type | string*/ selector, {dynamic read: null}) - : super(selector, descendants: true, read: read); -} - -/** - * See: [ViewChildrenMetadata] for docs. - * @stable - */ -class ViewChildren extends ViewChildrenMetadata { - const ViewChildren(dynamic /*Type | string*/ selector, {dynamic read: null}) : super(selector, read: read); -} - -/** - * See: [ViewChildMetadata] for docs. - * @stable - */ -class ViewChild extends ViewChildMetadata { - const ViewChild(dynamic /*Type | string*/ selector, {dynamic read: null}) : super(selector, read: read); -} - -/** - * See: [InputMetadata] for docs. - * @stable - */ -class Input extends InputMetadata { - const Input([String bindingPropertyName]) : super(bindingPropertyName); -} - -/** - * See: [OutputMetadata] for docs. - * @stable - */ -class Output extends OutputMetadata { - const Output([String bindingPropertyName]) : super(bindingPropertyName); -} - -/** - * See: [HostBindingMetadata] for docs. - * @stable - */ -class HostBinding extends HostBindingMetadata { - const HostBinding([String hostPropertyName]) : super(hostPropertyName); -} - -/** - * See: [HostListenerMetadata] for docs. - * @stable - */ -class HostListener extends HostListenerMetadata { - const HostListener(String eventName, [List args]) - : super(eventName, args); -} diff --git a/modules/@angular/core/src/profile/wtf_impl.dart b/modules/@angular/core/src/profile/wtf_impl.dart deleted file mode 100644 index 1650c64d79..0000000000 --- a/modules/@angular/core/src/profile/wtf_impl.dart +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Tracing for Dart applications. - * - * The tracing API hooks up to either [WTF](http://google.github.io/tracing-framework/) or - * [Dart Observatory](https://www.dartlang.org/tools/observatory/). - */ -library angular2.src.core.wtf_impl; - -typedef dynamic WtfScopeFn([arg0, arg1]); - -var context = null; -var _trace; -var _events; -var _createScope; -var _leaveScope; -var _beginTimeRange; -var _endTimeRange; -final List _arg1 = [null]; -final List _arg2 = [null, null]; - -bool detectWTF() { - if (context != null && context.hasProperty('wtf')) { - var wtf = context['wtf']; - if (wtf.hasProperty('trace')) { - _trace = wtf['trace']; - _events = _trace['events']; - _createScope = _events['createScope']; - _leaveScope = _trace['leaveScope']; - _beginTimeRange = _trace['beginTimeRange']; - _endTimeRange = _trace['endTimeRange']; - return true; - } - } - return false; -} - -int getArgSize(String signature) { - int start = signature.indexOf('(') + 1; - int end = signature.indexOf(')', start); - bool found = false; - int count = 0; - for (var i = start; i < end; i++) { - var ch = signature[i]; - if (identical(ch, ',')) { - found = false; - } - if (!found) { - found = true; - count++; - } - } - return count; -} - -dynamic createScope(String signature, [flags]) { - _arg2[0] = signature; - _arg2[1] = flags; - var jsScope = _createScope.apply(_arg2, thisArg: _events); - switch (getArgSize(signature)) { - case 0: - return ([arg0, arg1]) { - return jsScope.apply(const []); - }; - case 1: - return ([arg0, arg1]) { - _arg1[0] = arg0; - return jsScope.apply(_arg1); - }; - case 2: - return ([arg0, arg1]) { - _arg2[0] = arg0; - _arg2[1] = arg1; - return jsScope.apply(_arg2); - }; - default: - throw "Max 2 arguments are supported."; - } -} - -void leave(scope, [returnValue]) { - _arg2[0] = scope; - _arg2[1] = returnValue; - _leaveScope.apply(_arg2, thisArg: _trace); - return returnValue; -} - -dynamic startTimeRange(String rangeType, String action) { - _arg2[0] = rangeType; - _arg2[1] = action; - return _beginTimeRange.apply(_arg2, thisArg: _trace); -} - -void endTimeRange(dynamic range) { - _arg1[0] = range; - _endTimeRange.apply(_arg1, thisArg: _trace); -} diff --git a/modules/@angular/core/src/profile/wtf_init.dart b/modules/@angular/core/src/profile/wtf_init.dart deleted file mode 100644 index 870eb5f74d..0000000000 --- a/modules/@angular/core/src/profile/wtf_init.dart +++ /dev/null @@ -1,14 +0,0 @@ -library angular2.src.core.wtf_init; - -import 'dart:js' as js; -import 'wtf_impl.dart' as impl; - -/** - * Must be executed explicitly in Dart to set the JS Context. - * - * NOTE: this is done explicitly to allow WTF api not to depend on - * JS context and possible to run the noop WTF stubs outside the browser. - */ -wtfInit() { - impl.context = js.context; -} diff --git a/modules/@angular/core/src/reflection/debug_reflection_capabilities.dart b/modules/@angular/core/src/reflection/debug_reflection_capabilities.dart deleted file mode 100644 index 7f36d151bd..0000000000 --- a/modules/@angular/core/src/reflection/debug_reflection_capabilities.dart +++ /dev/null @@ -1,63 +0,0 @@ -library reflection.debug_reflection_capabilities; - -import 'dart:mirrors'; -import 'package:logging/logging.dart' as log; -import 'package:stack_trace/stack_trace.dart'; -import 'types.dart'; -import 'reflection_capabilities.dart' as standard; - -class ReflectionCapabilities extends standard.ReflectionCapabilities { - final bool _verbose; - final log.Logger _log = new log.Logger('ReflectionCapabilities'); - - ReflectionCapabilities({bool verbose: false}) - : _verbose = verbose, - super() { - log.hierarchicalLoggingEnabled = true; - _log.level = _verbose ? log.Level.ALL : log.Level.INFO; - _log.onRecord.listen((log.LogRecord rec) { - print('[${rec.loggerName}(${rec.level.name})]: ${rec.message}'); - }); - } - - void _notify(String methodName, param) { - var trace = _verbose ? ' ${Trace.format(new Trace.current())}' : ''; - _log.info('"$methodName" requested for "$param".$trace'); - } - - Function factory(Type type) { - ClassMirror classMirror = reflectType(type); - _notify('factory', '${classMirror.qualifiedName}'); - return super.factory(type); - } - - List parameters(typeOrFunc) { - _notify('parameters', typeOrFunc); - return super.parameters(typeOrFunc); - } - - List annotations(typeOrFunc) { - _notify('annotations', typeOrFunc); - return super.annotations(typeOrFunc); - } - - Map propMetadata(typeOrFunc) { - _notify('propMetadata', typeOrFunc); - return super.propMetadata(typeOrFunc); - } - - GetterFn getter(String name) { - _notify('getter', name); - return super.getter(name); - } - - SetterFn setter(String name) { - _notify('setter', name); - return super.setter(name); - } - - MethodFn method(String name) { - _notify('method', name); - return super.method(name); - } -} diff --git a/modules/@angular/core/src/reflection/reflection.dart b/modules/@angular/core/src/reflection/reflection.dart deleted file mode 100644 index f110cc8b6e..0000000000 --- a/modules/@angular/core/src/reflection/reflection.dart +++ /dev/null @@ -1,59 +0,0 @@ -library reflection.reflection; - -import 'reflector.dart'; -import 'types.dart'; -export 'reflector.dart'; -import 'platform_reflection_capabilities.dart'; -import 'package:angular2/src/facade/lang.dart'; - -class NoReflectionCapabilities implements PlatformReflectionCapabilities { - @override - bool isReflectionEnabled() { - return false; - } - - @override - Function factory(Type type) { - throw "Cannot find reflection information on ${stringify(type)}"; - } - - @override - List interfaces(Type type) { - throw "Cannot find reflection information on ${stringify(type)}"; - } - - @override - List parameters(dynamic type) { - throw "Cannot find reflection information on ${stringify(type)}"; - } - - @override - List annotations(dynamic type) { - throw "Cannot find reflection information on ${stringify(type)}"; - } - - @override - Map propMetadata(dynamic type) { - throw "Cannot find reflection information on ${stringify(type)}"; - } - - @override - GetterFn getter(String name) { - throw "Cannot find getter ${name}"; - } - - @override - SetterFn setter(String name) { - throw "Cannot find setter ${name}"; - } - - @override - MethodFn method(String name) { - throw "Cannot find method ${name}"; - } - - @override - String importUri(Type type) => './'; -} - -final Reflector reflector = new Reflector(new NoReflectionCapabilities()); diff --git a/modules/@angular/core/src/reflection/reflection_capabilities.dart b/modules/@angular/core/src/reflection/reflection_capabilities.dart deleted file mode 100644 index 49fbeeee69..0000000000 --- a/modules/@angular/core/src/reflection/reflection_capabilities.dart +++ /dev/null @@ -1,458 +0,0 @@ -library reflection.reflection_capabilities; - -import 'dart:mirrors'; - -import 'package:angular2/src/core/metadata/lifecycle_hooks.dart'; -import 'package:angular2/src/facade/lang.dart'; - -import 'platform_reflection_capabilities.dart'; -import 'types.dart'; - -import '../linker/template_ref.dart'; - -var DOT_REGEX = new RegExp('\\.'); - -class ReflectionCapabilities implements PlatformReflectionCapabilities { - Map parameterizedTypeMapping = new Map(); - - ReflectionCapabilities([metadataReader]) { - // In Dart, there is no way of getting from a parameterized Type to - // the underlying non parameterized type. - // So we need to have a separate Map for the types that are generic - // and used in our DI... - parameterizedTypeMapping[reflectType(TemplateRef).qualifiedName] = TemplateRef; - } - - _typeFromMirror(TypeMirror typeMirror) { - var result = parameterizedTypeMapping[typeMirror.qualifiedName]; - if (result == null && typeMirror.hasReflectedType && typeMirror.reflectedType != dynamic) { - result = typeMirror.reflectedType; - } - return result; - } - - bool isReflectionEnabled() { - return true; - } - - Function factory(Type type) { - ClassMirror classMirror = reflectType(type); - MethodMirror ctor = classMirror.declarations[classMirror.simpleName]; - Function create = classMirror.newInstance; - Symbol name = ctor.constructorName; - int length = ctor.parameters.length; - - switch (length) { - case 0: - return () => create(name, []).reflectee; - case 1: - return (a1) => create(name, [a1]).reflectee; - case 2: - return (a1, a2) => create(name, [a1, a2]).reflectee; - case 3: - return (a1, a2, a3) => create(name, [a1, a2, a3]).reflectee; - case 4: - return (a1, a2, a3, a4) => create(name, [a1, a2, a3, a4]).reflectee; - case 5: - return (a1, a2, a3, a4, a5) => - create(name, [a1, a2, a3, a4, a5]).reflectee; - case 6: - return (a1, a2, a3, a4, a5, a6) => - create(name, [a1, a2, a3, a4, a5, a6]).reflectee; - case 7: - return (a1, a2, a3, a4, a5, a6, a7) => - create(name, [a1, a2, a3, a4, a5, a6, a7]).reflectee; - case 8: - return (a1, a2, a3, a4, a5, a6, a7, a8) => - create(name, [a1, a2, a3, a4, a5, a6, a7, a8]).reflectee; - case 9: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9) => - create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9]).reflectee; - case 10: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) => - create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10]).reflectee; - case 11: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) => - create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11]) - .reflectee; - case 12: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) => - create(name, [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12]) - .reflectee; - case 13: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13 - ]).reflectee; - case 14: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14 - ]).reflectee; - case 15: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15 - ]).reflectee; - case 16: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15, a16) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15, - a16 - ]).reflectee; - case 17: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15, a16, a17) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15, - a16, - a17 - ]).reflectee; - case 18: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15, a16, a17, a18) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15, - a16, - a17, - a18 - ]).reflectee; - case 19: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15, a16, a17, a18, a19) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15, - a16, - a17, - a18, - a19 - ]).reflectee; - case 20: - return (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, - a15, a16, a17, a18, a19, a20) => - create(name, [ - a1, - a2, - a3, - a4, - a5, - a6, - a7, - a8, - a9, - a10, - a11, - a12, - a13, - a14, - a15, - a16, - a17, - a18, - a19, - a20 - ]).reflectee; - } - - throw "Cannot create a factory for '${stringify(type)}' because its constructor has more than 20 arguments"; - } - - List parameters(typeOrFunc) { - final parameters = typeOrFunc is Type - ? _constructorParameters(typeOrFunc) - : _functionParameters(typeOrFunc); - return parameters.map(_convertParameter).toList(); - } - - List _convertParameter(ParameterMirror p) { - var t = p.type; - var type = _typeFromMirror(t); - var res = type != null ? [type] : []; - res.addAll(p.metadata.map((m) => m.reflectee)); - return res; - } - - List annotations(typeOrFunc) { - final meta = typeOrFunc is Type - ? _constructorMetadata(typeOrFunc) - : _functionMetadata(typeOrFunc); - - return meta.map((m) => m.reflectee).toList(); - } - - Map propMetadata(typeOrFunc) { - final res = {}; - reflectClass(typeOrFunc).declarations.forEach((k, v) { - var name = _normalizeName(MirrorSystem.getName(k)); - if (res[name] == null) res[name] = []; - res[name].addAll(v.metadata.map((fm) => fm.reflectee)); - }); - return res; - } - - String _normalizeName(String name) { - return name.endsWith("=") ? name.substring(0, name.length - 1) : name; - } - - bool hasLifecycleHook(dynamic type, Type lcInterface, String lcProperty) { - if (type is! Type) return false; - return this.interfaces(type).contains(lcInterface); - } - - List interfaces(type) { - final clazz = reflectType(type); - _assertDeclaresLifecycleHooks(clazz); - return _interfacesFromMirror(clazz); - } - - List _interfacesFromMirror(classMirror) { - return classMirror.superinterfaces.map((si) => si.reflectedType).toList() - ..addAll(classMirror.superclass == null - ? [] - : _interfacesFromMirror(classMirror.superclass)); - } - - GetterFn getter(String name) { - var symbol = new Symbol(name); - return (receiver) => reflect(receiver).getField(symbol).reflectee; - } - - SetterFn setter(String name) { - var symbol = new Symbol(name); - return (receiver, value) => - reflect(receiver).setField(symbol, value).reflectee; - } - - MethodFn method(String name) { - var symbol = new Symbol(name); - return (receiver, posArgs) => - reflect(receiver).invoke(symbol, posArgs).reflectee; - } - - List _functionParameters(Function func) { - var closureMirror = reflect(func); - return closureMirror.function.parameters; - } - - List _constructorParameters(Type type) { - ClassMirror classMirror = reflectType(type); - MethodMirror ctor = classMirror.declarations[classMirror.simpleName]; - return ctor.parameters; - } - - List _functionMetadata(Function func) { - var closureMirror = reflect(func); - return closureMirror.function.metadata; - } - - List _constructorMetadata(Type type) { - ClassMirror classMirror = reflectType(type); - return classMirror.metadata; - } - - String importUri(dynamic type) { - // StaticSymbol - if (type is Map && type['filePath'] != null) { - return type['filePath']; - } - // Runtime type - return '${(reflectClass(type).owner as LibraryMirror).uri}'; - } -} - -final _lifecycleHookMirrors = [ - reflectType(AfterContentChecked), - reflectType(AfterContentInit), - reflectType(AfterViewChecked), - reflectType(AfterViewInit), - reflectType(DoCheck), - reflectType(OnChanges), - reflectType(OnDestroy), - reflectType(OnInit), -]; - -/// Checks whether [clazz] implements lifecycle ifaces without declaring them. -/// -/// Due to Dart implementation details, lifecycle hooks are only called when a -/// class explicitly declares that it implements the associated interface. -/// See https://goo.gl/b07Kii for details. -void _assertDeclaresLifecycleHooks(ClassMirror clazz) { - final missingDeclarations = []; - for (var iface in _lifecycleHookMirrors) { - if (!_checkDeclares(clazz, iface: iface) && - _checkImplements(clazz, iface: iface)) { - missingDeclarations.add(iface); - } - } - if (missingDeclarations.isNotEmpty) { - throw new MissingInterfaceError(clazz, missingDeclarations); - } -} - -/// Returns whether [clazz] declares that it implements [iface]. -/// -/// Returns `false` if [clazz] implements [iface] but does not declare it. -/// Returns `false` if [clazz]'s superclass declares that it -/// implements [iface]. -bool _checkDeclares(ClassMirror clazz, {ClassMirror iface: null}) { - if (iface == null) { - throw new ArgumentError.notNull('iface'); - } - return clazz.superinterfaces.contains(iface); -} - -/// Returns whether [clazz] implements [iface]. -/// -/// Returns `true` if [clazz] implements [iface] and does not declare it. -/// Returns `true` if [clazz]'s superclass implements [iface]. -/// -/// This is an approximation of a JavaScript feature check: -/// ```js -/// var matches = true; -/// for (var prop in iface) { -/// if (iface.hasOwnProperty(prop)) { -/// matches = matches && clazz.hasOwnProperty(prop); -/// } -/// } -/// return matches; -/// ``` -bool _checkImplements(ClassMirror clazz, {ClassMirror iface: null}) { - if (iface == null) { - throw new ArgumentError.notNull('iface'); - } - - var matches = true; - iface.declarations.forEach((symbol, declarationMirror) { - if (!matches) return; - if (declarationMirror.isConstructor || declarationMirror.isPrivate) return; - matches = clazz.declarations.keys.contains(symbol); - }); - if (!matches && clazz.superclass != null) { - matches = _checkImplements(clazz.superclass, iface: iface); - } - if (!matches && clazz.mixin != clazz) { - matches = _checkImplements(clazz.mixin, iface: iface); - } - - return matches; -} - -/// Error thrown when a class implements a lifecycle iface it does not declare. -class MissingInterfaceError extends Error { - final ClassMirror clazz; - final List missingDeclarations; - - MissingInterfaceError(this.clazz, this.missingDeclarations); - - @override - String toString() { - final buf = new StringBuffer(); - buf.write('${clazz.simpleName} implements '); - if (missingDeclarations.length == 1) { - buf.write('an interface but does not declare it: '); - } else { - buf.write('interfaces but does not declare them: '); - } - buf.write( - missingDeclarations.map((d) => d.simpleName.toString()).join(', ')); - buf.write('. See https://goo.gl/b07Kii for more info.'); - return buf.toString(); - } -} diff --git a/modules/@angular/core/src/reflection/types.dart b/modules/@angular/core/src/reflection/types.dart deleted file mode 100644 index 2bc51af45c..0000000000 --- a/modules/@angular/core/src/reflection/types.dart +++ /dev/null @@ -1,5 +0,0 @@ -library reflection.types; - -typedef SetterFn(obj, value); -typedef GetterFn(obj); -typedef MethodFn(obj, List args); diff --git a/modules/@angular/core/src/util.dart b/modules/@angular/core/src/util.dart deleted file mode 100644 index a4c365c124..0000000000 --- a/modules/@angular/core/src/util.dart +++ /dev/null @@ -1,4 +0,0 @@ -library angular2.src.core.util; - -// the ts version is needed only for TS, we don't need a Dart implementation -// because there are no decorators in Dart. diff --git a/modules/@angular/core/src/util/decorators.dart b/modules/@angular/core/src/util/decorators.dart deleted file mode 100644 index f7d274607e..0000000000 --- a/modules/@angular/core/src/util/decorators.dart +++ /dev/null @@ -1 +0,0 @@ -library angular2.core.util.decorators; diff --git a/modules/@angular/core/src/zone/ng_zone_impl.dart b/modules/@angular/core/src/zone/ng_zone_impl.dart deleted file mode 100644 index 15aa36e29e..0000000000 --- a/modules/@angular/core/src/zone/ng_zone_impl.dart +++ /dev/null @@ -1,226 +0,0 @@ -library angular.zone; - -import 'dart:async'; -import 'package:stack_trace/stack_trace.dart' show Chain; - -typedef void ZeroArgFunction(); -typedef void ErrorHandlingFn(error, stackTrace); - -/** - * A `Timer` wrapper that lets you specify additional functions to call when it - * is cancelled. - */ -class WrappedTimer implements Timer { - Timer _timer; - ZeroArgFunction _onCancelCb; - - WrappedTimer(Timer timer) { - _timer = timer; - } - - void addOnCancelCb(ZeroArgFunction onCancelCb) { - if (this._onCancelCb != null) { - throw "On cancel cb already registered"; - } - this._onCancelCb = onCancelCb; - } - - void cancel() { - if (this._onCancelCb != null) { - this._onCancelCb(); - } - _timer.cancel(); - } - - bool get isActive => _timer.isActive; -} - -/** - * Stores error information; delivered via [NgZone.onError] stream. - */ -class NgZoneError { - /// Error object thrown. - final error; - /// Either long or short chain of stack traces. - final List stackTrace; - NgZoneError(this.error, this.stackTrace); -} - -/** - * A `Zone` wrapper that lets you schedule tasks after its private microtask queue is exhausted but - * before the next "VM turn", i.e. event loop iteration. - * - * This lets you freely schedule microtasks that prepare data, and set an {@link onMicrotaskEmpty} handler that - * will consume that data after it's ready but before the browser has a chance to re-render. - * - * A VM turn consist of a single macrotask followed 0 to many microtasks. - * - * The wrapper maintains an "inner" and "mount" `Zone`. The application code will executes - * in the "inner" zone unless `runOutsideAngular` is explicitely called. - * - * A typical application will create a singleton `NgZone`. The mount zone is the `Zone` where the singleton has been - * instantiated. The default `onMicrotaskEmpty` runs the Angular change detection. - */ -class NgZoneImpl { - static bool isInAngularZone() { - return Zone.current['isAngularZone'] == true; - } - - // Number of microtasks pending from _innerZone (& descendants) - int _pendingMicrotasks = 0; - List _pendingTimers = []; - Function onEnter; - Function onLeave; - Function setMicrotask; - Function setMacrotask; - Function onError; - - Zone _outerZone; - Zone _innerZone; - /** - * Associates with this - * - * - a "mount" [Zone], which is a the one that instantiated this. - * - an "inner" [Zone], which is a child of the mount [Zone]. - * - * @param {bool} trace whether to enable long stack trace. They should only be - * enabled in development mode as they significantly impact perf. - */ - NgZoneImpl({ - bool trace, - Function this.onEnter, - Function this.onLeave, - Function this.setMicrotask, - Function this.setMacrotask, - Function this.onError - }) { - _outerZone = Zone.current; - - if (trace) { - _innerZone = Chain.capture( - () => _createInnerZone(Zone.current), - onError: _onErrorWithLongStackTrace - ); - } else { - _innerZone = _createInnerZone( - Zone.current, - handleUncaughtError: _onErrorWithoutLongStackTrace - ); - } - } - - Zone _createInnerZone(Zone zone, {handleUncaughtError}) { - return zone.fork( - specification: new ZoneSpecification( - scheduleMicrotask: _scheduleMicrotask, - run: _run, - runUnary: _runUnary, - runBinary: _runBinary, - handleUncaughtError: handleUncaughtError, - createTimer: _createTimer), - zoneValues: {'isAngularZone': true} - ); - } - - dynamic runInnerGuarded(fn()) { - return _innerZone.runGuarded(fn); - } - - dynamic runInner(fn()) { - return _innerZone.run(fn); - } - - /** - * Runs `fn` in the mount zone and returns whatever it returns. - * - * In a typical app where the inner zone is the Angular zone, this allows one to escape Angular's - * auto-digest mechanism. - * - * ``` - * void myFunction(NgZone zone, Element element) { - * element.onClick.listen(() { - * // auto-digest will run after element click. - * }); - * zone.runOutsideAngular(() { - * element.onMouseMove.listen(() { - * // auto-digest will NOT run after mouse move - * }); - * }); - * } - * ``` - */ - dynamic runOuter(fn()) { - return _outerZone.run(fn); - } - - dynamic _run(Zone self, ZoneDelegate parent, Zone zone, fn()) { - try { - onEnter(); - return parent.run(zone, fn); - } finally { - onLeave(); - } - } - - dynamic _runUnary(Zone self, ZoneDelegate parent, Zone zone, fn(arg), arg) => - _run(self, parent, zone, () => fn(arg)); - - dynamic _runBinary(Zone self, ZoneDelegate parent, Zone zone, fn(arg1, arg2), - arg1, arg2) => - _run(self, parent, zone, () => fn(arg1, arg2)); - - void _scheduleMicrotask(Zone self, ZoneDelegate parent, Zone zone, fn) { - if (_pendingMicrotasks == 0) { - setMicrotask(true); - } - _pendingMicrotasks++; - var microtask = () { - try { - fn(); - } finally { - _pendingMicrotasks--; - if (_pendingMicrotasks == 0) { - setMicrotask(false); - } - } - }; - parent.scheduleMicrotask(zone, microtask); - } - - // Called by Chain.capture() on errors when long stack traces are enabled - void _onErrorWithLongStackTrace(error, Chain chain) { - final traces = chain.terse.traces.map((t) => t.toString()).toList(); - onError(new NgZoneError(error, traces)); - } - - // Outer zone handleUnchaughtError when long stack traces are not used - void _onErrorWithoutLongStackTrace(Zone self, ZoneDelegate parent, Zone zone, - error, StackTrace trace) - { - onError(new NgZoneError(error, [trace.toString()])); - } - - Timer _createTimer( - Zone self, ZoneDelegate parent, Zone zone, Duration duration, fn()) { - WrappedTimer wrappedTimer; - var cb = () { - try { - fn(); - } finally { - _pendingTimers.remove(wrappedTimer); - setMacrotask(_pendingTimers.isNotEmpty); - } - }; - Timer timer = parent.createTimer(zone, duration, cb); - wrappedTimer = new WrappedTimer(timer); - wrappedTimer.addOnCancelCb(() { - _pendingTimers.remove(wrappedTimer); - setMacrotask(_pendingTimers.isNotEmpty); - }); - - _pendingTimers.add(wrappedTimer); - setMacrotask(true); - return wrappedTimer; - } - -} diff --git a/modules/@angular/core/test/change_detection/iterable.dart b/modules/@angular/core/test/change_detection/iterable.dart deleted file mode 100644 index f4dfaad368..0000000000 --- a/modules/@angular/core/test/change_detection/iterable.dart +++ /dev/null @@ -1,6 +0,0 @@ -import 'dart:collection'; - -class TestIterable extends IterableBase { - List list = []; - Iterator get iterator => list.iterator; -} diff --git a/modules/@angular/core/test/di/binding_spec.dart b/modules/@angular/core/test/di/binding_spec.dart deleted file mode 100644 index 204bb1e67f..0000000000 --- a/modules/@angular/core/test/di/binding_spec.dart +++ /dev/null @@ -1,60 +0,0 @@ -/// This file contains tests that make sense only in Dart world, such as -/// verifying that things are valid constants. -library angular2.test.di.binding_dart_spec; - -import 'dart:mirrors'; -import 'package:@angular/core/testing/testing_internal.dart'; -import 'package:angular2/core.dart'; - -main() { - describe('Binding', () { - it('can create constant from token', () { - expect(const Binding(Foo).token).toBe(Foo); - }); - - it('can create constant from class', () { - expect(const Binding(Foo, toClass: Bar).toClass).toBe(Bar); - }); - - it('can create constant from value', () { - expect(const Binding(Foo, toValue: 5).toValue).toBe(5); - }); - - it('can create constant from alias', () { - expect(const Binding(Foo, toAlias: Bar).toAlias).toBe(Bar); - }); - - it('can create constant from factory', () { - expect(const Binding(Foo, toFactory: fn).toFactory).toBe(fn); - }); - - it('can be used in annotation', () { - ClassMirror mirror = reflectType(Annotated); - var bindings = mirror.metadata[0].reflectee.bindings; - expect(bindings.length).toBe(5); - bindings.forEach((b) { - expect(b).toBeA(Binding); - }); - }); - }); -} - -class Foo {} - -class Bar extends Foo {} - -fn() => null; - -class Annotation { - final List bindings; - const Annotation(this.bindings); -} - -@Annotation(const [ - const Binding(Foo), - const Binding(Foo, toClass: Bar), - const Binding(Foo, toValue: 5), - const Binding(Foo, toAlias: Bar), - const Binding(Foo, toFactory: fn) -]) -class Annotated {} diff --git a/modules/@angular/core/test/dom/html5lib_adapter.server.spec.dart b/modules/@angular/core/test/dom/html5lib_adapter.server.spec.dart deleted file mode 100644 index 42487e8f1a..0000000000 --- a/modules/@angular/core/test/dom/html5lib_adapter.server.spec.dart +++ /dev/null @@ -1,34 +0,0 @@ -library angular2.dom.html5lib_adapter.test; - -import 'package:guinness2/guinness2.dart'; -import 'package:test/test.dart' hide expect; -import 'package:angular2/src/platform/server/html_adapter.dart'; - -// A smoke-test of the adapter. It is primarily tested by the compiler. -main() { - describe('Html5Lib DOM Adapter', () { - Html5LibDomAdapter subject; - - beforeEach(() { - subject = new Html5LibDomAdapter(); - }); - - it('should parse HTML', () { - expect(subject.parse('
hi
'), isNotNull); - }); - - it('implements hasAttribute', () { - var div = subject.querySelector( - subject.parse('
'), ('div')); - expect(subject.hasAttribute(div, 'foo')).toBeTrue(); - expect(subject.hasAttribute(div, 'bar')).toBeFalse(); - }); - - it('implements getAttribute', () { - var div = subject.querySelector( - subject.parse('
'), ('div')); - expect(subject.getAttribute(div, 'foo')).toEqual('bar'); - expect(subject.getAttribute(div, 'bar')).toBe(null); - }); - }); -} diff --git a/modules/@angular/core/test/dom/shim_spec.dart b/modules/@angular/core/test/dom/shim_spec.dart deleted file mode 100644 index 27bfcee54b..0000000000 --- a/modules/@angular/core/test/dom/shim_spec.dart +++ /dev/null @@ -1,5 +0,0 @@ -library angular2.test.core.dom.shim_spec; - -main() { - // not relevant for dart. -} diff --git a/modules/@angular/core/test/facade/observable_spec.dart b/modules/@angular/core/test/facade/observable_spec.dart deleted file mode 100644 index 4877b20756..0000000000 --- a/modules/@angular/core/test/facade/observable_spec.dart +++ /dev/null @@ -1,5 +0,0 @@ -library angular2.test.facade.observable_spec; - -main() { - //stub to ignore JS Observable specific tests -} diff --git a/modules/@angular/core/test/forward_ref_integration_spec.dart b/modules/@angular/core/test/forward_ref_integration_spec.dart deleted file mode 100644 index d7e9e0c673..0000000000 --- a/modules/@angular/core/test/forward_ref_integration_spec.dart +++ /dev/null @@ -1,6 +0,0 @@ -/// This file contains tests that make sense only in Dart -library angular2.test.core.forward_ref_integration_spec; - -main() { - // Don't run in Dart as it is not relevant, and Dart const rules prevent us from expressing it. -} diff --git a/modules/@angular/core/test/linker/integration_dart_spec.dart b/modules/@angular/core/test/linker/integration_dart_spec.dart deleted file mode 100644 index 16f427b689..0000000000 --- a/modules/@angular/core/test/linker/integration_dart_spec.dart +++ /dev/null @@ -1,275 +0,0 @@ -/// This file contains tests that make sense only in Dart -library angular2.test.di.integration_dart_spec; - -import 'package:angular2/angular2.dart'; -import 'package:angular2/core.dart'; -import 'package:angular2/src/core/debug/debug_node.dart'; -import 'package:@angular/core/testing/testing_internal.dart'; -import 'package:observe/observe.dart'; -import 'package:angular2/src/core/change_detection/differs/default_iterable_differ.dart'; -import 'package:angular2/src/core/change_detection/change_detection.dart'; - -class MockException implements Error { - var message; - var stackTrace; -} - -class NonError { - var message; -} - -void functionThatThrows() { - try { - throw new MockException(); - } catch (e, stack) { - // If we lose the stack trace the message will no longer match - // the first line in the stack - e.message = stack.toString().split('\n')[0]; - e.stackTrace = stack; - rethrow; - } -} - -void functionThatThrowsNonError() { - try { - throw new NonError(); - } catch (e, stack) { - // If we lose the stack trace the message will no longer match - // the first line in the stack - e.message = stack.toString().split('\n')[0]; - rethrow; - } -} - -main() { - describe('Error handling', () { - it( - 'should preserve Error stack traces thrown from components', - inject([TestComponentBuilder, AsyncTestCompleter], (tb, async) { - tb - .overrideView( - Dummy, - new ViewMetadata( - template: '', - directives: [ThrowingComponent])) - .createAsync(Dummy) - .catchError((e, stack) { - expect(e).toContainError("MockException"); - expect(e).toContainError("functionThatThrows"); - async.done(); - }); - })); - - it( - 'should preserve non-Error stack traces thrown from components', - inject([TestComponentBuilder, AsyncTestCompleter], (tb, async) { - tb - .overrideView( - Dummy, - new ViewMetadata( - template: '', - directives: [ThrowingComponent2])) - .createAsync(Dummy) - .catchError((e, stack) { - expect(e).toContainError("NonError"); - expect(e).toContainError("functionThatThrows"); - async.done(); - }); - })); - }); - - describe('Property access', () { - it( - 'should distinguish between map and property access', - inject([TestComponentBuilder, AsyncTestCompleter], (tb, async) { - tb - .overrideView( - Dummy, - new ViewMetadata( - template: '', - directives: [PropertyAccess])) - .createAsync(Dummy) - .then((tc) { - tc.detectChanges(); - expect(asNativeElements(tc.debugElement.children)) - .toHaveText('prop:foo-prop;map:foo-map'); - async.done(); - }); - })); - - it( - 'should not fallback on map access if property missing', - inject([TestComponentBuilder, AsyncTestCompleter], (tb, async) { - tb - .overrideView( - Dummy, - new ViewMetadata( - template: '', - directives: [NoPropertyAccess])) - .createAsync(Dummy) - .then((tc) { - expect(() => tc.detectChanges()) - .toThrowError(new RegExp('property not found')); - async.done(); - }); - })); - }); - - describe('OnChange', () { - it( - 'should be notified of changes', - inject([TestComponentBuilder, AsyncTestCompleter], (tb, async) { - tb - .overrideView( - Dummy, - new ViewMetadata( - template: '''''', - directives: [OnChangeComponent])) - .createAsync(Dummy) - .then((tc) { - tc.detectChanges(); - var cmp = tc.debugElement.children[0] - .inject(OnChangeComponent); - expect(cmp.prop).toEqual('hello'); - expect(cmp.changes.containsKey('prop')).toEqual(true); - async.done(); - }); - })); - }); - - describe("ObservableListDiff", () { - it( - 'should be notified of changes', - fakeAsync(inject([TestComponentBuilder, Log], - (TestComponentBuilder tcb, Log log) { - tcb - .overrideView( - Dummy, - new ViewMetadata( - template: - '''''', - directives: [ComponentWithObservableList])) - .createAsync(Dummy) - .then((tc) { - tc.debugElement.componentInstance.value = - new ObservableList.from([1, 2]); - - tc.detectChanges(); - - expect(log.result()).toEqual("check"); - expect(asNativeElements(tc.debugElement.children)) - .toHaveText('12'); - - tc.detectChanges(); - - // we did not change the list => no checks - expect(log.result()).toEqual("check"); - - tc.debugElement.componentInstance.value.add(3); - - flushMicrotasks(); - - tc.detectChanges(); - - // we changed the list => a check - expect(log.result()).toEqual("check; check"); - expect(asNativeElements(tc.debugElement.children)) - .toHaveText('123'); - - // we replaced the list => a check - tc.debugElement.componentInstance.value = - new ObservableList.from([5, 6, 7]); - - tc.detectChanges(); - - expect(log.result()).toEqual("check; check; check"); - expect(asNativeElements(tc.debugElement.children)) - .toHaveText('567'); - }); - }))); - }); -} - -@Component(selector: 'dummy') -class Dummy { - dynamic value; -} - -@Component(selector: 'throwing-component') -@View(template: '') -class ThrowingComponent { - ThrowingComponent() { - functionThatThrows(); - } -} - -@Component(selector: 'throwing-component2') -@View(template: '') -class ThrowingComponent2 { - ThrowingComponent2() { - functionThatThrowsNonError(); - } -} - -@proxy -class PropModel implements Map { - final String foo = 'foo-prop'; - - operator [](_) => 'foo-map'; - - noSuchMethod(_) { - throw 'property not found'; - } -} - -@Component(selector: 'property-access') -@View(template: '''prop:{{model.foo}};map:{{model['foo']}}''') -class PropertyAccess { - final model = new PropModel(); -} - -@Component(selector: 'no-property-access') -@View(template: '''{{model.doesNotExist}}''') -class NoPropertyAccess { - final model = new PropModel(); -} - -@Component(selector: 'on-change', inputs: const ['prop']) -@View(template: '') -class OnChangeComponent implements OnChanges { - Map changes; - String prop; - - @override - void ngOnChanges(Map changes) { - this.changes = changes; - } -} - -@Component( - selector: 'component-with-observable-list', - changeDetection: ChangeDetectionStrategy.OnPush, - inputs: const ['list'], - providers: const [ - const Binding(IterableDiffers, - toValue: const IterableDiffers(const [ - const ObservableListDiffFactory(), - const DefaultIterableDifferFactory() - ])) - ]) -@View( - template: - '{{item}}', - directives: const [NgFor, DirectiveLoggingChecks]) -class ComponentWithObservableList { - Iterable list; -} - -@Directive(selector: 'directive-logging-checks') -class DirectiveLoggingChecks implements DoCheck { - Log log; - - DirectiveLoggingChecks(this.log); - - ngDoCheck() => log.add("check"); -} diff --git a/modules/@angular/core/test/metadata/decorators_spec.dart b/modules/@angular/core/test/metadata/decorators_spec.dart deleted file mode 100644 index 29fa75dd2e..0000000000 --- a/modules/@angular/core/test/metadata/decorators_spec.dart +++ /dev/null @@ -1,5 +0,0 @@ -library angular2.test.core.annotations.decorators_dart_spec; - -main() { - // not relavant for dart. -} diff --git a/modules/@angular/core/test/profile/wtf_impl_spec.dart b/modules/@angular/core/test/profile/wtf_impl_spec.dart deleted file mode 100644 index 04f2be93ff..0000000000 --- a/modules/@angular/core/test/profile/wtf_impl_spec.dart +++ /dev/null @@ -1,18 +0,0 @@ -/// This file contains tests that make sense only in Dart -library angular2.test.core.wtf_impl; - -import 'package:@angular/core/testing/testing_internal.dart'; -import 'package:angular2/src/core/profile/wtf_impl.dart' as impl; - -main() { - describe('WTF', () { - describe('getArgSize', () { - it("should parse args", () { - expect(impl.getArgSize('foo#bar')).toBe(0); - expect(impl.getArgSize('foo#bar()')).toBe(0); - expect(impl.getArgSize('foo#bar(foo bar)')).toBe(1); - expect(impl.getArgSize('foo#bar(foo bar, baz q)')).toBe(2); - }); - }); - }); -} diff --git a/modules/@angular/core/test/reflection/reflector_common.dart b/modules/@angular/core/test/reflection/reflector_common.dart deleted file mode 100644 index 4a3b307ac4..0000000000 --- a/modules/@angular/core/test/reflection/reflector_common.dart +++ /dev/null @@ -1,34 +0,0 @@ -class ClassDecorator { - final dynamic value; - - const ClassDecorator(this.value); -} - -class ParamDecorator { - final dynamic value; - - const ParamDecorator(this.value); -} - -class PropDecorator { - final dynamic value; - - const PropDecorator(this.value); -} - -ClassDecorator classDecorator(value) { - return new ClassDecorator(value); -} - -ParamDecorator paramDecorator(value) { - return new ParamDecorator(value); -} - -PropDecorator propDecorator(value) { - return new PropDecorator(value); -} - -class HasGetterAndSetterDecorators { - @PropDecorator("get") get a {} - @PropDecorator("set") set a(v) {} -} diff --git a/modules/@angular/core/test/spies.dart b/modules/@angular/core/test/spies.dart deleted file mode 100644 index ffbbeeaeb4..0000000000 --- a/modules/@angular/core/test/spies.dart +++ /dev/null @@ -1,19 +0,0 @@ -library core.spies; - -import 'package:angular2/core.dart'; -import 'package:angular2/src/core/change_detection/change_detection.dart'; -import 'package:angular2/src/platform/dom/dom_adapter.dart'; -import 'package:@angular/core/testing/testing_internal.dart'; - -@proxy -class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef {} - -@proxy -class SpyIterableDifferFactory extends SpyObject - implements IterableDifferFactory {} - -@proxy -class SpyElementRef extends SpyObject implements ElementRef {} - -@proxy -class SpyDomAdapter extends SpyObject implements DomAdapter {} diff --git a/modules/@angular/core/test/util/decorators_spec.dart b/modules/@angular/core/test/util/decorators_spec.dart deleted file mode 100644 index 3ac4e37048..0000000000 --- a/modules/@angular/core/test/util/decorators_spec.dart +++ /dev/null @@ -1,5 +0,0 @@ -library angular2.test.util.decorators_dart_spec; - -main() { - // not relavant for dart. -} diff --git a/modules/@angular/core/testing/async.dart b/modules/@angular/core/testing/async.dart deleted file mode 100644 index 44dd3363b7..0000000000 --- a/modules/@angular/core/testing/async.dart +++ /dev/null @@ -1,4 +0,0 @@ -// This symbol is not used on the Dart side. This exists just as a stub. -async(Function fn) { - throw 'async() test wrapper not available for Dart.'; -} diff --git a/modules/@angular/core/testing/fake_async.dart b/modules/@angular/core/testing/fake_async.dart deleted file mode 100644 index 81078154a2..0000000000 --- a/modules/@angular/core/testing/fake_async.dart +++ /dev/null @@ -1,103 +0,0 @@ -library testing.fake_async; - -import 'dart:async' show runZoned, ZoneSpecification; -import 'package:quiver/testing/async.dart' as quiver; -import 'package:angular2/src/facade/exceptions.dart' show BaseException; - -const _u = const Object(); - -quiver.FakeAsync _fakeAsync = null; - -/** - * Wraps the [fn] to be executed in the fakeAsync zone: - * - microtasks are manually executed by calling [flushMicrotasks], - * - timers are synchronous, [tick] simulates the asynchronous passage of time. - * - * If there are any pending timers at the end of the function, an exception - * will be thrown. - * - * Can be used to wrap inject() calls. - * - * Returns a `Function` that wraps [fn]. - */ -Function fakeAsync(Function fn) { - if (_fakeAsync != null) { - throw 'fakeAsync() calls can not be nested'; - } - - return ([a0 = _u, - a1 = _u, - a2 = _u, - a3 = _u, - a4 = _u, - a5 = _u, - a6 = _u, - a7 = _u, - a8 = _u, - a9 = _u]) { - // runZoned() to install a custom exception handler that re-throws - return runZoned(() { - return new quiver.FakeAsync().run((quiver.FakeAsync async) { - try { - _fakeAsync = async; - List args = [a0, a1, a2, a3, a4, a5, a6, a7, a8, a9] - .takeWhile((a) => a != _u) - .toList(); - var res = Function.apply(fn, args); - _fakeAsync.flushMicrotasks(); - - if (async.periodicTimerCount > 0) { - throw new BaseException('${async.periodicTimerCount} periodic ' - 'timer(s) still in the queue.'); - } - - if (async.nonPeriodicTimerCount > 0) { - throw new BaseException('${async.nonPeriodicTimerCount} timer(s) ' - 'still in the queue.'); - } - - return res; - } finally { - _fakeAsync = null; - } - }); - }, - zoneSpecification: new ZoneSpecification( - handleUncaughtError: (self, parent, zone, error, stackTrace) => - throw error)); - }; -} - -/** - * Simulates the asynchronous passage of [millis] milliseconds for the timers - * in the fakeAsync zone. - * - * The microtasks queue is drained at the very start of this function and after - * any timer callback has been executed. - */ -void tick([int millis = 0]) { - _assertInFakeAsyncZone(); - var duration = new Duration(milliseconds: millis); - _fakeAsync.elapse(duration); -} - -/** - * This is not needed in Dart. Because quiver correctly removes a timer when - * it throws an exception. - */ -void clearPendingTimers() {} - -/** - * Flush any pending microtasks. - */ -void flushMicrotasks() { - _assertInFakeAsyncZone(); - _fakeAsync.flushMicrotasks(); -} - -void _assertInFakeAsyncZone() { - if (_fakeAsync == null) { - throw new BaseException('The code should be running in the fakeAsync zone ' - 'to call this function'); - } -} diff --git a/modules/@angular/core/testing/lang_utils.dart b/modules/@angular/core/testing/lang_utils.dart deleted file mode 100644 index 62b6a66534..0000000000 --- a/modules/@angular/core/testing/lang_utils.dart +++ /dev/null @@ -1,10 +0,0 @@ -library testing.lang_utils; - -import 'dart:mirrors'; - -Type getTypeOf(instance) => instance.runtimeType; - -dynamic instantiateType(Type type, [List params = const []]) { - var cm = reflectClass(type); - return cm.newInstance(new Symbol(''), params).reflectee; -} diff --git a/modules/@angular/core/testing/testing.dart b/modules/@angular/core/testing/testing.dart deleted file mode 100644 index e58a9c8bff..0000000000 --- a/modules/@angular/core/testing/testing.dart +++ /dev/null @@ -1,3 +0,0 @@ -library angular2.src.testing.testing; - -// empty as this file is for external TS/js users and should not be transpiled to dart diff --git a/modules/@angular/core/testing/testing_internal.dart b/modules/@angular/core/testing/testing_internal.dart deleted file mode 100644 index 413852e9fb..0000000000 --- a/modules/@angular/core/testing/testing_internal.dart +++ /dev/null @@ -1,69 +0,0 @@ -library angular2.src.testing.testing_internal; - -import 'testing_internal_core.dart' as core; -export 'testing_internal_core.dart' - hide - beforeEachProviders, - beforeEachBindings, - beforeEach, - it, - iit, - xit, - testSetup, - describe, - ddescribe, - xdescribe; - -import 'package:angular2/platform/testing/browser.dart'; -import 'package:angular2/src/facade/collection.dart' show StringMapWrapper; -import "package:angular2/src/core/zone/ng_zone.dart" show NgZone; - -export 'test_injector.dart' show inject; - -void testSetup() { - core.setDartBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS); -} - -void beforeEachProviders(Function fn) { - testSetup(); - core.beforeEachProviders(fn); -} - -@Deprecated('using beforeEachProviders instead') -void beforeEachBindings(Function fn) { - beforeEachProviders(fn); -} - -void beforeEach(fn) { - testSetup(); - core.beforeEach(fn); -} - -void it(name, fn, [timeOut = null]) { - core.it(name, fn, timeOut); -} - -void iit(name, fn, [timeOut = null]) { - core.iit(name, fn, timeOut); -} - -void xit(name, fn, [timeOut = null]) { - core.xit(name, fn, timeOut); -} - -void describe(name, fn) { - testSetup(); - core.describe(name, fn); -} - -void ddescribe(name, fn) { - testSetup(); - core.ddescribe(name, fn); -} - -void xdescribe(name, fn) { - testSetup(); - core.xdescribe(name, fn); -} - -bool isInInnerZone() => NgZone.isInAngularZone(); diff --git a/modules/@angular/docs/web_workers/web_workers.md b/modules/@angular/docs/web_workers/web_workers.md index 9772148263..7e7cfc3ef2 100644 --- a/modules/@angular/docs/web_workers/web_workers.md +++ b/modules/@angular/docs/web_workers/web_workers.md @@ -144,8 +144,6 @@ but should use the angular 2 transformer to remove it in your final JS code. Not with running the transformer on your UI code (#3971). You can (and should) pass the file where you call `bootstrap` as an entry point to the transformer, but you should not pass your UI index file to the transformer until that bug is fixed. -* In dart we call `asyncApplication` instead of `application` from the render thread because starting an isolate in Dart is asyncronous - whereas starting a new WebWorker in JavaScript is a synchronous operation. ## Writing WebWorker Compatible Components You can do almost everything in a WebWorker component that you can do in a typical Angular 2 Component. @@ -306,9 +304,6 @@ If you use the MessageBus directly, you are responsible for serializing your mes In JavaScript / TypeScript this means they must be serializable via JavaScript's [structured cloning algorithim](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). -In Dart this means they must be valid messages that can be passed through a -[SendPort](https://api.dartlang.org/1.12.1/dart-isolate/SendPort/send.html). - ### MessageBus and Zones The MessageBus API includes support for [zones](http://www.github.com/angular/zone.js). @@ -333,36 +328,8 @@ if you do this, you don't need to implement zone or channel support yourself. Yo `MessageBusSink` that extends `GenericMessageBusSink` and a `MessageBusSource` that extends `GenericMessageBusSource`. The `MessageBusSink` must override the `sendMessages` method. This method is given a list of serialized messages that it is required to send through the sink. -The `MessageBusSource` needs to provide a [Stream](https://api.dartlang.org/1.12.1/dart-async/Stream-class.html) -of incoming messages (either by passing the stream to `GenericMessageBusSource's` constructor or by calling -attachTo() with the stream). It also needs to override the abstract `decodeMessages` method. This method is -given a List of serialized messages received by the source and should perform any decoding work that needs to be -done before the application can read the messages. -For example, if your MessageBus sends and receives JSON data you would do the following: -```Dart -import 'package:angular2/src/web_workers/shared/generic_message_bus.dart'; -import 'dart:convert'; - -class JsonMessageBusSink extends GenericMessageBusSink { - @override - void sendMessages(List messages) { - String encodedMessages = JSON.encode(messages); - // Send encodedMessages here - } -} - -class JsonMessageBusSource extends GenericMessageBuSource { - JsonMessageBusSource(Stream incomingMessages) : super (incomingMessages); - - @override - List decodeMessages(dynamic messages) { - return JSON.decode(messages); - } -} -``` - -Once you've implemented your custom MessageBus in either TypeScript or Dart, you must provide it through DI +Once you've implemented your custom MessageBus in either TypeScript, you must provide it through DI during bootstrap like so: In TypeScript: @@ -410,52 +377,6 @@ function initAppThread(zone: NgZone, bus: MyAwesomeMessageBus): void{ */ } ``` -In Dart: -```Dart -// index.dart, running on the UI side -import 'package:angular2/core.dart'; -import 'package:angular2/platform/worker_render.dart'; - -main() { - var bus = new MyAwesomeMessageBus(); - platform([WORKER_RENDER_PLATFORM]) - .application([WORKER_RENDER_APPLICATION_COMMON, new Provider(MessageBus, useValue: bus), - new Provider(APP_INITIALIZER, - useFactory: (injector) => () => initializeGenericWorkerRenderer(injector), - deps: [Injector], - multi: true - ) - ]); -} - -``` -```Dart -// background_index.dart, running on the application side -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; -import "./app.dart" show MyApp; - -main() { - /** - * Do initialization work here to set up the app thread and MessageBus; - * Once you have a working MessageBus you should bootstrap your app. - */ - reflector.reflectionCapabilities = new ReflectionCapabilities(); - platform([WORKER_APP_PLATFORM_PROVIDERS]) - .application([WORKER_APP_APPLICATION_COMMON, new Provider(MessageBus, useValue: bus), -new Provider(APP_INITIALIZER, useFactory: (zone, bus) => () => initAppThread(zone, bus), multi: true, deps: [NgZone, MessageBus])]) - .bootstrap(MyApp); -} - - -void initAppThread(NgZone zone) { - /** - * Here you can do any initilization work that requires the app providers to be initialized. - * At a minimum, you must attach your bus to the zone and setup a DOM adapter. - * Depending on your environment you may choose to do more work here. - */ -} -``` Notice how we use the `WORKER_RENDER_APPLICTION_COMMON` providers instead of the `WORKER_RENDER_APPLICATION` providers on the render thread. This is because the `WORKER_RENDER_APPLICATION` providers include an application initializer that starts a new WebWorker/Isolate. The `WORKER_RENDER_APPLICATION_COMMON` providers make no assumption about where your application code lives. diff --git a/modules/@angular/examples/core/pipes/ts/async_pipe/async_pipe_example.dart b/modules/@angular/examples/core/pipes/ts/async_pipe/async_pipe_example.dart deleted file mode 100644 index 2bc22b2b2a..0000000000 --- a/modules/@angular/examples/core/pipes/ts/async_pipe/async_pipe_example.dart +++ /dev/null @@ -1,2 +0,0 @@ -library angular2.examples.core.pipes.ts.async_pipe; -// TODO(alxhub): Implement an example for Dart. \ No newline at end of file diff --git a/modules/@angular/examples/core/pipes/ts/date_pipe/date_pipe_example.dart b/modules/@angular/examples/core/pipes/ts/date_pipe/date_pipe_example.dart deleted file mode 100644 index 40832aac06..0000000000 --- a/modules/@angular/examples/core/pipes/ts/date_pipe/date_pipe_example.dart +++ /dev/null @@ -1,2 +0,0 @@ -library angular2.examples.core.pipes.ts.date_pipe; -// TODO(alxhub): Implement an example for Dart. diff --git a/modules/@angular/facade/src/async.dart b/modules/@angular/facade/src/async.dart deleted file mode 100644 index 899a411b99..0000000000 --- a/modules/@angular/facade/src/async.dart +++ /dev/null @@ -1,132 +0,0 @@ -library angular2.core.facade.async; - -import 'dart:async'; -export 'dart:async' show Stream, StreamController, StreamSubscription; - -export 'promise.dart'; - -class TimerWrapper { - static Timer setTimeout(fn(), int millis) => - new Timer(new Duration(milliseconds: millis), fn); - static void clearTimeout(Timer timer) { - timer.cancel(); - } - - static Timer setInterval(fn(), int millis) { - var interval = new Duration(milliseconds: millis); - return new Timer.periodic(interval, (Timer timer) { - fn(); - }); - } - - static void clearInterval(Timer timer) { - timer.cancel(); - } -} - -class ObservableWrapper { - static StreamSubscription subscribe/**/(Stream s, onNext(/*=T*/ value), - [onError, onComplete]) { - return s.listen(onNext, - onError: onError, onDone: onComplete, cancelOnError: true); - } - - static bool isObservable(obs) { - return obs is Stream; - } - - /** - * Returns whether `emitter` has any subscribers listening to events. - */ - static bool hasSubscribers(EventEmitter emitter) { - return emitter._controller.hasListener; - } - - static void dispose(StreamSubscription s) { - s.cancel(); - } - - @Deprecated('Use callEmit() instead') - static void callNext(EventEmitter emitter, value) { - emitter.add(value); - } - - static void callEmit(EventEmitter emitter, value) { - emitter.add(value); - } - - static void callError(EventEmitter emitter, error) { - emitter.addError(error); - } - - static void callComplete(EventEmitter emitter) { - emitter.close(); - } - - static Stream fromPromise(Future f) { - return new Stream.fromFuture(f); - } - - static Future toPromise(Stream s) { - return s.single; - } -} - -class EventEmitter extends Stream { - StreamController _controller; - - /// Creates an instance of [EventEmitter], which depending on [isAsync], - /// delivers events synchronously or asynchronously. - EventEmitter([bool isAsync = true]) { - _controller = new StreamController.broadcast(sync: !isAsync); - } - - StreamSubscription listen(void onData(T event), - {Function onError, void onDone(), bool cancelOnError}) { - return _controller.stream.listen(onData, - onError: onError, onDone: onDone, cancelOnError: cancelOnError); - } - - void add(value) { - _controller.add(value); - } - - void emit(value) { - _controller.add(value); - } - - void addError(error) { - _controller.addError(error); - } - - void close() { - _controller.close(); - } -} - -//todo(robwormald): maybe fix in ts2dart? -class Subject extends Stream { - StreamController _controller; - - Subject([bool isAsync = true]) { - _controller = new StreamController.broadcast(sync: !isAsync); - } - - StreamSubscription listen(void onData(T data), - {Function onError, void onDone(), bool cancelOnError}) { - return _controller.stream.listen(onData, - onError: onError, onDone: onDone, cancelOnError: cancelOnError); - } - - void add(value) { - _controller.add(value); - } - - void addError(error) { - _controller.addError(error); - } - - void close() { - _controller.close(); - } -} diff --git a/modules/@angular/facade/src/base_wrapped_exception.dart b/modules/@angular/facade/src/base_wrapped_exception.dart deleted file mode 100644 index ab3b913f55..0000000000 --- a/modules/@angular/facade/src/base_wrapped_exception.dart +++ /dev/null @@ -1,17 +0,0 @@ -library angular.core.facade.base_wrapped_exception; - -/** - * A base class for the WrappedException that can be used to identify - * a WrappedException from ExceptionHandler without adding circular - * dependency. - */ -class BaseWrappedException extends Error { - BaseWrappedException(); - - get originalException => null; - get originalStack => null; - - String get message => ''; - String get wrapperMessage => ''; - dynamic get context => null; -} diff --git a/modules/@angular/facade/src/browser.dart b/modules/@angular/facade/src/browser.dart deleted file mode 100644 index 8c364d7f7d..0000000000 --- a/modules/@angular/facade/src/browser.dart +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Dart version of browser APIs. This library depends on 'dart:html' and - * therefore can only run in the browser. - */ -library angular2.src.facade.browser; - -import 'dart:js' show context; -import 'dart:html' show Location, window; - -export 'dart:html' - show - document, - window, - Element, - Node, - MouseEvent, - KeyboardEvent, - Event, - EventTarget, - History, - Location, - EventListener; - -Location get location => window.location; - -final _gc = context['gc']; - -void gc() { - if (_gc != null) { - _gc.apply(const []); - } -} diff --git a/modules/@angular/facade/src/collection.dart b/modules/@angular/facade/src/collection.dart deleted file mode 100644 index cabedff0a4..0000000000 --- a/modules/@angular/facade/src/collection.dart +++ /dev/null @@ -1,287 +0,0 @@ -library facade.collection; - -import 'dart:collection' show IterableBase; -import 'dart:convert' show JsonEncoder; -export 'dart:core' show Iterator, Map, List, Set; -import 'dart:math' show max, min; - -var jsonEncoder = new JsonEncoder(); - -class MapIterator extends Iterator { - final Iterator _iterator; - final Map _map; - - MapIterator(Map map) - : _map = map, - _iterator = map.keys.iterator; - - bool moveNext() => _iterator.moveNext(); - - List get current { - return _iterator.current != null - ? [_iterator.current, _map[_iterator.current]] - : null; - } -} - -class IterableMap extends IterableBase { - final Map _map; - - IterableMap(Map map) : _map = map; - - Iterator get iterator => new MapIterator(_map); -} - -class MapWrapper { - static Map/**/ clone/**/(Map/**/ m) => new Map.from(m); - - // in opposite to JS, Dart does not create a new map - static Map/**/ createFromStringMap/**/(Map/**/ m) => m; - - // in opposite to JS, Dart does not create a new map - static Map/**/ toStringMap/**/(Map/**/ m) => m; - - static Map/**/ createFromPairs/**/(List pairs) => pairs.fold(/**/{}, (m, p) { - m[p[0]] = p[1]; - return m; - }); - - static void clearValues(Map m) { - for (var k in m.keys) { - m[k] = null; - } - } - - static Iterable/*>*/ iterable/**/(Map/**/ m) => new IterableMap(m); - static List/**/ keys/**/(Map/**/ m) => m.keys.toList(); - static List/**/ values/**/(Map/**/ m) => m.values.toList(); -} - -class StringMapWrapper { - static Map/**/ create/**/() => {}; - static bool contains/**/(Map/**/ map, String key) => map.containsKey(key); - static get/**/(Map/**/ map, String key) => map[key]; - static void set/**/(Map/**/ map, String key, /*=V*/value) { - map[key] = value; - } - - static void delete/**/(Map/**/ m, String k) { - m.remove(k); - } - - static void forEach/**/(Map/**/ m, fn(/*=V*/ v, String k)) { - m.forEach((k, v) => fn(v, k)); - } - - static Map/**/ merge/**/(Map/**/ a, Map/**/ b) { - var m = new Map/**/.from(a); - if (b != null) { - b.forEach((k, v) => m[k] = v); - } - return m; - } - - static List keys(Map a) { - return a.keys.toList(); - } - - static List values(Map a) { - return a.values.toList(); - } - - static bool isEmpty(Map m) => m.isEmpty; - static bool equals/**/(Map/**/ m1, Map/**/ m2) { - if (m1.length != m2.length) { - return false; - } - for (var key in m1.keys) { - if (m1[key] != m2[key]) { - return false; - } - } - return true; - } -} - -typedef bool Predicate(T item); - -class ListWrapper { - static List/**/ clone/**/(Iterable/**/ l) => new List.from(l); - static List/**/ createFixedSize/**/(int size) => new List(size); - static List/**/ createGrowableSize/**/(int size) => - new List.generate(size, (_) => null, growable: true); - - static bool contains(List m, k) => m.contains(k); - static int indexOf(List list, value, [int startIndex = 0]) => - list.indexOf(value, startIndex); - static int lastIndexOf(List list, value, [int startIndex = null]) => - list.lastIndexOf(value, startIndex == null ? list.length : startIndex); - - static void forEachWithIndex/**/(List/**/ list, fn(/*=T*/ item, int index)) { - for (var i = 0; i < list.length; ++i) { - fn(list[i], i); - } - } - static /*=T*/ first/**/(List/**/ list) => list.isEmpty ? null : list.first; - static /*=T*/ last/**/(List/**/ list) => list.isEmpty ? null : list.last; - static List/**/ reversed/**/(List/**/ list) => list.reversed.toList(); - static List/**/ concat/**/(List/**/ a, List/**/ b) { - return new List() - ..length = a.length + b.length - ..setRange(0, a.length, a) - ..setRange(a.length, a.length + b.length, b); - } - - static void insert/**/(List/**/ l, int index, /*=T*/ value) { - l.insert(index, value); - } - - static removeAt(List l, int index) => l.removeAt(index); - static void removeAll/**/(List/**/ list, List/**/ items) { - for (var i = 0; i < items.length; ++i) { - list.remove(items[i]); - } - } - - static bool remove/**/(List/**/ list, /*=T*/ item) => list.remove(item); - static void clear(List l) { - l.clear(); - } - - static bool isEmpty(Iterable list) => list.isEmpty; - static void fill/**/(List/**/ l, /*=T*/ value, [int start = 0, int end]) { - l.fillRange(_startOffset(l, start), _endOffset(l, end), value); - } - - static bool equals/**/(List/**/ a, List/**/ b) { - if (a.length != b.length) return false; - for (var i = 0; i < a.length; ++i) { - if (a[i] != b[i]) return false; - } - return true; - } - - static List/**/ slice/**/(List/**/ l, [int from = 0, int to]) { - from = _startOffset(l, from); - to = _endOffset(l, to); - //in JS if from > to an empty array is returned - if (to != null && from > to) { - return []; - } - return l.sublist(from, to); - } - - static List/**/ splice/**/(List/**/ l, int from, int length) { - from = _startOffset(l, from); - var to = from + length; - var sub = l.sublist(from, to); - l.removeRange(from, to); - return sub; - } - - static void sort/**/(List/**/ l, [int compareFn(/*=T*/a, /*=T*/b) = null]) { - if (compareFn == null) { - l.sort(); - } else { - l.sort(compareFn); - } - } - - static String toJSON(List l) { - return jsonEncoder.convert(l); - } - - // JS splice, slice, fill functions can take start < 0 which indicates a position relative to - // the end of the list - static int _startOffset(List l, int start) { - int len = l.length; - return start < 0 ? max(len + start, 0) : min(start, len); - } - - // JS splice, slice, fill functions can take end < 0 which indicates a position relative to - // the end of the list - static int _endOffset(List l, int end) { - int len = l.length; - if (end == null) return len; - return end < 0 ? max(len + end, 0) : min(end, len); - } - - static maximum(List l, fn(item)) { - if (l.length == 0) { - return null; - } - var solution = null; - var maxValue = double.NEGATIVE_INFINITY; - for (var index = 0; index < l.length; index++) { - var candidate = l[index]; - if (candidate == null) { - continue; - } - var candidateValue = fn(candidate); - if (candidateValue > maxValue) { - solution = candidate; - maxValue = candidateValue; - } - } - return solution; - } - - static List flatten(List l) { - var target = []; - _flattenArray(l, target); - return target; - } - - static addAll(List l, List source) { - l.addAll(source); - } -} - -List _flattenArray(List source, List target) { - if (source != null) { - for (var i = 0; i < source.length; i++) { - var item = source[i]; - if (item is List) { - _flattenArray(item, target); - } else { - target.add(item); - } - } - } - return target; -} - - -bool isListLikeIterable(obj) => obj is Iterable; - -bool areIterablesEqual/**/( - Iterable/**/ a, - Iterable/**/ b, - bool comparator(/*=T*/a, /*=T*/b)) -{ - var iterator1 = a.iterator; - var iterator2 = b.iterator; - - while (true) { - var done1 = !iterator1.moveNext(); - var done2 = !iterator2.moveNext(); - if (done1 && done2) return true; - if (done1 || done2) return false; - if (!comparator(iterator1.current, iterator2.current)) return false; - } -} - -void iterateListLike/**/(Iterable/**/ iter, fn(/*=T*/item)) { - assert(iter is Iterable); - for (var item in iter) { - fn(item); - } -} - -class SetWrapper { - static Set/**/ createFromList/**/(List/**/ l) => new Set.from(l); - static bool has/**/(Set/**/ s, /*=T*/key) => s.contains(key); - static void delete/**/(Set/**/ m, /*=T*/k) { - m.remove(k); - } -} diff --git a/modules/@angular/facade/src/exceptions.dart b/modules/@angular/facade/src/exceptions.dart deleted file mode 100644 index bc16f3ca22..0000000000 --- a/modules/@angular/facade/src/exceptions.dart +++ /dev/null @@ -1,50 +0,0 @@ -library angular.core.facade.exceptions; - -import 'base_wrapped_exception.dart'; -import 'exception_handler.dart'; -export 'exception_handler.dart'; - -class BaseException extends Error { - final String _message; - - BaseException([this._message]); - - String get message => _message; - - String toString() { - return this.message; - } -} - -class WrappedException extends BaseWrappedException { - final dynamic _context; - final String _wrapperMessage; - final originalException; - final originalStack; - - WrappedException( - [this._wrapperMessage, - this.originalException, - this.originalStack, - this._context]); - - String get message { - return ExceptionHandler.exceptionToString(this); - } - - String toString() { - return this.message; - } - - dynamic get context => _context; - - String get wrapperMessage => _wrapperMessage; -} - -Error makeTypeError([String message = ""]) { - return new BaseException(message); -} - -dynamic unimplemented() { - throw new BaseException('unimplemented'); -} diff --git a/modules/@angular/facade/src/intl.dart b/modules/@angular/facade/src/intl.dart deleted file mode 100644 index c94b66be5b..0000000000 --- a/modules/@angular/facade/src/intl.dart +++ /dev/null @@ -1,57 +0,0 @@ -library facade.intl; - -import 'package:intl/intl.dart'; - -String _normalizeLocale(String locale) => locale.replaceAll('-', '_'); - -enum NumberFormatStyle { Decimal, Percent, Currency } - -class NumberFormatter { - static String format(num number, String locale, NumberFormatStyle style, - {int minimumIntegerDigits: 1, - int minimumFractionDigits: 0, - int maximumFractionDigits: 3, - String currency, - bool currencyAsSymbol: false}) { - locale = _normalizeLocale(locale); - NumberFormat formatter; - switch (style) { - case NumberFormatStyle.Decimal: - formatter = new NumberFormat.decimalPattern(locale); - break; - case NumberFormatStyle.Percent: - formatter = new NumberFormat.percentPattern(locale); - break; - case NumberFormatStyle.Currency: - if (currencyAsSymbol) { - // See https://github.com/dart-lang/intl/issues/59. - throw new Exception( - 'Displaying currency as symbol is not supported.'); - } - formatter = new NumberFormat.currencyPattern(locale, currency); - break; - } - formatter.minimumIntegerDigits = minimumIntegerDigits; - formatter.minimumFractionDigits = minimumFractionDigits; - formatter.maximumFractionDigits = maximumFractionDigits; - return formatter.format(number); - } -} - -class DateFormatter { - static RegExp _multiPartRegExp = new RegExp(r'^([yMdE]+)([Hjms]+)$'); - - static String format(DateTime date, String locale, String pattern) { - locale = _normalizeLocale(locale); - var formatter = new DateFormat(null, locale); - var matches = _multiPartRegExp.firstMatch(pattern); - if (matches != null) { - // Support for patterns which have known date and time components. - formatter.addPattern(matches[1]); - formatter.addPattern(matches[2], ', '); - } else { - formatter.addPattern(pattern); - } - return formatter.format(date); - } -} diff --git a/modules/@angular/facade/src/lang.dart b/modules/@angular/facade/src/lang.dart deleted file mode 100644 index a1b7670e6b..0000000000 --- a/modules/@angular/facade/src/lang.dart +++ /dev/null @@ -1,373 +0,0 @@ -library angular.core.facade.lang; - -export 'dart:core' show Type, RegExp, print, DateTime, Uri; -import 'dart:math' as math; -import 'dart:convert' as convert; -import 'dart:async' show Future, Zone; - -String getTypeNameForDebugging(Object type) => type.toString(); - -class Math { - static final _random = new math.Random(); - static int floor(num n) => n.floor(); - static double random() => _random.nextDouble(); - static num min(num a, num b) => math.min(a, b); -} - -const IS_DART = true; - -scheduleMicroTask(Function fn) { - Zone.current.scheduleMicrotask(fn); -} - -bool isPresent(Object obj) => obj != null; -bool isBlank(Object obj) => obj == null; -bool isString(Object obj) => obj is String; -bool isFunction(Object obj) => obj is Function; -bool isType(Object obj) => obj is Type; -bool isStringMap(Object obj) => obj is Map; -bool isStrictStringMap(Object obj) => obj is Map; -bool isArray(Object obj) => obj is List; -bool isPromise(Object obj) => obj is Future; -bool isNumber(Object obj) => obj is num; -bool isBoolean(Object obj) => obj is bool; -bool isDate(Object obj) => obj is DateTime; - -String stringify(obj) { - final exp = new RegExp(r"from Function '(\w+)'"); - final str = obj.toString(); - if (exp.firstMatch(str) != null) { - return exp.firstMatch(str).group(1); - } else { - return str; - } -} - -int serializeEnum(val) { - return val.index; -} - -/** - * Deserializes an enum - * val should be the indexed value of the enum (sa returned from @link{serializeEnum}) - * values should be a map from indexes to values for the enum that you want to deserialize. - */ -dynamic deserializeEnum(num val, Map values) { - return values[val]; -} - -String resolveEnumToken(enumValue, val) { - // turn Enum.Token -> Token - return val.toString().replaceFirst(new RegExp('^.+\\.'),''); -} - -class StringWrapper { - static String fromCharCode(int code) { - return new String.fromCharCode(code); - } - - static int charCodeAt(String s, int index) { - return s.codeUnitAt(index); - } - - static List split(String s, RegExp regExp) { - var parts = []; - var lastEnd = 0; - regExp.allMatches(s).forEach((match) { - parts.add(s.substring(lastEnd, match.start)); - lastEnd = match.end; - for (var i = 0; i < match.groupCount; i++) { - parts.add(match.group(i + 1)); - } - }); - parts.add(s.substring(lastEnd)); - return parts; - } - - static bool equals(String s, String s2) { - return s == s2; - } - - static String stripLeft(String s, String charVal) { - if (isPresent(s) && s.length > 0) { - var pos = 0; - for (var i = 0; i < s.length; i++) { - if (s[i] != charVal) break; - pos++; - } - s = s.substring(pos); - } - return s; - } - - static String stripRight(String s, String charVal) { - if (isPresent(s) && s.length > 0) { - var pos = s.length; - for (var i = s.length - 1; i >= 0; i--) { - if (s[i] != charVal) break; - pos--; - } - s = s.substring(0, pos); - } - return s; - } - - static String replace(String s, Pattern from, String replace) { - return s.replaceFirst(from, replace); - } - - static String replaceAll(String s, RegExp from, String replace) { - return s.replaceAll(from, replace); - } - - static String slice(String s, [int start = 0, int end]) { - start = _startOffset(s, start); - end = _endOffset(s, end); - //in JS if start > end an empty string is returned - if (end != null && start > end) { - return ""; - } - return s.substring(start, end); - } - - static String replaceAllMapped(String s, RegExp from, Function cb) { - return s.replaceAllMapped(from, cb); - } - - static bool contains(String s, String substr) { - return s.contains(substr); - } - - static int compare(String a, String b) => a.compareTo(b); - - // JS slice function can take start < 0 which indicates a position relative to - // the end of the string - static int _startOffset(String s, int start) { - int len = s.length; - return start < 0 ? math.max(len + start, 0) : math.min(start, len); - } - - // JS slice function can take end < 0 which indicates a position relative to - // the end of the string - static int _endOffset(String s, int end) { - int len = s.length; - if (end == null) return len; - return end < 0 ? math.max(len + end, 0) : math.min(end, len); - } -} - -class StringJoiner { - final List _parts = []; - - void add(String part) { - _parts.add(part); - } - - String toString() => _parts.join(""); -} - -class NumberWrapper { - static String toFixed(num n, int fractionDigits) { - return n.toStringAsFixed(fractionDigits); - } - - static bool equal(num a, num b) { - return a == b; - } - - static int parseIntAutoRadix(String text) { - return int.parse(text); - } - - static int parseInt(String text, int radix) { - return int.parse(text, radix: radix); - } - - static double parseFloat(String text) { - return double.parse(text); - } - - static double get NaN => double.NAN; - - static bool isNumeric(value) { - if(value == null) { - return false; - } - return double.parse(value, (e) => null) != null; - } - - static bool isNaN(num value) => value.isNaN; - - static bool isInteger(value) => value is int; -} - -class RegExpWrapper { - static RegExp create(regExpStr, [String flags = '']) { - bool multiLine = flags.contains('m'); - bool caseSensitive = !flags.contains('i'); - return new RegExp(regExpStr, - multiLine: multiLine, caseSensitive: caseSensitive); - } - - static Match firstMatch(RegExp regExp, String input) { - return regExp.firstMatch(input); - } - - static bool test(RegExp regExp, String input) { - return regExp.hasMatch(input); - } - - static Iterator matcher(RegExp regExp, String input) { - return regExp.allMatches(input).iterator; - } - - static String replaceAll(RegExp regExp, String input, Function replace) { - final m = RegExpWrapper.matcher(regExp, input); - var res = ""; - var prev = 0; - while(m.moveNext()) { - var c = m.current; - res += input.substring(prev, c.start); - res += replace(c); - prev = c.start + c[0].length; - } - res += input.substring(prev); - return res; - } -} - -class RegExpMatcherWrapper { - static _JSLikeMatch next(Iterator matcher) { - if (matcher.moveNext()) { - return new _JSLikeMatch(matcher.current); - } - return null; - } -} - -class _JSLikeMatch { - Match _m; - - _JSLikeMatch(this._m); - - String operator [](index) => _m[index]; - int get index => _m.start; - int get length => _m.groupCount + 1; -} - -class FunctionWrapper { - static apply(Function fn, posArgs) { - return Function.apply(fn, posArgs); - } - - static Function bind(Function fn, dynamic scope) { - return fn; - } -} - -const _NAN_KEY = const Object(); - -// Dart VM implements `identical` as true reference identity. JavaScript does -// not have this. The closest we have in JS is `===`. However, for strings JS -// would actually compare the contents rather than references. `dart2js` -// compiles `identical` to `===` and therefore there is a discrepancy between -// Dart VM and `dart2js`. The implementation of `looseIdentical` attempts to -// bridge the gap between the two while retaining good performance -// characteristics. In JS we use simple `identical`, which compiles to `===`, -// and in Dart VM we emulate the semantics of `===` by special-casing strings. -// Note that the VM check is a compile-time constant. This allows `dart2js` to -// evaluate the conditional during compilation and inline the entire function. -// -// See: dartbug.com/22496, dartbug.com/25270 -const _IS_DART_VM = !identical(1.0, 1); // a hack -bool looseIdentical(a, b) => _IS_DART_VM - ? _looseIdentical(a, b) - : identical(a, b); - -// This function is intentionally separated from `looseIdentical` to keep the -// number of AST nodes low enough for `dart2js` to inline the code. -bool _looseIdentical(a, b) => - a is String && b is String ? a == b : identical(a, b); - -// Dart compare map keys by equality and we can have NaN != NaN -dynamic getMapKey(value) { - if (value is! num) return value; - return value.isNaN ? _NAN_KEY : value; -} - -// TODO: remove with https://github.com/angular/angular/issues/3055 -dynamic normalizeBlank(obj) => obj; - -bool normalizeBool(bool obj) { - return isBlank(obj) ? false : obj; -} - -bool isJsObject(o) { - return false; -} - -warn(o) { - print(o); -} - -// Can't be all uppercase as our transpiler would think it is a special directive... -class Json { - static parse(String s) => convert.JSON.decode(s); - static String stringify(data) { - var encoder = new convert.JsonEncoder.withIndent(" "); - return encoder.convert(data); - } -} - -class DateWrapper { - static DateTime create(int year, - [int month = 1, - int day = 1, - int hour = 0, - int minutes = 0, - int seconds = 0, - int milliseconds = 0]) { - return new DateTime(year, month, day, hour, minutes, seconds, milliseconds); - } - - static DateTime fromISOString(String str) { - return DateTime.parse(str); - } - - static DateTime fromMillis(int ms) { - return new DateTime.fromMillisecondsSinceEpoch(ms, isUtc: true); - } - - static int toMillis(DateTime date) { - return date.millisecondsSinceEpoch; - } - - static DateTime now() { - return new DateTime.now(); - } - - static String toJson(DateTime date) { - return date.toUtc().toIso8601String(); - } -} - -bool isPrimitive(Object obj) => obj is num || obj is bool || obj == null || obj is String; - -// needed to match the exports from lang.js -var global = null; - -dynamic evalExpression(String sourceUrl, String expr, String declarations, Map vars) { - throw "Dart does not support evaluating expression during runtime!"; -} - -bool hasConstructor(Object value, Type type) { - return value.runtimeType == type; -} - -String escape(String s) { - return Uri.encodeComponent(s); -} - -String escapeRegExp(String s) { - return s.replaceAllMapped(new RegExp(r'([.*+?^=!:${}()|[\]\/\\])'), (Match m) => '\\${m[1]}'); -} diff --git a/modules/@angular/facade/src/math.dart b/modules/@angular/facade/src/math.dart deleted file mode 100644 index 08adb680d3..0000000000 --- a/modules/@angular/facade/src/math.dart +++ /dev/null @@ -1,24 +0,0 @@ -library angular.core.facade.math; - -import 'dart:core' show double, num; -import 'dart:math' as math; - -const NaN = double.NAN; - -class Math { - static num pow(num x, num exponent) { - return math.pow(x, exponent); - } - - static num max(num a, num b) => math.max(a, b); - - static num min(num a, num b) => math.min(a, b); - - static num floor(num a) => a.floor(); - - static num ceil(num a) => a.ceil(); - - static num sqrt(num x) => math.sqrt(x); - - static num round(num x) => x.round(); -} diff --git a/modules/@angular/facade/src/promise.dart b/modules/@angular/facade/src/promise.dart deleted file mode 100644 index eda21d483a..0000000000 --- a/modules/@angular/facade/src/promise.dart +++ /dev/null @@ -1,58 +0,0 @@ -library angular2.core.facade.promise; - -import 'dart:async'; -import 'dart:async' as async; - -class PromiseWrapper { - static Future/**/ resolve/**/(dynamic /*=T*/ obj) => new Future.value(obj); - - static Future/**/ reject/**/(dynamic /*=T*/ obj, Object stackTrace) => new Future.error(obj, - stackTrace != null ? stackTrace : obj is Error ? (obj as Error).stackTrace : null); - - static Future*/> all/**/(List promises) { - return Future - .wait(promises.map((p) => p is Future ? p as Future/**/ : new Future/**/.value(p))); - } - static Future/**/ then/**/(Future/**/ promise, dynamic /*=R*/ success(dynamic /*=T*/ value), [Function onError]) { - if (success == null) return promise.catchError(onError); - return promise.then(success, onError: onError); - } - - static Future/**/ wrap/**/(dynamic /*=T*/ fn()) { - return new Future(fn); - } - - // Note: We can't rename this method to `catch`, as this is not a valid - // method name in Dart. - static Future catchError(Future promise, Function onError) { - return promise.catchError(onError); - } - - static void scheduleMicrotask(fn) { - async.scheduleMicrotask(fn); - } - - static bool isPromise(obj) { - return obj is Future; - } - - static PromiseCompleter/**/ completer/**/() => - new PromiseCompleter(); -} - -class PromiseCompleter { - final Completer c = new Completer(); - - Future get promise => c.future; - - void resolve(v) { - c.complete(v); - } - - void reject(error, stack) { - if (stack == null && error is Error) { - stack = error.stackTrace; - } - c.completeError(error, stack); - } -} diff --git a/modules/@angular/facade/test/async_dart_spec.dart b/modules/@angular/facade/test/async_dart_spec.dart deleted file mode 100644 index bcf5a1c2a7..0000000000 --- a/modules/@angular/facade/test/async_dart_spec.dart +++ /dev/null @@ -1,106 +0,0 @@ -/// This file contains tests that make sense only in Dart -library angular2.test.facade.async_dart_spec; - -import 'dart:async'; -import 'package:angular2/testing_internal.dart'; -import 'package:angular2/src/facade/async.dart'; - -class MockException implements Error { - var message; - var stackTrace; -} - -class NonError { - var message; -} - -void functionThatThrows() { - try { - throw new MockException(); - } catch (e, stack) { - // If we lose the stack trace the message will no longer match - // the first line in the stack - e.message = stack.toString().split('\n')[0]; - e.stackTrace = stack; - rethrow; - } -} - -void functionThatThrowsNonError() { - try { - throw new NonError(); - } catch (e, stack) { - // If we lose the stack trace the message will no longer match - // the first line in the stack - e.message = stack.toString().split('\n')[0]; - rethrow; - } -} - -void expectFunctionThatThrowsWithStackTrace( - Future future, AsyncTestCompleter async) { - PromiseWrapper.catchError(future, (err, StackTrace stack) { - expect(stack.toString().split('\n')[0]).toEqual(err.message); - async.done(); - }); -} - -main() { - describe('async facade', () { - describe('Completer', () { - it( - 'should preserve Error stack traces', - inject([AsyncTestCompleter], (async) { - var c = PromiseWrapper.completer(); - - expectFunctionThatThrowsWithStackTrace(c.promise, async); - - try { - functionThatThrows(); - } catch (e) { - c.reject(e, null); - } - })); - - it( - 'should preserve error stack traces for non-Errors', - inject([AsyncTestCompleter], (async) { - var c = PromiseWrapper.completer(); - - expectFunctionThatThrowsWithStackTrace(c.promise, async); - - try { - functionThatThrowsNonError(); - } catch (e, s) { - c.reject(e, s); - } - })); - }); - - describe('PromiseWrapper', () { - describe('reject', () { - it( - 'should preserve Error stack traces', - inject([AsyncTestCompleter], (async) { - try { - functionThatThrows(); - } catch (e) { - var rejectedFuture = PromiseWrapper.reject(e, null); - expectFunctionThatThrowsWithStackTrace(rejectedFuture, async); - } - })); - - it( - 'should preserve stack traces for non-Errors', - inject([AsyncTestCompleter], (async) { - try { - functionThatThrowsNonError(); - } catch (e, s) { - var rejectedFuture = PromiseWrapper.reject(e, s); - expectFunctionThatThrowsWithStackTrace(rejectedFuture, async); - } - })); - }); - }); - }); -} diff --git a/modules/@angular/forms/common.dart b/modules/@angular/forms/common.dart deleted file mode 100644 index 1592d948a1..0000000000 --- a/modules/@angular/forms/common.dart +++ /dev/null @@ -1 +0,0 @@ -export 'index.dart'; diff --git a/modules/@angular/forms/src/directives/normalize_validator.dart b/modules/@angular/forms/src/directives/normalize_validator.dart deleted file mode 100644 index 510abb3001..0000000000 --- a/modules/@angular/forms/src/directives/normalize_validator.dart +++ /dev/null @@ -1,20 +0,0 @@ -library angular2.core.forms.normalize_validators; - -import 'package:angular2/src/common/forms/directives/validators.dart' show Validator; - -Function normalizeValidator(dynamic validator){ - if (validator is Validator) { - return (c) => validator.validate(c); - } else { - return validator; - } -} - - -Function normalizeAsyncValidator(dynamic validator){ - if (validator is Validator) { - return (c) => validator.validate(c); - } else { - return validator; - } -} diff --git a/modules/@angular/forms/test/spies.dart b/modules/@angular/forms/test/spies.dart deleted file mode 100644 index 6c94ca2246..0000000000 --- a/modules/@angular/forms/test/spies.dart +++ /dev/null @@ -1,14 +0,0 @@ -library core.spies; - -import 'package:angular2/common.dart'; -import 'package:angular2/src/core/change_detection/change_detection.dart'; -import 'package:angular2/testing_internal.dart'; - -@proxy -class SpyNgControl extends SpyObject implements NgControl {} - -@proxy -class SpyValueAccessor extends SpyObject implements ControlValueAccessor {} - -@proxy -class SpyChangeDetectorRef extends SpyObject implements ChangeDetectorRef {} diff --git a/modules/@angular/platform-browser/src/browser/location/history.dart b/modules/@angular/platform-browser/src/browser/location/history.dart deleted file mode 100644 index 1a06ea9ff6..0000000000 --- a/modules/@angular/platform-browser/src/browser/location/history.dart +++ /dev/null @@ -1,3 +0,0 @@ -import 'dart:html' show History; - -bool supportsState() => History.supportsState; \ No newline at end of file diff --git a/modules/@angular/platform-browser/src/browser/tools/tools.dart b/modules/@angular/platform-browser/src/browser/tools/tools.dart deleted file mode 100644 index ad6d0fc08b..0000000000 --- a/modules/@angular/platform-browser/src/browser/tools/tools.dart +++ /dev/null @@ -1,39 +0,0 @@ -library angular2.src.tools.tools; - -import 'dart:js'; -import 'package:angular2/src/core/linker/component_factory.dart' - show ComponentRef; -import 'common_tools.dart' show AngularTools; - -/** - * Enabled Angular 2 debug tools that are accessible via your browser's - * developer console. - * - * Usage: - * - * 1. Open developer console (e.g. in Chrome Ctrl + Shift + j) - * 1. Type `ng.` (usually the console will show auto-complete suggestion) - * 1. Try the change detection profiler `ng.profiler.timeChangeDetection()` - * then hit Enter. - * - * @experimental All debugging apis are currently experimental. - */ -void enableDebugTools(ComponentRef ref) { - final tools = new AngularTools(ref); - context['ng'] = new JsObject.jsify({ - 'profiler': { - 'timeChangeDetection': ([config]) { - tools.profiler.timeChangeDetection(config); - } - } - }); -} - -/** - * Disables Angular 2 tools. - * - * @experimental All debugging apis are currently experimental. - */ -void disableDebugTools() { - context.deleteProperty('ng'); -} diff --git a/modules/@angular/platform-browser/test/browser/tools/spies.dart b/modules/@angular/platform-browser/test/browser/tools/spies.dart deleted file mode 100644 index abb563bd55..0000000000 --- a/modules/@angular/platform-browser/test/browser/tools/spies.dart +++ /dev/null @@ -1,26 +0,0 @@ -import 'package:angular2/testing_internal.dart' show SpyObject; -import 'package:angular2/core.dart' show Injector, ReflectiveInjector, bind; -import 'package:angular2/src/core/application_ref.dart' show ApplicationRef; -import 'package:angular2/src/core/linker/component_factory.dart' - show ComponentRef; -import 'dart:js'; - -@proxy -class SpyApplicationRef extends SpyObject implements ApplicationRef { - tick() {} -} - -@proxy -class SpyComponentRef extends SpyObject implements ComponentRef { - Injector injector; - - SpyComponentRef() { - this.injector = ReflectiveInjector - .resolveAndCreate([{provide: ApplicationRef, useClass: SpyApplicationRef}]); - } -} - -void callNgProfilerTimeChangeDetection([config]) { - context['ng']['profiler'] - .callMethod('timeChangeDetection', config != null ? [config] : []); -} diff --git a/modules/@angular/platform-server/compiler_private.dart b/modules/@angular/platform-server/compiler_private.dart deleted file mode 100644 index 2490141638..0000000000 --- a/modules/@angular/platform-server/compiler_private.dart +++ /dev/null @@ -1 +0,0 @@ -export '../compiler.dart'; diff --git a/modules/@angular/platform-server/index.dart b/modules/@angular/platform-server/index.dart deleted file mode 100644 index ff9d666822..0000000000 --- a/modules/@angular/platform-server/index.dart +++ /dev/null @@ -1,2 +0,0 @@ -// TODO: vsavkin add SERVER_PROVIDERS and SERVER_APPLICATION_PROVIDERS -export 'package:angular2/src/platform/server/html_adapter.dart'; diff --git a/modules/@angular/platform-server/platform-server.dart b/modules/@angular/platform-server/platform-server.dart deleted file mode 100644 index d95e841ce0..0000000000 --- a/modules/@angular/platform-server/platform-server.dart +++ /dev/null @@ -1 +0,0 @@ -export './index.dart'; diff --git a/modules/@angular/platform-server/platform_browser_private.dart b/modules/@angular/platform-server/platform_browser_private.dart deleted file mode 100644 index 6bdd163a76..0000000000 --- a/modules/@angular/platform-server/platform_browser_private.dart +++ /dev/null @@ -1 +0,0 @@ -export './platform-browser.dart' show DomAdapter, setRootDomAdapter; diff --git a/modules/@angular/platform-server/src/abstract_html_adapter.dart b/modules/@angular/platform-server/src/abstract_html_adapter.dart deleted file mode 100644 index 41c595154b..0000000000 --- a/modules/@angular/platform-server/src/abstract_html_adapter.dart +++ /dev/null @@ -1,457 +0,0 @@ -library angular2.dom.abstractHtmlAdapter; - -import 'package:html/parser.dart' as parser; -import 'package:html/dom.dart'; - -import 'package:angular2/platform/common_dom.dart'; -import 'package:angular2/src/compiler/xhr.dart'; - -import 'package:angular2/src/facade/lang.dart' show isBlank, isPresent; -import 'package:angular2/src/platform/dom/animation/dom_animate_player.dart' show DomAnimatePlayer; - -const _attrToPropMap = const { - 'innerHtml': 'innerHTML', - 'readonly': 'readOnly', - 'tabindex': 'tabIndex', -}; - -abstract class AbstractHtml5LibAdapter implements DomAdapter { - hasProperty(element, String name) { - // This is needed for serverside compile to generate the right getters/setters. - // TODO: change this once we have property schema support. - // Attention: Keep this in sync with browser_adapter.dart! - return true; - } - - void setProperty(Element element, String name, Object value) => - throw 'not implemented'; - - getProperty(Element element, String name) => throw 'not implemented'; - - invoke(Element element, String methodName, List args) => - throw 'not implemented'; - - @override - get attrToPropMap => _attrToPropMap; - - @override - set attrToPropMap(value) { - throw 'readonly'; - } - - @override - getGlobalEventTarget(String target) { - throw 'not implemented'; - } - - @override - getTitle() { - throw 'not implemented'; - } - - @override - setTitle(String newTitle) { - throw 'not implemented'; - } - - @override - String getEventKey(event) { - throw 'not implemented'; - } - - @override - void replaceChild(el, newNode, oldNode) { - throw 'not implemented'; - } - - @override - dynamic getBoundingClientRect(el) { - throw 'not implemented'; - } - - @override - Type getXHR() => XHR; - - Element parse(String templateHtml) => parser.parse(templateHtml).firstChild; - query(selector) { - throw 'not implemented'; - } - - querySelector(el, String selector) { - return el.querySelector(selector); - } - - List querySelectorAll(el, String selector) { - return el.querySelectorAll(selector); - } - - on(el, evt, listener) { - throw 'not implemented'; - } - - Function onAndCancel(el, evt, listener) { - throw 'not implemented'; - } - - dispatchEvent(el, evt) { - throw 'not implemented'; - } - - createMouseEvent(eventType) { - throw 'not implemented'; - } - - createEvent(eventType) { - throw 'not implemented'; - } - - preventDefault(evt) { - throw 'not implemented'; - } - - isPrevented(evt) { - throw 'not implemented'; - } - - getInnerHTML(el) { - return el.innerHtml; - } - - getOuterHTML(el) { - return el.outerHtml; - } - - String nodeName(node) { - switch (node.nodeType) { - case Node.ELEMENT_NODE: - return (node as Element).localName; - case Node.TEXT_NODE: - return '#text'; - default: - throw 'not implemented for type ${node.nodeType}. ' - 'See http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1950641247' - ' for node types definitions.'; - } - } - - String nodeValue(node) => node.data; - String type(node) { - throw 'not implemented'; - } - - content(node) { - return node; - } - - firstChild(el) => el is NodeList ? el.first : el.firstChild; - - nextSibling(el) { - final parentNode = el.parentNode; - if (parentNode == null) return null; - final siblings = parentNode.nodes; - final index = siblings.indexOf(el); - if (index < siblings.length - 1) { - return siblings[index + 1]; - } - return null; - } - - parentElement(el) { - return el.parent; - } - - List childNodes(el) => el.nodes; - List childNodesAsList(el) => el.nodes; - clearNodes(el) { - el.nodes.forEach((e) => e.remove()); - } - - appendChild(el, node) => el.append(node.remove()); - removeChild(el, node) { - throw 'not implemented'; - } - - remove(el) => el.remove(); - insertBefore(el, node) { - if (el.parent == null) throw '$el must have a parent'; - el.parent.insertBefore(node, el); - } - - insertAllBefore(el, nodes) { - throw 'not implemented'; - } - - insertAfter(el, node) { - throw 'not implemented'; - } - - setInnerHTML(el, value) { - el.innerHtml = value; - } - - getText(el) { - return el.text; - } - - setText(el, String value) => el.text = value; - - getValue(el) { - throw 'not implemented'; - } - - setValue(el, String value) { - throw 'not implemented'; - } - - getChecked(el) { - throw 'not implemented'; - } - - setChecked(el, bool value) { - throw 'not implemented'; - } - - createComment(String text) => new Comment(text); - createTemplate(String html) => createElement('template')..innerHtml = html; - createElement(tagName, [doc]) { - return new Element.tag(tagName); - } - - createElementNS(ns, tagName, [doc]) { - throw 'not implemented'; - } - - createTextNode(String text, [doc]) => new Text(text); - - createScriptTag(String attrName, String attrValue, [doc]) { - throw 'not implemented'; - } - - createStyleElement(String css, [doc]) { - throw 'not implemented'; - } - - createShadowRoot(el) { - throw 'not implemented'; - } - - getShadowRoot(el) { - throw 'not implemented'; - } - - getHost(el) { - throw 'not implemented'; - } - - clone(node) => node.clone(true); - getElementsByClassName(element, String name) { - throw 'not implemented'; - } - - getElementsByTagName(element, String name) { - throw 'not implemented'; - } - - List classList(element) => element.classes.toList(); - - addClass(element, String className) { - element.classes.add(className); - } - - removeClass(element, String className) { - throw 'not implemented'; - } - - hasClass(element, String className) => element.classes.contains(className); - - setStyle(element, String styleName, String styleValue) { - throw 'not implemented'; - } - - bool hasStyle(Element element, String styleName, [String styleValue]) { - throw 'not implemented'; - } - - removeStyle(element, String styleName) { - throw 'not implemented'; - } - - getStyle(element, String styleName) { - throw 'not implemented'; - } - - String tagName(element) => element.localName; - - attributeMap(element) { - // `attributes` keys can be {@link AttributeName}s. - var map = {}; - element.attributes.forEach((key, value) { - map['$key'] = value; - }); - return map; - } - - hasAttribute(element, String attribute) { - // `attributes` keys can be {@link AttributeName}s. - return element.attributes.keys.any((key) => '$key' == attribute); - } - - hasAttributeNS(element, String ns, String attribute) { - throw 'not implemented'; - } - - getAttribute(element, String attribute) { - // `attributes` keys can be {@link AttributeName}s. - var key = element.attributes.keys.firstWhere((key) => '$key' == attribute, - orElse: () {}); - return element.attributes[key]; - } - - getAttributeNS(element, String ns, String attribute) { - throw 'not implemented'; - } - - setAttribute(element, String name, String value) { - element.attributes[name] = value; - } - - setAttributeNS(element, String ns, String name, String value) { - throw 'not implemented'; - } - - removeAttribute(element, String attribute) { - element.attributes.remove(attribute); - } - - removeAttributeNS(element, String ns, String attribute) { - throw 'not implemented'; - } - - templateAwareRoot(el) => el; - - createHtmlDocument() { - throw 'not implemented'; - } - - defaultDoc() { - throw 'not implemented'; - } - - bool elementMatches(n, String selector) { - throw 'not implemented'; - } - - bool isTemplateElement(Element el) { - return el != null && el.localName.toLowerCase() == 'template'; - } - - bool isTextNode(node) => node.nodeType == Node.TEXT_NODE; - bool isCommentNode(node) => node.nodeType == Node.COMMENT_NODE; - - bool isElementNode(node) => node.nodeType == Node.ELEMENT_NODE; - - bool hasShadowRoot(node) { - throw 'not implemented'; - } - - bool isShadowRoot(node) { - throw 'not implemented'; - } - - importIntoDoc(node) { - throw 'not implemented'; - } - - adoptNode(node) { - throw 'not implemented'; - } - - String getHref(element) { - throw 'not implemented'; - } - - void resolveAndSetHref(element, baseUrl, href) { - throw 'not implemented'; - } - - List getDistributedNodes(Node) { - throw 'not implemented'; - } - - bool supportsDOMEvents() { - return false; - } - - bool supportsNativeShadowDOM() { - return false; - } - - bool supportsWebAnimation() { - return false; - } - - getHistory() { - throw 'not implemented'; - } - - getLocation() { - throw 'not implemented'; - } - - getBaseHref() { - throw 'not implemented'; - } - - resetBaseElement() { - throw 'not implemented'; - } - - String getUserAgent() { - return 'Angular 2 Dart Transformer'; - } - - void setData(Element element, String name, String value) { - this.setAttribute(element, 'data-${name}', value); - } - - getComputedStyle(element) { - throw 'not implemented'; - } - - String getData(Element element, String name) { - return this.getAttribute(element, 'data-${name}'); - } - - // TODO(tbosch): move this into a separate environment class once we have it - setGlobalVar(String name, value) { - // noop on the server - } - - requestAnimationFrame(callback) { - throw 'not implemented'; - } - - cancelAnimationFrame(id) { - throw 'not implemented'; - } - - performanceNow() { - throw 'not implemented'; - } - - getAnimationPrefix() { - throw 'not implemented'; - } - - getTransitionEnd() { - throw 'not implemented'; - } - - supportsAnimation() { - throw 'not implemented'; - } - - DomAnimatePlayer animate(element, keyframes, options) { - throw 'not implemented'; - } -} diff --git a/modules/@angular/platform-server/src/html_adapter.dart b/modules/@angular/platform-server/src/html_adapter.dart deleted file mode 100644 index 3e00cea312..0000000000 --- a/modules/@angular/platform-server/src/html_adapter.dart +++ /dev/null @@ -1,25 +0,0 @@ -library angular2.dom.htmlAdapter; - -import 'abstract_html_adapter.dart'; -import 'package:angular2/platform/common_dom.dart'; -import 'dart:io'; - -class Html5LibDomAdapter extends AbstractHtml5LibAdapter { - static void makeCurrent() { - setRootDomAdapter(new Html5LibDomAdapter()); - } - - logError(errorMessage) { - stderr.writeln('${errorMessage}'); - } - - log(message) { - stdout.writeln('${message}'); - } - - logGroup(message) { - stdout.writeln('${message}'); - } - - logGroupEnd() {} -} diff --git a/modules/@angular/platform-server/src/parse5_adapter.dart b/modules/@angular/platform-server/src/parse5_adapter.dart deleted file mode 100644 index 615105394f..0000000000 --- a/modules/@angular/platform-server/src/parse5_adapter.dart +++ /dev/null @@ -1,3 +0,0 @@ -library angular2.src.dom.parse5_adapter; - -// no dart implementation diff --git a/modules/@angular/platform-server/testing/server.dart b/modules/@angular/platform-server/testing/server.dart deleted file mode 100644 index a46a40721f..0000000000 --- a/modules/@angular/platform-server/testing/server.dart +++ /dev/null @@ -1 +0,0 @@ -// Intentionally blank, the Parse5Adapater bindings for JavaScript don't apply. diff --git a/modules/@angular/pubspec.yaml b/modules/@angular/pubspec.yaml deleted file mode 100644 index 5f49b08a75..0000000000 --- a/modules/@angular/pubspec.yaml +++ /dev/null @@ -1,35 +0,0 @@ -name: angular2 -version: <%= packageJson.version %> -authors: -<%= Object.keys(packageJson.contributors).map(function(name) { - return '- '+name+' <'+packageJson.contributors[name]+'>'; -}).join('\n') %> -description: Angular 2 for Dart - a web framework for modern web apps -homepage: <%= packageJson.homepage %> -environment: - sdk: '>=1.10.0 <2.0.0' -dependencies: - analyzer: '>=0.24.4 <0.28.0' - barback: '^0.15.2+2' - dart_style: '>=0.1.8 <0.3.0' - glob: '^1.0.0' - html: '^0.12.0' - intl: '^0.12.4' - logging: '>=0.9.0 <0.12.0' - observe: '^0.13.1' - path: '^1.0.0' - protobuf: '0.5.1' - source_span: '^1.0.0' - stack_trace: '^1.1.1' - build: '>=0.0.1' -dev_dependencies: - transformer_test: '^0.2.0' - guinness: '^0.1.18' - guinness2: '0.0.5' - quiver: '^0.21.4' - test: '^0.12.6' -transformers: -- angular2/transform/codegen -- $dart2js: - commandLineOptions: - - --show-package-warnings diff --git a/modules/@angular/router-deprecated/core_private.dart b/modules/@angular/router-deprecated/core_private.dart deleted file mode 100644 index 309077433f..0000000000 --- a/modules/@angular/router-deprecated/core_private.dart +++ /dev/null @@ -1 +0,0 @@ -export '../core/private_export.dart'; diff --git a/modules/@angular/router-deprecated/src/interfaces.ts b/modules/@angular/router-deprecated/src/interfaces.ts index d19928129e..8c52db43f3 100644 --- a/modules/@angular/router-deprecated/src/interfaces.ts +++ b/modules/@angular/router-deprecated/src/interfaces.ts @@ -15,7 +15,6 @@ import {ComponentInstruction} from './instruction'; // TODO(rado): find a better way to fix this, or remove if likely culprit // https://github.com/systemjs/systemjs/issues/487 gets closed. var __ignore_me = global; -var __make_dart_analyzer_happy: Promise = null; /** * Defines route lifecycle method `routerOnActivate`, which is called by the router at the end of a diff --git a/modules/@angular/router-deprecated/src/lifecycle/lifecycle_annotations.dart b/modules/@angular/router-deprecated/src/lifecycle/lifecycle_annotations.dart deleted file mode 100644 index 232e19b12c..0000000000 --- a/modules/@angular/router-deprecated/src/lifecycle/lifecycle_annotations.dart +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This indirection is needed for TS compilation path. - * See comment in lifecycle_annotations.ts. - */ - -library angular2.router.lifecycle_annotations; - -export "./lifecycle_annotations_impl.dart"; diff --git a/modules/@angular/router-deprecated/src/lifecycle/route_lifecycle_reflector.dart b/modules/@angular/router-deprecated/src/lifecycle/route_lifecycle_reflector.dart deleted file mode 100644 index 99c576d19a..0000000000 --- a/modules/@angular/router-deprecated/src/lifecycle/route_lifecycle_reflector.dart +++ /dev/null @@ -1,38 +0,0 @@ -library angular.router.route_lifecycle_reflector; - -import 'package:angular2/src/router/lifecycle/lifecycle_annotations_impl.dart'; -import 'package:angular2/src/router/interfaces.dart'; -import 'package:angular2/src/core/reflection/reflection.dart'; - -bool hasLifecycleHook(RouteLifecycleHook e, type) { - if (type is! Type) return false; - - final List interfaces = reflector.interfaces(type); - var interface; - - if (e == routerOnActivate) { - interface = OnActivate; - } else if (e == routerOnDeactivate) { - interface = OnDeactivate; - } else if (e == routerOnReuse) { - interface = OnReuse; - } else if (e == routerCanDeactivate) { - interface = CanDeactivate; - } else if (e == routerCanReuse) { - interface = CanReuse; - } - - return interfaces.contains(interface); -} - -Function getCanActivateHook(type) { - final List annotations = reflector.annotations(type); - - for (var annotation in annotations) { - if (annotation is CanActivate) { - return annotation.fn; - } - } - - return null; -} diff --git a/modules/@angular/router-deprecated/src/route_config/route_config_decorator.dart b/modules/@angular/router-deprecated/src/route_config/route_config_decorator.dart deleted file mode 100644 index 6e64fe392d..0000000000 --- a/modules/@angular/router-deprecated/src/route_config/route_config_decorator.dart +++ /dev/null @@ -1,3 +0,0 @@ -library angular2.router.route_config_decorator; - -export './route_config_impl.dart'; diff --git a/modules/@angular/router-deprecated/src/route_config/route_config_impl.ts b/modules/@angular/router-deprecated/src/route_config/route_config_impl.ts index 6258c9dcad..fb1b074a09 100644 --- a/modules/@angular/router-deprecated/src/route_config/route_config_impl.ts +++ b/modules/@angular/router-deprecated/src/route_config/route_config_impl.ts @@ -12,8 +12,6 @@ import {RegexSerializer} from '../rules/route_paths/regex_route_path'; export {RouteDefinition} from '../route_definition'; -var __make_dart_analyzer_happy: Promise = null; - /** * The `RouteConfig` decorator defines routes for a given component. * diff --git a/modules/@angular/router-deprecated/src/route_config/route_config_normalizer.dart b/modules/@angular/router-deprecated/src/route_config/route_config_normalizer.dart deleted file mode 100644 index 60bc1516d0..0000000000 --- a/modules/@angular/router-deprecated/src/route_config/route_config_normalizer.dart +++ /dev/null @@ -1,30 +0,0 @@ -library angular2.src.router.route_config_normalizer; - -import "route_config_decorator.dart"; -import "../route_definition.dart"; -import "../route_registry.dart"; -import "package:angular2/src/facade/lang.dart"; -import "package:angular2/src/facade/exceptions.dart" show BaseException; - -RouteDefinition normalizeRouteConfig(RouteDefinition config, RouteRegistry registry) { - if (config is AsyncRoute) { - - configRegistryAndReturnType(componentType) { - registry.configFromComponent(componentType); - return componentType; - } - - loader() { - return config.loader().then(configRegistryAndReturnType); - } - return new AsyncRoute(path: config.path, loader: loader, name: config.name, data: config.data, useAsDefault: config.useAsDefault); - } - return config; -} - -void assertComponentExists(Type component, String path) { - if (component == null) { - throw new BaseException( - 'Component for route "${path}" is not defined, or is not a class.'); - } -} diff --git a/modules/@angular/router-deprecated/src/route_definition.dart b/modules/@angular/router-deprecated/src/route_definition.dart deleted file mode 100644 index 343b466d2f..0000000000 --- a/modules/@angular/router-deprecated/src/route_definition.dart +++ /dev/null @@ -1,11 +0,0 @@ -library angular2.src.router.route_definition; - -abstract class RouteDefinition { - final String path; - final String name; - final bool useAsDefault; - final String regex; - final List regex_group_names; - final Function serializer; - const RouteDefinition({this.path, this.name, this.useAsDefault : false, this.regex, this.regex_group_names, this.serializer}); -} diff --git a/modules/@angular/router-deprecated/test/route_config/route_config_spec.dart b/modules/@angular/router-deprecated/test/route_config/route_config_spec.dart deleted file mode 100644 index d2951cfc90..0000000000 --- a/modules/@angular/router-deprecated/test/route_config/route_config_spec.dart +++ /dev/null @@ -1,9 +0,0 @@ -library angular2.test.router.route_config_spec; - -/** - * This is intentionally left blank. `route_config_spec.ts` contains tests specific - * to using untyped objects for users writing idiomatic ES5 or TS. - * The rest of the router tests have typed annotations, so there's no need to add - * additional tests here for Dart. - */ -main() {} diff --git a/modules/@angular/router-deprecated/test/spies.dart b/modules/@angular/router-deprecated/test/spies.dart deleted file mode 100644 index da5df6692d..0000000000 --- a/modules/@angular/router-deprecated/test/spies.dart +++ /dev/null @@ -1,20 +0,0 @@ -library router.spies; - -import 'package:angular2/platform/common.dart' show PlatformLocation, Location; -import 'package:angular2/router.dart'; -import 'package:angular2/testing_internal.dart'; - -@proxy -class SpyLocation extends SpyObject implements Location {} - -@proxy -class SpyRouter extends SpyObject implements Router {} - -@proxy -class SpyRouterOutlet extends SpyObject implements RouterOutlet {} - -class SpyPlatformLocation extends SpyObject implements PlatformLocation { - String pathname = null; - String search = null; - String hash = null; -} diff --git a/modules/benchmarks/e2e_test/compiler_perf.dart b/modules/benchmarks/e2e_test/compiler_perf.dart deleted file mode 100644 index 5342391aef..0000000000 --- a/modules/benchmarks/e2e_test/compiler_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.compiler_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/costs_perf.dart b/modules/benchmarks/e2e_test/costs_perf.dart deleted file mode 100644 index 1e35ad0b2b..0000000000 --- a/modules/benchmarks/e2e_test/costs_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.costs_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/di_perf.dart b/modules/benchmarks/e2e_test/di_perf.dart deleted file mode 100644 index 0199cf1ef7..0000000000 --- a/modules/benchmarks/e2e_test/di_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.di_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/largetable_perf.dart b/modules/benchmarks/e2e_test/largetable_perf.dart deleted file mode 100644 index 4fe65518a3..0000000000 --- a/modules/benchmarks/e2e_test/largetable_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.largetable_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.dart b/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.dart deleted file mode 100644 index f619c0e170..0000000000 --- a/modules/benchmarks/e2e_test/naive_infinite_scroll_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.naive_infinite_scroll_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.dart b/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.dart deleted file mode 100644 index ff8fad6244..0000000000 --- a/modules/benchmarks/e2e_test/naive_infinite_scroll_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.naive_infinite_scroll_spec; - -main() {} diff --git a/modules/benchmarks/e2e_test/page_load_perf.dart b/modules/benchmarks/e2e_test/page_load_perf.dart deleted file mode 100644 index 4b036c58d9..0000000000 --- a/modules/benchmarks/e2e_test/page_load_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.page_load_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/selector_perf.dart b/modules/benchmarks/e2e_test/selector_perf.dart deleted file mode 100644 index f630bf6694..0000000000 --- a/modules/benchmarks/e2e_test/selector_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.selector_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/static_tree_perf.dart b/modules/benchmarks/e2e_test/static_tree_perf.dart deleted file mode 100644 index 1e61c7222a..0000000000 --- a/modules/benchmarks/e2e_test/static_tree_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.static_tree_perf; - -main() {} diff --git a/modules/benchmarks/e2e_test/tree_perf.dart b/modules/benchmarks/e2e_test/tree_perf.dart deleted file mode 100644 index 807e3ae10c..0000000000 --- a/modules/benchmarks/e2e_test/tree_perf.dart +++ /dev/null @@ -1,3 +0,0 @@ -library benchmarks.e2e_test.tree_perf; - -main() {} diff --git a/modules/benchmarks/pubspec.yaml b/modules/benchmarks/pubspec.yaml deleted file mode 100644 index cfef72a9bb..0000000000 --- a/modules/benchmarks/pubspec.yaml +++ /dev/null @@ -1,38 +0,0 @@ -name: angular2_benchmarks -version: <%= packageJson.version %> -authors: -<%= Object.keys(packageJson.contributors).map(function(name) { - return '- '+name+' <'+packageJson.contributors[name]+'>'; -}).join('\n') %> -description: Angular2 benchmarks -homepage: <%= packageJson.homepage %> -environment: - sdk: '>=1.10.0 <2.0.0' -dependencies: - angular2: '^<%= packageJson.version %>' - browser: '^0.10.0' -dependency_overrides: - angular2: - path: ../angular2 -transformers: -- angular2/transform/codegen -- angular2/transform/reflection_remover: - $include: - - web/src/compiler/compiler_benchmark.dart - - web/src/costs/index.dart - - web/src/di/di_benchmark.dart - - web/src/element_injector/element_injector_benchmark.dart - - web/src/largetable/largetable_benchmark.dart - - web/src/naive_infinite_scroll/index.dart - - web/src/static_tree/tree_benchmark.dart - - web/src/tree/tree_benchmark.dart - - web/src/page_load/page_load.dart -- $dart2js: - $include: web/src/** - minify: false - commandLineOptions: - - --dump-info - - --trust-type-annotations - - --trust-primitives - - --show-package-warnings - - --fatal-warnings diff --git a/modules/benchmarks/src/page_load/page_load.dart b/modules/benchmarks/src/page_load/page_load.dart deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/modules/playground/e2e_test/async/async_spec.dart b/modules/playground/e2e_test/async/async_spec.dart deleted file mode 100644 index d22b138845..0000000000 --- a/modules/playground/e2e_test/async/async_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.async_spec; - -main() {} diff --git a/modules/playground/e2e_test/hash_routing/hash_location_spec.dart b/modules/playground/e2e_test/hash_routing/hash_location_spec.dart deleted file mode 100644 index fcd80886f2..0000000000 --- a/modules/playground/e2e_test/hash_routing/hash_location_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.hash_location_spec; - -main() {} diff --git a/modules/playground/e2e_test/hello_world/hello_world_spec.dart b/modules/playground/e2e_test/hello_world/hello_world_spec.dart deleted file mode 100644 index c43dc53e2b..0000000000 --- a/modules/playground/e2e_test/hello_world/hello_world_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.hello_world.hello_world_spec; - -main() {} diff --git a/modules/playground/e2e_test/http/http_spec.dart b/modules/playground/e2e_test/http/http_spec.dart deleted file mode 100644 index 9890d16056..0000000000 --- a/modules/playground/e2e_test/http/http_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.http.http_spec; - -main() {} diff --git a/modules/playground/e2e_test/jsonp/jsonp_spec.dart b/modules/playground/e2e_test/jsonp/jsonp_spec.dart deleted file mode 100644 index 2521c6ff50..0000000000 --- a/modules/playground/e2e_test/jsonp/jsonp_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.jsonp.jsonp_spec; - -main() {} diff --git a/modules/playground/e2e_test/key_events/key_events_spec.dart b/modules/playground/e2e_test/key_events/key_events_spec.dart deleted file mode 100644 index bd88bd98bd..0000000000 --- a/modules/playground/e2e_test/key_events/key_events_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.key_events.key_events_spec; - -main() {} diff --git a/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.dart b/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.dart deleted file mode 100644 index f9a6083fd7..0000000000 --- a/modules/playground/e2e_test/model_driven_forms/model_driven_forms_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.hello_world.model_driven_forms_spec; - -main() {} diff --git a/modules/playground/e2e_test/order_management/order_management_spec.dart b/modules/playground/e2e_test/order_management/order_management_spec.dart deleted file mode 100644 index 25c30c7023..0000000000 --- a/modules/playground/e2e_test/order_management/order_management_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.order_management_spec; - -main() {} diff --git a/modules/playground/e2e_test/person_management/person_management_spec.dart b/modules/playground/e2e_test/person_management/person_management_spec.dart deleted file mode 100644 index 6f2663b16f..0000000000 --- a/modules/playground/e2e_test/person_management/person_management_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.person_management_spec; - -main() {} diff --git a/modules/playground/e2e_test/relative_assets/assets_spec.dart b/modules/playground/e2e_test/relative_assets/assets_spec.dart deleted file mode 100644 index 200a722456..0000000000 --- a/modules/playground/e2e_test/relative_assets/assets_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.relative_assets.assets_spec; - -main() {} diff --git a/modules/playground/e2e_test/routing/routing_spec.dart b/modules/playground/e2e_test/routing/routing_spec.dart deleted file mode 100644 index 8c1c7fd661..0000000000 --- a/modules/playground/e2e_test/routing/routing_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.routing.routing_spec; - -main() {} diff --git a/modules/playground/e2e_test/routing_deprecated/routing_deprecated_spec.dart b/modules/playground/e2e_test/routing_deprecated/routing_deprecated_spec.dart deleted file mode 100644 index 8c1c7fd661..0000000000 --- a/modules/playground/e2e_test/routing_deprecated/routing_deprecated_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.routing.routing_spec; - -main() {} diff --git a/modules/playground/e2e_test/sourcemap/sourcemap_spec.dart b/modules/playground/e2e_test/sourcemap/sourcemap_spec.dart deleted file mode 100644 index cff45146db..0000000000 --- a/modules/playground/e2e_test/sourcemap/sourcemap_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.sourcemap.sourcemap_spec; - -main() {} diff --git a/modules/playground/e2e_test/svg/svg_spec.dart b/modules/playground/e2e_test/svg/svg_spec.dart deleted file mode 100644 index 2d253782ac..0000000000 --- a/modules/playground/e2e_test/svg/svg_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.svg.svg_spec; - -main() {} diff --git a/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.dart b/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.dart deleted file mode 100644 index e8d50701ef..0000000000 --- a/modules/playground/e2e_test/template_driven_forms/template_driven_forms_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.hello_world.template_driven_forms_spec; - -main() {} diff --git a/modules/playground/e2e_test/web_workers/input/input_spec.dart b/modules/playground/e2e_test/web_workers/input/input_spec.dart deleted file mode 100644 index ac6b852b05..0000000000 --- a/modules/playground/e2e_test/web_workers/input/input_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.web_workers.input_spec; - -main() {} diff --git a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.dart b/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.dart deleted file mode 100644 index bd9deff9b1..0000000000 --- a/modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.web_workers.kitchen_sink_spec; - -main() {} diff --git a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.dart b/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.dart deleted file mode 100644 index b606f0f369..0000000000 --- a/modules/playground/e2e_test/web_workers/message_broker/message_broker_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.message_bus; - -main() {} diff --git a/modules/playground/e2e_test/web_workers/router/router_spec.dart b/modules/playground/e2e_test/web_workers/router/router_spec.dart deleted file mode 100644 index 87b2b59cb0..0000000000 --- a/modules/playground/e2e_test/web_workers/router/router_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.web_workers.router.router_spec; - -main() {} diff --git a/modules/playground/e2e_test/web_workers/todo/todo_spec.dart b/modules/playground/e2e_test/web_workers/todo/todo_spec.dart deleted file mode 100644 index 36d8df17da..0000000000 --- a/modules/playground/e2e_test/web_workers/todo/todo_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.web_workers.todo_spec; - -main() {} diff --git a/modules/playground/e2e_test/zippy_component/zippy_spec.dart b/modules/playground/e2e_test/zippy_component/zippy_spec.dart deleted file mode 100644 index 480b07867c..0000000000 --- a/modules/playground/e2e_test/zippy_component/zippy_spec.dart +++ /dev/null @@ -1,3 +0,0 @@ -library playground.e2e_test.zippy_component.zippy_spec; - -main() {} diff --git a/modules/playground/pubspec.yaml b/modules/playground/pubspec.yaml deleted file mode 100644 index deb98d894f..0000000000 --- a/modules/playground/pubspec.yaml +++ /dev/null @@ -1,81 +0,0 @@ -name: playground -environment: - sdk: '>=1.10.0 <2.0.0' -dependencies: - observe: '^0.13.1' - angular2: '^<%= packageJson.version %>' - browser: '^0.10.0' -dev_dependencies: - guinness2: '0.0.5' - benchpress: - path: ../benchpress -dependency_overrides: - angular2: - path: ../angular2 - matcher: '0.12.0+1' -transformers: -- angular2/transform/codegen: - platform_directives: 'package:angular2/src/common/directives.dart#CORE_DIRECTIVES' -- angular2/transform/reflection_remover: - $include: - - web/src/animate/index.dart - - web/src/async/index.dart - - web/src/gestures/index.dart - - web/src/hash_routing/index.dart - - web/src/hello_world/index.dart - - web/src/key_events/index.dart - - web/src/model_driven_forms/index.dart - - web/src/observable_models/index.dart - - web/src/order_management/index.dart - - web/src/person_management/index.dart - - web/src/relative_assets/index.dart - - web/src/routing/index.dart - - web/src/sourcemap/index.dart - - web/src/svg/index.dart - - web/src/template_driven_forms/index.dart - - web/src/todo/index.dart - - web/src/web_workers/kitchen_sink/background_index.dart - - web/src/web_workers/kitchen_sink/index.dart - - web/src/web_workers/message_broker/background_index.dart - - web/src/web_workers/message_broker/index.dart - - web/src/web_workers/todo/background_index.dart - - web/src/web_workers/todo/index.dart - - web/src/web_workers/todo/server_index.dart - - web/src/web_workers/router/index.dart - - web/src/web_workers/router/background_index.dart - - web/src/web_workers/input/index.dart - - web/src/web_workers/input/background_index.dart - - web/src/zippy_component/index.dart -- angular2/transform/deferred_rewriter: - # No playground apps use deferred imports, but in general - # all libraries with deferred imports should be included. - $include: [] - -- $dart2js: - $include: - - web/src/** - $exclude: - # web worker code compiled separately; see below - - web/src/web_workers/** - minify: false - commandLineOptions: - - --show-package-warnings - - --trust-type-annotations - - --trust-primitives - - --enable-experimental-mirrors - - --fatal-warnings - -# TODO(yjbanov): cannot use --fatal-warnings on web-worker code due to -# dart2js bug https://github.com/dart-lang/sdk/issues/23875 -- $dart2js: - $include: - - web/src/web_workers/** - $exclude: - - web/src/web_workers/images/** - - web/src/web_workers/todo/server_index.dart - minify: false - commandLineOptions: - - --show-package-warnings - - --trust-type-annotations - - --trust-primitives - - --enable-experimental-mirrors diff --git a/modules/playground/src/relative_assets/app/my_cmp.dart b/modules/playground/src/relative_assets/app/my_cmp.dart deleted file mode 100644 index 2f097936e3..0000000000 --- a/modules/playground/src/relative_assets/app/my_cmp.dart +++ /dev/null @@ -1,9 +0,0 @@ -import 'package:angular2/core.dart' show Component; - -@Component( - selector: 'my-cmp', - templateUrl: 'tpl.html', - styleUrls: const ['style.css'] -) -class MyCmp { -} diff --git a/modules/playground/src/upgrade/index.dart b/modules/playground/src/upgrade/index.dart deleted file mode 100644 index d9a5117bcd..0000000000 --- a/modules/playground/src/upgrade/index.dart +++ /dev/null @@ -1,5 +0,0 @@ -library angualr2.playground.upgrade.index; - -main() { - // do nothing -} diff --git a/modules/playground/src/web_workers/images/background_index.dart b/modules/playground/src/web_workers/images/background_index.dart deleted file mode 100644 index 554e526d4c..0000000000 --- a/modules/playground/src/web_workers/images/background_index.dart +++ /dev/null @@ -1,13 +0,0 @@ -library playground.src.web_workers.images.background_index; - -import "index_common.dart" show ImageDemo; -import "dart:isolate"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; -import "package:angular2/src/core/reflection/reflection_capabilities.dart"; -import "package:angular2/src/core/reflection/reflection.dart"; - -main(List args, SendPort replyTo) { - reflector.reflectionCapabilities = new ReflectionCapabilities(); - bootstrapApp(replyTo, ImageDemo); -} diff --git a/modules/playground/src/web_workers/images/file_api.dart b/modules/playground/src/web_workers/images/file_api.dart deleted file mode 100644 index ad0b5da1bc..0000000000 --- a/modules/playground/src/web_workers/images/file_api.dart +++ /dev/null @@ -1,9 +0,0 @@ -export 'dart:html' show FileReader; - -import 'dart:typed_data'; - -class Uint8ArrayWrapper { - static Uint8ClampedList create(ByteBuffer buffer) { - return new Uint8ClampedList.view(buffer); - } -} diff --git a/modules/playground/src/web_workers/images/index.dart b/modules/playground/src/web_workers/images/index.dart deleted file mode 100644 index fea8f54601..0000000000 --- a/modules/playground/src/web_workers/images/index.dart +++ /dev/null @@ -1,11 +0,0 @@ -library angular2.examples.web_workers.images.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; -import "package:angular2/src/core/reflection/reflection_capabilities.dart"; -import "package:angular2/src/core/reflection/reflection.dart"; - -main() { - reflector.reflectionCapabilities = new ReflectionCapabilities(); - bootstrapRender("background_index.dart"); -} diff --git a/modules/playground/src/web_workers/images/services/bitmap.dart b/modules/playground/src/web_workers/images/services/bitmap.dart deleted file mode 100644 index d5bda53ca8..0000000000 --- a/modules/playground/src/web_workers/images/services/bitmap.dart +++ /dev/null @@ -1,23 +0,0 @@ -library angular2.examples.web_workers.images.bitmap_service; - -import 'dart:html'; -import 'dart:typed_data'; - -// TODO(jteplitz602) Implement this class #3493 -class BitmapService { - ImageData applySepia(ImageData imageData) { - return null; - } - - String arrayBufferToDataUri(Uint8ClampedList data) { - return null; - } - - ImageData convertToImageData(ByteBuffer buffer) { - return null; - } - - String toDataUri(ImageData imageData) { - return null; - } -} diff --git a/modules/playground/src/web_workers/input/background_index.dart b/modules/playground/src/web_workers/input/background_index.dart deleted file mode 100644 index 6a441e5b17..0000000000 --- a/modules/playground/src/web_workers/input/background_index.dart +++ /dev/null @@ -1,11 +0,0 @@ -library playground.src.web_workers.input.background_index; - -import "index_common.dart" show InputCmp; -import "dart:isolate"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main(List args, SendPort replyTo) { - bootstrapApp(replyTo, InputCmp); -} diff --git a/modules/playground/src/web_workers/input/index.dart b/modules/playground/src/web_workers/input/index.dart deleted file mode 100644 index 9d4ff05446..0000000000 --- a/modules/playground/src/web_workers/input/index.dart +++ /dev/null @@ -1,9 +0,0 @@ -library angular2.examples.web_workers.input.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main() { - bootstrapRender("background_index.dart"); -} diff --git a/modules/playground/src/web_workers/kitchen_sink/background_index.dart b/modules/playground/src/web_workers/kitchen_sink/background_index.dart deleted file mode 100644 index 8ca65b5413..0000000000 --- a/modules/playground/src/web_workers/kitchen_sink/background_index.dart +++ /dev/null @@ -1,11 +0,0 @@ -library playground.src.web_workers.kitchen_sink.background_index; - -import "index_common.dart" show HelloCmp; -import "dart:isolate"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main(List args, SendPort replyTo) { - bootstrapApp(replyTo, HelloCmp); -} diff --git a/modules/playground/src/web_workers/kitchen_sink/index.dart b/modules/playground/src/web_workers/kitchen_sink/index.dart deleted file mode 100644 index 7c7a4af15e..0000000000 --- a/modules/playground/src/web_workers/kitchen_sink/index.dart +++ /dev/null @@ -1,9 +0,0 @@ -library angular2.examples.web_workers.kitchen_sink.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main() { - bootstrapRender("background_index.dart"); -} diff --git a/modules/playground/src/web_workers/message_broker/background_index.dart b/modules/playground/src/web_workers/message_broker/background_index.dart deleted file mode 100644 index aac1a08702..0000000000 --- a/modules/playground/src/web_workers/message_broker/background_index.dart +++ /dev/null @@ -1,11 +0,0 @@ -library angular2.examples.message_broker.background_index; - -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; -import "index_common.dart" show App; -import "dart:isolate"; - -@AngularEntrypoint() -main(List args, SendPort replyTo) { - bootstrapApp(replyTo, App); -} diff --git a/modules/playground/src/web_workers/message_broker/index.dart b/modules/playground/src/web_workers/message_broker/index.dart deleted file mode 100644 index e3153aa3b9..0000000000 --- a/modules/playground/src/web_workers/message_broker/index.dart +++ /dev/null @@ -1,23 +0,0 @@ -library angular2.examples.message_broker.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; -import "dart:html"; - -@AngularEntrypoint() -main() { - const ECHO_CHANNEL = "ECHO"; - bootstrapRender("background_index.dart") - .then((ref) { - var brokerFactory = ref.injector.get(ClientMessageBrokerFactory); - var broker = brokerFactory.createMessageBroker(ECHO_CHANNEL, false); - querySelector("#send_echo").addEventListener("click", (e) { - var val = (querySelector("#echo_input") as InputElement).value; - var args = new UiArguments("echo", [new FnArg(val, PRIMITIVE)]); - broker.runOnService(args, PRIMITIVE).then((echo_result) { - querySelector("#echo_result") - .appendHtml("${echo_result}"); - }); - }); - }); -} diff --git a/modules/playground/src/web_workers/router/background_index.dart b/modules/playground/src/web_workers/router/background_index.dart deleted file mode 100644 index d82470bbac..0000000000 --- a/modules/playground/src/web_workers/router/background_index.dart +++ /dev/null @@ -1,13 +0,0 @@ -library playground.src.web_workers.router.background_index; - -import "index_common.dart" show App; -import "dart:isolate"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; -import "package:angular2/platform/common.dart" show LocationStrategy, HashLocationStrategy; -import "package:angular2/src/web_workers/worker/router_providers.dart"; - -@AngularEntrypoint() -main(List args, SendPort replyTo) { - bootstrapApp(replyTo, App, [WORKER_APP_ROUTER, new Provider(LocationStrategy, useClass: HashLocationStrategy)]); -} diff --git a/modules/playground/src/web_workers/router/index.dart b/modules/playground/src/web_workers/router/index.dart deleted file mode 100644 index 0a8d66d5b7..0000000000 --- a/modules/playground/src/web_workers/router/index.dart +++ /dev/null @@ -1,12 +0,0 @@ -library angular2.examples.web_workers.router.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; -import "package:angular2/src/core/reflection/reflection_capabilities.dart"; -import "package:angular2/src/core/reflection/reflection.dart"; - -@AngularEntrypoint() -main() { - reflector.reflectionCapabilities = new ReflectionCapabilities(); - bootstrapRender("background_index.dart", WORKER_RENDER_ROUTER); -} diff --git a/modules/playground/src/web_workers/todo/background_index.dart b/modules/playground/src/web_workers/todo/background_index.dart deleted file mode 100644 index c993676bf3..0000000000 --- a/modules/playground/src/web_workers/todo/background_index.dart +++ /dev/null @@ -1,11 +0,0 @@ -library playground.src.web_workers.todo.background_index; - -import "index_common.dart" show TodoApp; -import "dart:isolate"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main(List args, SendPort replyTo) { - bootstrapApp(replyTo, TodoApp); -} diff --git a/modules/playground/src/web_workers/todo/index.dart b/modules/playground/src/web_workers/todo/index.dart deleted file mode 100644 index cadcbd2706..0000000000 --- a/modules/playground/src/web_workers/todo/index.dart +++ /dev/null @@ -1,9 +0,0 @@ -library angular2.examples.web_workers.todo.index; - -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/core.dart"; - -@AngularEntrypoint() -main() { - bootstrapRender("background_index.dart"); -} diff --git a/modules/playground/src/web_workers/todo/index_web_socket.dart b/modules/playground/src/web_workers/todo/index_web_socket.dart deleted file mode 100644 index 694df99513..0000000000 --- a/modules/playground/src/web_workers/todo/index_web_socket.dart +++ /dev/null @@ -1,24 +0,0 @@ -library angular2.examples.web_workers.todo.index_web_socket; - -import "package:angular2/core.dart"; -import "package:angular2/platform/worker_render.dart"; -import "package:angular2/src/web_workers/debug_tools/web_socket_message_bus.dart"; -import 'dart:html' show WebSocket; - -@AngularEntrypoint() -main() { - var webSocket = new WebSocket("ws://127.0.0.1:1337/ws"); - webSocket.onOpen.listen((e) { - var bus = new WebSocketMessageBus.fromWebSocket(webSocket); - var platform = createPlatform(ReflectiveInjector.resolveAndCreate(WORKER_RENDER_PLATFORM)); - var appInjector = ReflectiveInjector.resolveAndCreate([ - WORKER_RENDER_APPLICATION_COMMON, new Provider(MessageBus, useValue: bus), - new Provider(APP_INITIALIZER, - useFactory: (injector) => () => initializeGenericWorkerRenderer(injector), - deps: [Injector], - multi: true - ) - ], platform.injector); - appInjector.get(ApplicationRef); - }); -} diff --git a/modules/playground/src/web_workers/todo/server_index.dart b/modules/playground/src/web_workers/todo/server_index.dart deleted file mode 100644 index b2b39cffa3..0000000000 --- a/modules/playground/src/web_workers/todo/server_index.dart +++ /dev/null @@ -1,34 +0,0 @@ -library angular2.examples.web_workers.todo.server_index; - -import "index_common.dart" show TodoApp; -import "package:angular2/src/web_workers/debug_tools/multi_client_server_message_bus.dart"; -import "package:angular2/platform/worker_app.dart"; -import "package:angular2/core.dart"; -import 'dart:io'; -import "package:angular2/src/core/reflection/reflection_capabilities.dart"; -import "package:angular2/src/core/reflection/reflection.dart"; -import "package:angular2/src/platform/server/html_adapter.dart"; - -void main() { - reflector.reflectionCapabilities = new ReflectionCapabilities(); - HttpServer.bind('127.0.0.1', 1337).then((HttpServer server) { - print("Server Listening for requests on 127.0.0.1:1337"); - var bus = new MultiClientServerMessageBus.fromHttpServer(server); - - var platform = createPlatform(ReflectiveInjector.resolveAndCreate(WORKER_APP_PLATFORM)); - var appInjector = ReflectiveInjector.resolveAndCreate([ - WORKER_APP_APPLICATION_COMMON, - new Provider(MessageBus, useValue: bus), - new Provider(APP_INITIALIZER, - useFactory: initAppThread, multi: true, deps: [NgZone, MessageBus]) - ], platform.injector); - coreLoadAndBootstrap(TodoApp, appInjector); - }); -} - -initAppThread(NgZone zone, MessageBus bus) { - return () { - Html5LibDomAdapter.makeCurrent(); - bus.attachToZone(zone); - }; -} diff --git a/modules/playground/test/benchpress/webdriver_async.server.spec.dart b/modules/playground/test/benchpress/webdriver_async.server.spec.dart deleted file mode 100644 index f4b10f785b..0000000000 --- a/modules/playground/test/benchpress/webdriver_async.server.spec.dart +++ /dev/null @@ -1,56 +0,0 @@ -import 'dart:async'; -import 'dart:io' show Platform; -import 'package:guinness2/guinness2.dart'; -import 'package:benchpress/benchpress.dart'; -import 'package:webdriver/webdriver.dart' - show WebDriver, Capabilities, LogType, LogLevel, By; - -main() { - describe('benchpress', () { - WebDriver driver; - Runner runner; - - beforeEach(() async { - driver = await createTestDriver(); - await driver - .get('http://localhost:8002/playground/src/benchpress/index.html'); - - var bindings = [{ - provide: WebDriverAdapter, - useFactory: () => new AsyncWebDriverAdapter(driver), - deps: [] - }]; - runner = new Runner(bindings); - }); - - afterEach(() async { - await driver.close(); - }); - - it('should work', () { - return runner.sample(id: 'benchpress smoke test', execute: () async { - var button = await driver.findElement(const By.tagName('button')); - await button.click(); - var logText = await (await driver.findElement(const By.id('log'))).text; - expect(logText, 'hi'); - }); - }); - }); -} - -Future createTestDriver() { - Map env = Platform.environment; - return WebDriver.createDriver(desiredCapabilities: { - 'name': 'Dartium', - 'browserName': 'chrome', - 'chromeOptions': { - 'binary': env['DARTIUM_BIN'], - 'args': ['--js-flags=--expose-gc'], - 'perfLoggingPrefs': { - 'traceCategories': - 'v8,blink.console,disabled-by-default-devtools.timeline' - }, - }, - 'loggingPrefs': {'performance': 'ALL', 'browser': 'ALL',} - }); -} diff --git a/scripts/ci-lite/install.sh b/scripts/ci-lite/install.sh index a1b85c4f31..8347aab9a4 100755 --- a/scripts/ci-lite/install.sh +++ b/scripts/ci-lite/install.sh @@ -61,6 +61,4 @@ $(npm bin)/webdriver-manager update # TODO: install bower packages # bower install -# TODO: install dart packages - echo 'travis_fold:end:INSTALL' diff --git a/scripts/ci/build_dart.sh b/scripts/ci/build_dart.sh deleted file mode 100755 index 16ffc77324..0000000000 --- a/scripts/ci/build_dart.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -set -ex - -echo ============================================================================= -# go to project dir -SCRIPT_DIR=$(dirname $0) -source $SCRIPT_DIR/env_dart.sh -cd $SCRIPT_DIR/../.. - -./node_modules/.bin/gulp build.js.cjs build.dart benchpress.bundle - -pub install diff --git a/scripts/ci/build_dart_ddc.sh b/scripts/ci/build_dart_ddc.sh deleted file mode 100755 index fc2194ea2f..0000000000 --- a/scripts/ci/build_dart_ddc.sh +++ /dev/null @@ -1,170 +0,0 @@ -#!/bin/bash -set -ex - -echo ============================================================================= -echo "DART DEV COMPILER (DDC) BUILD" -echo ============================================================================= - -# go to project dir -SCRIPT_DIR=$(dirname $0) -REPO_ROOT_DIR=`cd ${SCRIPT_DIR}/../..; pwd` -source $SCRIPT_DIR/env_dart.sh -cd $REPO_ROOT_DIR - -# Variables -DDC_TOTAL_WARNING_CAP="100" -DDC_TOTAL_ERROR_CAP="0" -DDC_DIR=`pwd`/tmp/dev_compiler -DDC_VERSION="0.1.24" - -# Get DDC -mkdir -p tmp -rm -rf tmp/dev_compiler -git clone https://github.com/dart-lang/dev_compiler.git tmp/dev_compiler -(cd $DDC_DIR && \ - git checkout tags/$DDC_VERSION && \ - $PUB get) - -# Convert TypeScript to Dart -./node_modules/.bin/gulp build.js.cjs -./node_modules/.bin/gulp build/packages.dart -./node_modules/.bin/gulp build/pubspec.dart -node ./scripts/ci/dart_ddc/pubspec_for_ddc.js \ - --pubspec-file=dist/dart/playground/pubspec.yaml -cd dist/dart/playground -$PUB build --mode=debug -cd build/web - -# TODO: temporarily remove references to dart.js as ddc doesn't do it -# automatically yet (https://github.com/dart-lang/dev_compiler/issues/437) -echo `pwd` -for htmlFile in `find ./src -name '*.html'`; do - tmpFile=$REPO_ROOT_DIR/tmp/scriptless_html.tmp - cat $htmlFile | grep -vE '$tmpFile - mv $tmpFile $htmlFile -done - -############################################################################## -# Analyze code -############################################################################## - -LOG_FILE="analyzer.log" -set +e -$DART_SDK/bin/dart $DDC_DIR/bin/dartdevc.dart \ - --dart-sdk=$DART_SDK_LIB_SEARCH_PATH -o out \ - src/animate/index.dart \ - src/async/index.dart \ - src/gestures/index.dart \ - src/hash_routing/index.dart \ - src/hello_world/index.dart \ - src/key_events/index.dart \ - src/model_driven_forms/index.dart \ - src/observable_models/index.dart \ - src/order_management/index.dart \ - src/person_management/index.dart \ - src/relative_assets/index.dart \ - src/routing/index.dart \ - src/sourcemap/index.dart \ - src/svg/index.dart \ - src/template_driven_forms/index.dart \ - src/todo/index.dart \ - src/zippy_component/index.dart \ - >$LOG_FILE -EXIT_CODE=`echo $?` -set -e - -# Analyzer exits with 1 when there are warnings and something crazy -# like 255 when it crashes. We don't want to fail the build if its -# only warnings (until our code is warning-free). -if [[ "$EXIT_CODE" -ne "0" && "$EXIT_CODE" -ne "1" ]] -then - echo "DDC compiler crashed with exit code $EXIT_CODE" - exit 1 -fi - -cat $LOG_FILE -EXIT_CODE=0 - -# TODO remove `grep -v template.dart` after Tobias new compiler lands. - -WARNING_COUNT=$(cat $LOG_FILE | grep -E '^warning.*' | wc -l | sed -e 's/^[[:space:]]*//' || true) -ERROR_COUNT=$(cat $LOG_FILE | grep -E '^severe.*' | wc -l | sed -e 's/^[[:space:]]*//' || true) - - -if [[ "$ERROR_COUNT" -gt "$DDC_TOTAL_ERROR_CAP" ]] -then - echo "Found severe errors in angular2 package" - EXIT_CODE=1 -fi - -if [[ "$WARNING_COUNT" -gt "$DDC_TOTAL_WARNING_CAP" ]] -then - echo "Too many warnings: $WARNING_COUNT" - EXIT_CODE=1 -else - echo "Warning count ok" -fi - - -############################################################################## -# Run e2e tests -############################################################################## - -DIST_DIR="${REPO_ROOT_DIR}/dist/js/ddc" - -# Build the apps (again) -# TODO: ddc does not yet support compiling multiple html files. Ideally we -# could build everything during analysis above. -# See: https://github.com/dart-lang/dev_compiler/issues/430 - -ln -s `pwd`/packages src/hello_world/packages - -set +e -OUT_DIR="${DIST_DIR}/playground/src/hello_world" -mkdir -p $OUT_DIR -$DART_SDK/bin/dart $DDC_DIR/bin/dartdevc.dart \ - --force-compile \ - --dart-sdk=$DART_SDK_LIB_SEARCH_PATH -o $OUT_DIR \ - src/hello_world/index.html -EXIT_CODE=`echo $?` -set -e - -if [[ "$EXIT_CODE" -ne "0" && "$EXIT_CODE" -ne "1" ]] -then - echo "DDC compiler crashed with exit code $EXIT_CODE" - exit 1 -fi - - -# Run e2e tests -cd $REPO_ROOT_DIR - -./node_modules/.bin/webdriver-manager update - -function killServer () { - kill $serverPid -} - -./node_modules/.bin/gulp serve.js.ddc& -serverPid=$! - -echo CHROM_BIN=$CHROME_BIN -echo CHROM_BIN_VERSION=`$CHROME_BIN --version` - -trap killServer EXIT - -# wait for server to come up -sleep 10 - -function runSpec { - SPEC=$1 - ./node_modules/.bin/protractor protractor-ddc.conf.js \ - --browsers=${E2E_BROWSERS:-ChromeDesktop} \ - --spec=$SPEC -} - -# TODO: add more e2e tests -runSpec hello_world/hello_world_spec.js - -echo 'Dart DDC build finished' -exit $EXIT_CODE diff --git a/scripts/ci/dart_ddc/pubspec_for_ddc.js b/scripts/ci/dart_ddc/pubspec_for_ddc.js deleted file mode 100644 index 2475e50006..0000000000 --- a/scripts/ci/dart_ddc/pubspec_for_ddc.js +++ /dev/null @@ -1,25 +0,0 @@ -// Removes dart2js from pubspec.yaml for faster building -// Usage: node pubspec_for_ddc.js --pubspec-file=PATH_TO_PUBSPEC_YAML - -var fs = require('fs'); -var yaml = require('js-yaml'); -var yargs = require('yargs'); - -var pubspecFileOpt = 'pubspec-file'; -var pubspecFile = yargs - .demand([pubspecFileOpt]) - .argv[pubspecFileOpt]; - -var doc = yaml.safeLoad(fs.readFileSync(pubspecFile, 'utf8')); - -var transformers = doc['transformers']; -if (transformers) { - transformers.forEach(function (transformer) { - var dart2js = transformer['\$dart2js']; - if (dart2js) { - dart2js['$exclude'] = [ 'web/**/*' ]; - } - }); -} - -fs.writeFileSync(pubspecFile, yaml.safeDump(doc)); diff --git a/scripts/ci/env_dart.sh b/scripts/ci/env_dart.sh deleted file mode 100755 index 5e6aa481ae..0000000000 --- a/scripts/ci/env_dart.sh +++ /dev/null @@ -1,101 +0,0 @@ -#!/bin/bash -set -e -o pipefail - -if [[ -z $ENV_SET ]]; then - export ENV_SET=1 - - # Map DART_SDK and DARTSDK to each other if only one is specified. - # - # TODO(chirayu): Remove this legacy DARTSDK variable support. Check with Misko - # to see if he's using it on this Mac. - if [[ -z "$DART_SDK" ]]; then - : "${DARTSDK:=$DART_SDK}" - else - : "${DART_SDK:=$DARTSDK}" - fi - - unset DART - PLATFORM="$(uname -s)" - - case "$PLATFORM" in - (Darwin) - path=$(readlink ${BASH_SOURCE[0]}||echo './scripts/env.sh') - export NGDART_SCRIPT_DIR=$(dirname $path) - ;; - (Linux) - export NGDART_SCRIPT_DIR=$(dirname $(readlink -f ${BASH_SOURCE[0]})) - ;; - (*) - echo Unsupported platform $PLATFORM. Exiting ... >&2 - exit 3 - ;; - esac - - export NGDART_BASE_DIR=$(dirname $NGDART_SCRIPT_DIR) - - # Try to find the SDK alongside the dart command first. - if [[ -z "$DART_SDK" ]]; then - DART=$(which dart) || true - if [[ -x "$DART" ]]; then - DART_SDK="${DART/dart-sdk\/*/dart-sdk}" - if [[ ! -e "$DART_SDK" ]]; then - unset DART DART_SDK - fi - fi - fi - # Fallback: Assume it's alongside the current directory (e.g. Travis). - if [[ -z "$DART_SDK" ]]; then - DART_SDK="$(pwd)/dart-sdk" - fi - - : "${DART:=$DART_SDK/bin/dart}" - - if [[ ! -x "$DART" ]]; then - echo Unable to locate the dart binary / SDK. Exiting >&2 - exit 3 - fi - - if [[ -z "$DARTIUM" ]]; then - dartiumRoot="$DART_SDK/../chromium" - if [[ -e "$dartiumRoot" ]]; then - case "$PLATFORM" in - (Linux) export DARTIUM="$dartiumRoot/chrome" ;; - (Darwin) export DARTIUM="$dartiumRoot/Chromium.app/Contents/MacOS/Chromium" ;; - (*) echo Unsupported platform $PLATFORM. Exiting ... >&2 ; exit 3 ;; - esac - fi - fi - - export DART_SDK_LIB_SEARCH_PATH="$DART_SDK" - export DART_SDK - export DARTSDK - export DART - export PUB=${PUB:-"$DART_SDK/bin/pub"} - if [ -z "$PUB_CACHE" ]; then - export PUB_CACHE=$DART_SDK/pub-cache - fi - export DARTANALYZER=${DARTANALYZER:-"$DART_SDK/bin/dartanalyzer"} - export DARTDOC=${DARTDOC:-"$DART_SDK/bin/dartdoc"} - export DART_DOCGEN=${DART_DOCGEN:-"$DART_SDK/bin/docgen"} - export DART_VM_OPTIONS="--old_gen_heap_size=2048" - export DARTIUM_BIN=${DARTIUM_BIN:-"$DARTIUM"} - export CHROME_BIN=${CHROME_BIN:-"google-chrome"} - export PATH=$PATH:$DART_SDK/bin - - echo '*********' - echo '** ENV **' - echo '*********' - echo DART_SDK=$DART_SDK - echo DART_SDK_LIB_SEARCH_PATH=$DART_SDK_LIB_SEARCH_PATH - echo DART=$DART - echo PUB=$PUB - echo DARTANALYZER=$DARTANALYZER - echo DARTDOC=$DARTDOC - echo DART_DOCGEN=$DART_DOCGEN - echo DARTIUM_BIN=$DARTIUM_BIN - echo CHROME_BIN=$CHROME_BIN - echo PATH=$PATH - echo NGDART_BASE_DIR=$NGDART_BASE_DIR - echo NGDART_SCRIPT_DIR=$NGDART_SCRIPT_DIR - -fi diff --git a/scripts/ci/install_dart.sh b/scripts/ci/install_dart.sh deleted file mode 100755 index eed43224a8..0000000000 --- a/scripts/ci/install_dart.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -set -e -x - -DART_CHANNEL=$1 -VERSION=$2 -ARCH=$3 - -AVAILABLE_DART_VERSION=$(curl "https://storage.googleapis.com/dart-archive/channels/${DART_CHANNEL}/release/${VERSION}/VERSION" | python -c \ - 'import sys, json; print(json.loads(sys.stdin.read())["version"])') - -echo Fetch Dart channel: ${DART_CHANNEL} - -URL_PREFIX=https://storage.googleapis.com/dart-archive/channels/${DART_CHANNEL}/release/${VERSION} -DART_SDK_URL="$URL_PREFIX/sdk/dartsdk-$ARCH-release.zip" -DARTIUM_URL="$URL_PREFIX/dartium/dartium-$ARCH-release.zip" - -download_and_unzip() { - ZIPFILE=${1/*\//} - curl -O -L $1 && unzip -q $ZIPFILE && rm $ZIPFILE -} - -# TODO: do these downloads in parallel -download_and_unzip $DART_SDK_URL -download_and_unzip $DARTIUM_URL - -echo Fetched new dart version $( bin [: No such file or directory") { - // Skip bad output from Dart SDK .bat files on Windows - return; - } - var parsedLine = _AnalyzerOutputLine.parse(line); - if (!parsedLine) { - errorCount++; - console.log('Unexpected output: ' + line); - return; - } - // TODO remove once dartanalyzer handles transitive libraries - // skip errors in third-party packages - if (parsedLine.sourcePath.indexOf(dirName) == -1) { - return; - } - if (parsedLine.shouldIgnore()) { - return; - } - - if (parsedLine.isHint) { - hintCount++; - } else if (parsedLine.isWarning) { - warningCount++; - } else { - errorCount++; - } - console.log(dirName + ':' + parsedLine); - }); - stream.on('close', function() { - var error; - var report = []; - if (errorCount > 0) { - report.push(errorCount + ' error(s)'); - } - if (warningCount > 0) { - report.push(warningCount + ' warning(s)'); - } - if (hintCount > 0) { - report.push(hintCount + ' hint(s)'); - } - if (report.length > 0) { - error = 'Dartanalyzer showed ' + report.join(', '); - } - done(error); - }); - stream.on('error', function(error) { done(error); }); - } -}; - -// See https://github.com/dart-lang/analyzer_cli/blob/master/lib/src/error_formatter.dart -function _AnalyzerOutputLine(result) { - this.severity = result[1]; - this.errorType = result[2]; - this.errorCode = result[3]; - this.sourcePath = result[4]; - this.lineNum = result[5]; - this.colNum = result[6]; - this.asciiLineLength = parseInt(result[7], 10); - this.errorMsg = result[8]; - - this.isError = Boolean(this.severity.match(/ERROR/i)); - this.isHint = Boolean(this.severity.match(/INFO/i)); - this.isWarning = Boolean(this.severity.match(/WARNING/i)); -} - -_AnalyzerOutputLine.parse = function(line) { - var result = _AnalyzerOutputLine._analyzerParseRegExp.exec(line); - return result ? new _AnalyzerOutputLine(result) : null; -}; - -_AnalyzerOutputLine._analyzerParseRegExp = - new RegExp('([^\|]+)\\|' + // #1, severity (NONE, INFO, WARNING, ERROR) - '([^\|]+)\\|' + // #2, errorCode.type (HINT, *_WARNING, *_ERROR, etc) - '([^\|]+)\\|' + // #3, errorCode (UNUSED_IMPORT, UNUSED_CATCH_STACK, etc) - '([^\|]+[^\|\\\\])\\|' + // #4, sourcePath with '|' chars backslash-escaped. - '([^\|]+)\\|' + // #5, line number - '([^\|]+)\\|' + // #6, column number - '([^\|]+)\\|' + // #7, length of the ASCII line to draw - '(.*)$'); // #8, error message - -/* Maps file path (as string) to file source (an array of strings, one per line). */ -_AnalyzerOutputLine.cache = {}; - -_AnalyzerOutputLine.ERR_NO_SOURCE = '(Could not find source line).'; - -_AnalyzerOutputLine.prototype = { - toString: function() { - var sourceLine = this._getSourceLine(); - var lineText = _AnalyzerOutputLine.ERR_NO_SOURCE; - if (sourceLine) { - var repeat = function(str, num) { - if (str.repeat) return str.repeat(num); - return Array.prototype.join.call({length: num}, str); - }; - - lineText = - '\n' + sourceLine + '\n' + repeat(' ', this.colNum) + repeat('^', this.asciiLineLength); - } - return '[' + this.severity + '] type: ' + this.errorType + ' ' + - this.errorMsg + ' (' + this.sourcePath + ', line ' + this.lineNum + - ', col ' + this.colNum + ')' + lineText; - }, - - shouldIgnore: function() { - if (this.errorCode.match(/UNUSED_IMPORT/i)) { - if (this.sourcePath.match(/_analyzer\.dart/)) { - return true; - } - // TODO remove it once ts2dart properly generates abstract getters - if (this.errorMsg.match(/unimplemented/)) { - return true; - } - } - - if (this.errorCode.match(/DEPRECATED_MEMBER_USE/i)) { - return true; - } - - // TODO: https://github.com/angular/ts2dart/issues/168 - if (this.errorCode.match(/UNUSED_CATCH_STACK/i)) { - return true; - } - - // TODOs shouldn't break our build... - if (this.errorCode.match(/TODO/i)) { - return true; - } - - // Don't worry about hints in generated files. - if (this.isHint && this.sourcePath.match(/generated/i)) { - return true; - } - - // Don't worry about warnings in external code. - if (this.sourcePath.match(/benchmarks_external/i)) { - return true; - } - - if (this.errorCode.match(/UNUSED_SHOWN_NAME/i)) { - // TODO: Narrow this ignore down to test code only. - // See https://github.com/angular/angular/issues/8044 - return true; - } - return false; - }, - - // Reads the source file for the Analyzer output, caching it for future use. - _getSourceLine: function() { - var cache = _AnalyzerOutputLine.cache; - var sourceLines = null; - if (cache.hasOwnProperty(this.sourcePath)) { - sourceLines = cache[this.sourcePath]; - } else { - try { - sourceLines = String(fs.readFileSync(this.sourcePath)); - sourceLines = sourceLines.split('\n'); - } catch (e) { - sourceLines = null; - } finally { - // Even if this fails, cache `null` so we don't try again. - cache[this.sourcePath] = sourceLines; - } - } - return sourceLines && this.lineNum <= sourceLines.length ? sourceLines[this.lineNum - 1] : null; - } -}; diff --git a/tools/build/dartapidocs.js b/tools/build/dartapidocs.js deleted file mode 100644 index 665368a5ec..0000000000 --- a/tools/build/dartapidocs.js +++ /dev/null @@ -1,37 +0,0 @@ -var Q = require('q'); -var readline = require('readline'); -var spawn = require('child_process').spawn; -var util = require('./util'); - -module.exports = function(gulp, plugins, config) { - config.output = config.output || 'doc/api'; - return util.forEachSubDirSequential(config.dest, function(dir) { - var defer = Q.defer(); - var done = defer.makeNodeResolver(); - - var supportedModules = [ - 'dist/dart/angular2', - 'dist/dart/benchpress' - ]; - - if (supportedModules.indexOf(dir) === -1) { - done(); - } else { - console.log('INFO: running dartdoc for ', dir); - - var stream = spawn(config.command, ['--output=' + config.output], - {stdio: [process.stdin, process.stdout, process.stderr], cwd: dir}); - - stream.on('exit', function(code) { - if (code !== 0) { - done('ERROR: dartdoc exited with non-zero status ' + code); - } else { - done(); - } - }); - - stream.on('error', function(e) { done('ERROR: dartdoc reported error: ' + e); }); - } - return defer.promise; - }); -}; diff --git a/tools/build/proto.js b/tools/build/proto.js deleted file mode 100644 index d6a933db40..0000000000 --- a/tools/build/proto.js +++ /dev/null @@ -1,123 +0,0 @@ -var fs = require('fs'); -var glob = require('glob'); -var hashFiles = require('hash-files'); -var path = require('path'); -var protocDetect = require('./protoc').detect; -var spawn = require('child_process').spawn; - -// Hashs all .proto files at `config.dir`, calling `computedCallback` on each -// when done with the original file name and its hash. -// When all files have been hashed, calls `completeCallback` with no parameters. -function _hashProtosTask(config, computedCallback, completeCallback) { - var files = glob.sync(path.join(config.dir, '*.proto')); - var toUpdate = {}; - var checkComplete = function() { - for (var key in toUpdate) { - if (toUpdate.hasOwnProperty(key) && toUpdate[key]) { - return false; - } - } - return true; - }; - files.forEach(function(file) { toUpdate[file] = true; }); - files.forEach( - function(file) { - hashFiles({ - algorithm: config.algorithm || 'sha1', - files: [file] - }, function(error, hash) { - computedCallback(file, hash); - toUpdate[file] = false; - if (checkComplete()) { - completeCallback(); - } - }); - }); -} - -function _toPbDartExtension(path) { - return path.replace(/\.proto$/, '.pb.dart'); -} - -module.exports = { - // Generates `.pb.dart` files from all `.proto` files located at `config.dir`. - // This task requires the Dart protoc plugin, which is expected to reside at - // the path specified in `config.plugin`. - generate: function(config, done) { - // Note that while the Dart protoc plugin requires the Dart sdk, this task will be skipped if the - // Dart sdk is not available. - var protoc = protocDetect(); - if (!protoc) { - done(new Error('Could not detect protoc - failed to rebuild Dart proto code.')); - return; - } - - var protoPaths = glob.sync(path.join(config.dir, '*.proto')); - var spawnArgs = [ - '--plugin', config.plugin, - '--proto_path', config.dir, - '--dart_out', config.dir, - ].concat(protoPaths); - var proc = spawn(protoc.bin, spawnArgs, { - cwd: '.', - stdio: ['ignore', 2, 'inherit'] - }); - var failed = false; - var failWithError = function(msg) { - if (failed) return; - failed = true; - done(new Error('Failed while generating transformer boilerplate. Check for output above.\n' + - 'Message: ' + msg + '\n' + - 'Please run manually: ' + [protoc.bin].concat(spawnArgs).join(' '))); - }; - proc.on('error', function(err) { failWithError(String(err)); }); - proc.on('exit', function(code, signal) { - if (!code) { - var protocHash = hashFiles.sync({ - algorithm: config.algorithm || 'sha1', - files: [config.plugin] - }); - var computedCallback = function(fileName, hash) { - var pbDartPath = _toPbDartExtension(fileName); - var toAppend = '/**\n' + - ' * Generated with:\n' + - ' * ' + path.basename(fileName) + ' (' + hash + ')\n' + - ' * ' + protoc.version + '\n' + - ' * dart-protoc-plugin (' + protocHash + ')\n' + - ' */\n'; - fs.appendFileSync(pbDartPath, toAppend); - }; - return _hashProtosTask(config, computedCallback, function() { done(); }); - } else { - failWithError('Exit code was ' + code); - } - }); - }, - - // Checks that the `.pb.dart` files located at `config.dir` are in sync with - // the `proto` files at the same directory. - // It does this by computing the hash of the `.proto` files and looking for - // that string in the contents of the associated `.pb.dart` file. If one or - // more file(s) do not have that hash present, this task will fail with a - // descriptive error message. - lint: function(config, done) { - var missing = []; - var computedCallback = function(filePath, hash) { - var pbDartPath = _toPbDartExtension(filePath); - if (String(fs.readFileSync(pbDartPath)).indexOf(hash) < 0) { - missing.push(' ' + hash + ' not found in ' + pbDartPath + '\n'); - } - }; - var completeCallback = function() { - if (missing.length == 0) { - done(); - } else { - done(new Error( - 'Generated Dart protobuf files are out of date. Please run `gulp gen_protos.dart`.\n' + - missing.join('')) - ); - } - }; - return _hashProtosTask(config, computedCallback, completeCallback); - } -}; diff --git a/tools/build/protoc-gen-dart b/tools/build/protoc-gen-dart deleted file mode 100755 index 564e66fc4f..0000000000 --- a/tools/build/protoc-gen-dart +++ /dev/null @@ -1,5015 +0,0 @@ -#!/usr/bin/env dart -// Compiled https://github.com/dart-lang/dart-protoc-plugin/releases, v0.5.0 -import "dart:convert"; -import "dart:typed_data"; -import "dart:math"; -import "dart:math" as _A; -import "dart:collection"; -import "dart:async"; -import "dart:io"; -import "dart:io" as _B; -class CryptoUtils { - static String bytesToBase64_A(List bytes, {bool urlSafe: false, bool addLineSeparator: false}) { - return _CryptoUtils_A.bytesToBase64_B(bytes, urlSafe, addLineSeparator); - } -} -const Base64Codec BASE64 = const Base64Codec(); -const List _decodeTable_A = const[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, 62, -2, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, 0, -2, -2, -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, 63, -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2]; -const String _encodeTableUrlSafe_A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; -const String _encodeTable_A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -const int _LINE_LENGTH = 76; -const int _CR_A = 13; -const int _LF_A = 10; -const List _PAD_BYTES = const[61]; -const List _ENCODED_PAD_BYTES = const[37, 51, 68]; -const String _PAD = "="; -const String _ENCODED_PAD = "%3D"; -class Base64Codec extends Codec, String> { - final bool _urlSafe; - final bool _addLineSeparator; - final bool _encodePaddingCharacter; - const Base64Codec({bool urlSafe: false, bool addLineSeparator: false, bool encodePaddingCharacter: false}) : _urlSafe = urlSafe, _addLineSeparator = addLineSeparator, _encodePaddingCharacter = encodePaddingCharacter; - String get name => "base64"; - String encode(List bytes, {bool urlSafe, bool addLineSeparator, bool encodePaddingCharacter}) { - if (urlSafe == null) urlSafe = _urlSafe; - if (addLineSeparator == null) addLineSeparator = _addLineSeparator; - if (encodePaddingCharacter == null) { - encodePaddingCharacter = _encodePaddingCharacter; - } - return new Base64Encoder(urlSafe: urlSafe, addLineSeparator: addLineSeparator, encodePaddingCharacter: encodePaddingCharacter).convert(bytes); - } - Base64Encoder get encoder => new Base64Encoder(urlSafe: _urlSafe, addLineSeparator: _addLineSeparator, encodePaddingCharacter: _encodePaddingCharacter); - Base64Decoder get decoder => new Base64Decoder(); -} -class Base64Encoder extends Converter, String> { - final bool _urlSafe; - final bool _addLineSeparator; - final bool _encodePaddingCharacter; - final List _pad; - const Base64Encoder({bool urlSafe: false, bool addLineSeparator: false, bool encodePaddingCharacter: false}) : _urlSafe = urlSafe, _addLineSeparator = addLineSeparator, _encodePaddingCharacter = encodePaddingCharacter, _pad = encodePaddingCharacter == true ? _ENCODED_PAD_BYTES : _PAD_BYTES; - String convert(List bytes, [int start_A = 0, int end_A]) { - int bytes_length = bytes.length; - RangeError.checkValidRange(start_A, end_A, bytes_length); - if (end_A == null) end_A = bytes_length; - int length_A = end_A - start_A; - if (length_A == 0) { - return ""; - } - final String lookup_A = _urlSafe ? _encodeTableUrlSafe_A : _encodeTable_A; - final int remainderLength = length_A.remainder(3); - final int chunkLength = length_A - remainderLength; - int baseOutputLength = ((length_A ~/ 3) * 4); - int remainderOutputLength; - if (_encodePaddingCharacter) { - remainderOutputLength = ((remainderLength > 0) ? 6 : 0); - } else { - remainderOutputLength = ((remainderLength > 0) ? 4 : 0); - } - int outputLength = baseOutputLength + remainderOutputLength; - if (_addLineSeparator) { - outputLength += ((outputLength - 1) ~/ _LINE_LENGTH) << 1; - } - List out = new List(outputLength); - int j = 0, i = start_A, c = 0; - while (i < chunkLength) { - int x_A = ((bytes[i++] << 16) & 0x00FFFFFF) | ((bytes[i++] << 8) & 0x00FFFFFF) | bytes[i++]; - out[j++] = lookup_A.codeUnitAt(x_A >> 18); - out[j++] = lookup_A.codeUnitAt((x_A >> 12) & 0x3F); - out[j++] = lookup_A.codeUnitAt((x_A >> 6) & 0x3F); - out[j++] = lookup_A.codeUnitAt(x_A & 0x3F); - if (_addLineSeparator && ++c == 19 && j < outputLength - 2) { - out[j++] = _CR_A; - out[j++] = _LF_A; - c = 0; - } - } - if (remainderLength == 1) { - int x_A = bytes[i]; - out[j++] = lookup_A.codeUnitAt(x_A >> 2); - out[j++] = lookup_A.codeUnitAt((x_A << 4) & 0x3F); - out.setRange(j, j + _pad.length, _pad); - out.setRange(j + _pad.length, j + 2 * _pad.length, _pad); - } else if (remainderLength == 2) { - int x_A = bytes[i]; - int y_A = bytes[i + 1]; - out[j++] = lookup_A.codeUnitAt(x_A >> 2); - out[j++] = lookup_A.codeUnitAt(((x_A << 4) | (y_A >> 4)) & 0x3F); - out[j++] = lookup_A.codeUnitAt((y_A << 2) & 0x3F); - out.setRange(j, j + _pad.length, _pad); - } - return new String.fromCharCodes(out); - } - _Base64EncoderSink startChunkedConversion(Sink sink_A) { - StringConversionSink stringSink; - if (sink_A is StringConversionSink) { - stringSink = sink_A; - } else { - stringSink = new StringConversionSink.from(sink_A); - } - return new _Base64EncoderSink(stringSink, _urlSafe, _addLineSeparator); - } -} -class _Base64EncoderSink extends ChunkedConversionSink> { - final Base64Encoder _encoder; - final ChunkedConversionSink _outSink; - final List _buffer_A = new List(); - int _bufferCount = 0; - _Base64EncoderSink(this._outSink, urlSafe, addLineSeparator) : _encoder = new Base64Encoder(urlSafe: urlSafe, addLineSeparator: addLineSeparator); - void add(List chunk) { - var nextBufferCount = (chunk.length + _bufferCount) % 3; - int decodableLength = _bufferCount + chunk.length - nextBufferCount; - if (_bufferCount + chunk.length > _buffer_A.length) { - _buffer_A.replaceRange(_bufferCount, _buffer_A.length, chunk.sublist(0, _buffer_A.length - _bufferCount)); - _buffer_A.addAll(chunk.sublist(_buffer_A.length - _bufferCount)); - } else { - _buffer_A.replaceRange(_bufferCount, _bufferCount + chunk.length, chunk); - } - _outSink.add(_encoder.convert(_buffer_A, 0, decodableLength)); - _buffer_A.removeRange(0, decodableLength); - _bufferCount = nextBufferCount; - } - void close() { - if (_bufferCount > 0) { - _outSink.add(_encoder.convert(_buffer_A.sublist(0, _bufferCount))); - } - _outSink.close(); - } -} -class Base64Decoder extends Converter> { - const Base64Decoder(); - List convert(String input_A) { - int length_A = input_A.length; - if (length_A == 0) { - return new Uint8List(0); - } - int normalLength = 0; - int i = 0; - while (i < length_A) { - int codeUnit = input_A.codeUnitAt(i); - int c = _decodeTable_A[codeUnit]; - if (c == -2) { - if (codeUnit == _ENCODED_PAD_BYTES[0] && i < length_A - 2 && input_A.codeUnitAt(i + 1) == _ENCODED_PAD_BYTES[1] && input_A.codeUnitAt(i + 2) == _ENCODED_PAD_BYTES[2]) { - normalLength++; - i += 2; - } else { - throw new FormatException('Invalid character', input_A, i); - } - } - if (c >= 0) normalLength++; - i++; - } - if (normalLength % 4 != 0) { - throw new FormatException('''Size of Base 64 characters in Input - must be a multiple of 4''', input_A, normalLength); - } - int padLength = 0; - i = length_A - 1; - while (i >= 0) { - int currentCodeUnit = input_A.codeUnitAt(i); - if (currentCodeUnit == _ENCODED_PAD_BYTES[2] && i >= 2 && input_A.codeUnitAt(i - 1) == _ENCODED_PAD_BYTES[1] && input_A.codeUnitAt(i - 2) == _ENCODED_PAD_BYTES[0]) { - padLength++; - i -= 2; - } else if (_decodeTable_A[currentCodeUnit] > 0) { - break; - } else if (currentCodeUnit == _PAD_BYTES[0]) { - padLength++; - } - i--; - } - int outputLength = ((normalLength * 6) >> 3) - padLength; - List out = new Uint8List(outputLength); - for (int i = 0, o = 0; o < outputLength;) { - int x_A = 0; - for (int j = 4; j > 0;) { - int c = _decodeTable_A[input_A.codeUnitAt(i++)]; - if (c >= 0) { - x_A = ((x_A << 6) & 0x00FFFFFF) | c; - j--; - } - } - out[o++] = x_A >> 16; - if (o < outputLength) { - out[o++] = (x_A >> 8) & 0xFF; - if (o < outputLength) out[o++] = x_A & 0xFF; - } - } - return out; - } - _Base64DecoderSink startChunkedConversion(Sink> sink_A) { - if (sink_A is! ByteConversionSink) { - sink_A = new ByteConversionSink.from(sink_A); - } - return new _Base64DecoderSink(sink_A); - } -} -class _Base64DecoderSink extends ChunkedConversionSink { - final Base64Decoder _decoder_A = new Base64Decoder(); - final ChunkedConversionSink> _outSink; - String _unconverted = ""; - _Base64DecoderSink(this._outSink); - void add(String chunk) { - if (chunk.isEmpty) return; - if (_unconverted.isNotEmpty) { - chunk = _unconverted + chunk; - } - chunk = chunk.replaceAll(_ENCODED_PAD, _PAD); - int decodableLength = chunk.length; - if (chunk.length > 3 && chunk.contains(_ENCODED_PAD[0], chunk.length - 2)) { - decodableLength = chunk.lastIndexOf(_ENCODED_PAD[0]); - } - decodableLength -= decodableLength % 4; - _unconverted = chunk.substring(decodableLength); - if (decodableLength > 0) { - _outSink.add(_decoder_A.convert(chunk.substring(0, decodableLength))); - } - } - void close() { - if (_unconverted.isNotEmpty) { - _outSink.add(_decoder_A.convert(_unconverted)); - } - _outSink.close(); - } -} -abstract class _CryptoUtils_A { - static String bytesToBase64_B(List bytes, [bool urlSafe = false, bool addLineSeparator = false]) { - return BASE64.encode(bytes, urlSafe: urlSafe, addLineSeparator: addLineSeparator); - } -} -class Dart_options { - static final Extension defaultMixin = new Extension('FileOptions', 'defaultMixin', 96128839, PbFieldType.OS); - static final Extension mixin = new Extension('MessageOptions', 'mixin', 96128839, PbFieldType.OS); - static void registerAllExtensions(ExtensionRegistry registry) { - registry.add(defaultMixin); - registry.add(mixin); - } -} -class Int32 implements IntX { - static int _validateRadix(int radix) { - if (2 <= radix && radix <= 36) return radix; - throw new RangeError.range(radix, 2, 36, 'radix'); - } -} -class Int64 implements IntX { - final int _l; - final int _m; - final int _h_A; - static const int _BITS = 22; - static const int _BITS01 = 44; - static const int _BITS2 = 20; - static const int _MASK = 4194303; - static const int _MASK2 = 1048575; - static const int _SIGN_BIT_MASK = 524288; - static const Int64 ZERO_A = const Int64._bits(0, 0, 0); - const Int64._bits(int this._l, int this._m, int this._h_A); - factory Int64([int value_A = 0]) { - int v0 = 0, v1 = 0, v2 = 0; - bool negative = false; - if (value_A < 0) { - negative = true; - value_A = -value_A - 1; - } - if (_haveBigInts) { - v0 = _MASK & value_A; - v1 = _MASK & (value_A >> _BITS); - v2 = _MASK2 & (value_A >> _BITS01); - } else { - v2 = value_A ~/ 17592186044416; - value_A -= v2 * 17592186044416; - v1 = value_A ~/ 4194304; - value_A -= v1 * 4194304; - v0 = value_A; - } - if (negative) { - v0 = ~v0; - v1 = ~v1; - v2 = ~v2; - } - return Int64._masked_A(v0, v1, v2); - } - factory Int64.fromBytes(List bytes) { - int top_A = bytes[7] & 0xff; - top_A <<= 8; - top_A |= bytes[6] & 0xff; - top_A <<= 8; - top_A |= bytes[5] & 0xff; - top_A <<= 8; - top_A |= bytes[4] & 0xff; - int bottom_A = bytes[3] & 0xff; - bottom_A <<= 8; - bottom_A |= bytes[2] & 0xff; - bottom_A <<= 8; - bottom_A |= bytes[1] & 0xff; - bottom_A <<= 8; - bottom_A |= bytes[0] & 0xff; - return new Int64.fromInts(top_A, bottom_A); - } - factory Int64.fromInts(int top_A, int bottom_A) { - top_A &= 0xffffffff; - bottom_A &= 0xffffffff; - int d0 = _MASK & bottom_A; - int d1 = ((0xfff & top_A) << 10) | (0x3ff & (bottom_A >> _BITS)); - int d2 = _MASK2 & (top_A >> 12); - return new Int64._bits(d0, d1, d2); - } - static Int64 _promote(value_A) { - if (value_A is Int64) { - return value_A; - } else if (value_A is int) { - return new Int64(value_A); - } else if (value_A is Int32) { - return value_A.toInt64(); - } - throw new ArgumentError.value(value_A); - } - Int64 operator+(other) { - Int64 o = _promote(other); - int sum0 = _l + o._l; - int sum1 = _m + o._m + (sum0 >> _BITS); - int sum2 = _h_A + o._h_A + (sum1 >> _BITS); - return Int64._masked_A(sum0, sum1, sum2); - } - Int64 operator-(other) { - Int64 o = _promote(other); - return _sub(_l, _m, _h_A, o._l, o._m, o._h_A); - } - Int64 operator-() => _negate(_l, _m, _h_A); - Int64 operator*(other) { - Int64 o = _promote(other); - int a0 = _l & 0x1fff; - int a1 = (_l >> 13) | ((_m & 0xf) << 9); - int a2 = (_m >> 4) & 0x1fff; - int a3 = (_m >> 17) | ((_h_A & 0xff) << 5); - int a4 = (_h_A & 0xfff00) >> 8; - int b0 = o._l & 0x1fff; - int b1 = (o._l >> 13) | ((o._m & 0xf) << 9); - int b2 = (o._m >> 4) & 0x1fff; - int b3 = (o._m >> 17) | ((o._h_A & 0xff) << 5); - int b4 = (o._h_A & 0xfff00) >> 8; - int p0 = a0 * b0; - int p1 = a1 * b0; - int p2 = a2 * b0; - int p3 = a3 * b0; - int p4 = a4 * b0; - if (b1 != 0) { - p1 += a0 * b1; - p2 += a1 * b1; - p3 += a2 * b1; - p4 += a3 * b1; - } - if (b2 != 0) { - p2 += a0 * b2; - p3 += a1 * b2; - p4 += a2 * b2; - } - if (b3 != 0) { - p3 += a0 * b3; - p4 += a1 * b3; - } - if (b4 != 0) { - p4 += a0 * b4; - } - int c00 = p0 & 0x3fffff; - int c01 = (p1 & 0x1ff) << 13; - int c0 = c00 + c01; - int c10 = p0 >> 22; - int c11 = p1 >> 9; - int c12 = (p2 & 0x3ffff) << 4; - int c13 = (p3 & 0x1f) << 17; - int c1 = c10 + c11 + c12 + c13; - int c22 = p2 >> 18; - int c23 = p3 >> 5; - int c24 = (p4 & 0xfff) << 8; - int c2 = c22 + c23 + c24; - c1 += c0 >> _BITS; - c2 += c1 >> _BITS; - return Int64._masked_A(c0, c1, c2); - } - Int64 operator%(other) => _divide(this, other, _RETURN_MOD); - Int64 operator~/(other) => _divide(this, other, _RETURN_DIV); - Int64 remainder(other) => _divide(this, other, _RETURN_REM); - Int64 operator&(other) { - Int64 o = _promote(other); - int a0 = _l & o._l; - int a1 = _m & o._m; - int a2 = _h_A & o._h_A; - return new Int64._bits(a0, a1, a2); - } - Int64 operator|(other) { - Int64 o = _promote(other); - int a0 = _l | o._l; - int a1 = _m | o._m; - int a2 = _h_A | o._h_A; - return new Int64._bits(a0, a1, a2); - } - Int64 operator^(other) { - Int64 o = _promote(other); - int a0 = _l ^ o._l; - int a1 = _m ^ o._m; - int a2 = _h_A ^ o._h_A; - return Int64._masked_A(a0, a1, a2); - } - Int64 operator~() { - return Int64._masked_A(~_l, ~_m, ~_h_A); - } - Int64 operator<<(int n) { - if (n < 0) { - throw new ArgumentError.value(n); - } - n &= 63; - int res0, res1, res2; - if (n < _BITS) { - res0 = _l << n; - res1 = (_m << n) | (_l >> (_BITS - n)); - res2 = (_h_A << n) | (_m >> (_BITS - n)); - } else if (n < _BITS01) { - res0 = 0; - res1 = _l << (n - _BITS); - res2 = (_m << (n - _BITS)) | (_l >> (_BITS01 - n)); - } else { - res0 = 0; - res1 = 0; - res2 = _l << (n - _BITS01); - } - return Int64._masked_A(res0, res1, res2); - } - Int64 operator>>(int n) { - if (n < 0) { - throw new ArgumentError.value(n); - } - n &= 63; - int res0, res1, res2; - int a2 = _h_A; - bool negative = (a2 & _SIGN_BIT_MASK) != 0; - if (negative && _MASK > _MASK2) { - a2 += (_MASK - _MASK2); - } - if (n < _BITS) { - res2 = _shiftRight(a2, n); - if (negative) { - res2 |= _MASK2 & ~(_MASK2 >> n); - } - res1 = _shiftRight(_m, n) | (a2 << (_BITS - n)); - res0 = _shiftRight(_l, n) | (_m << (_BITS - n)); - } else if (n < _BITS01) { - res2 = negative ? _MASK2 : 0; - res1 = _shiftRight(a2, n - _BITS); - if (negative) { - res1 |= _MASK & ~(_MASK >> (n - _BITS)); - } - res0 = _shiftRight(_m, n - _BITS) | (a2 << (_BITS01 - n)); - } else { - res2 = negative ? _MASK2 : 0; - res1 = negative ? _MASK : 0; - res0 = _shiftRight(a2, n - _BITS01); - if (negative) { - res0 |= _MASK & ~(_MASK >> (n - _BITS01)); - } - } - return Int64._masked_A(res0, res1, res2); - } - bool operator==(other) { - Int64 o; - if (other is Int64) { - o = other; - } else if (other is int) { - if (_h_A == 0 && _m == 0) return _l == other; - if ((_MASK & other) == other) return false; - o = new Int64(other); - } else if (other is Int32) { - o = other.toInt64(); - } - if (o != null) { - return _l == o._l && _m == o._m && _h_A == o._h_A; - } - return false; - } - int compareTo(IntX other) => _compareTo(other); - int _compareTo(other) { - Int64 o = _promote(other); - int signa = _h_A >> (_BITS2 - 1); - int signb = o._h_A >> (_BITS2 - 1); - if (signa != signb) { - return signa == 0 ? 1 : -1; - } - if (_h_A > o._h_A) { - return 1; - } else if (_h_A < o._h_A) { - return -1; - } - if (_m > o._m) { - return 1; - } else if (_m < o._m) { - return -1; - } - if (_l > o._l) { - return 1; - } else if (_l < o._l) { - return -1; - } - return 0; - } - bool operator<(other) => _compareTo(other) < 0; - bool operator<=(other) => _compareTo(other) <= 0; - bool operator>(other) => this._compareTo(other) > 0; - bool operator>=(other) => _compareTo(other) >= 0; - bool get isNegative => (_h_A & _SIGN_BIT_MASK) != 0; - bool get isZero => _h_A == 0 && _m == 0 && _l == 0; - int get hashCode { - int bottom_A = ((_m & 0x3ff) << _BITS) | _l; - int top_A = (_h_A << 12) | ((_m >> 10) & 0xfff); - return bottom_A ^ top_A; - } - Int64 abs() { - return this.isNegative ? -this : this; - } - List toBytes() { - List result_A = new List(8); - result_A[0] = _l & 0xff; - result_A[1] = (_l >> 8) & 0xff; - result_A[2] = ((_m << 6) & 0xfc) | ((_l >> 16) & 0x3f); - result_A[3] = (_m >> 2) & 0xff; - result_A[4] = (_m >> 10) & 0xff; - result_A[5] = ((_h_A << 4) & 0xf0) | ((_m >> 18) & 0xf); - result_A[6] = (_h_A >> 4) & 0xff; - result_A[7] = (_h_A >> 12) & 0xff; - return result_A; - } - int toInt() { - int l = _l; - int m = _m; - int h = _h_A; - bool negative = false; - if ((_h_A & _SIGN_BIT_MASK) != 0) { - l = _MASK & ~_l; - m = _MASK & ~_m; - h = _MASK2 & ~_h_A; - negative = true; - } - if (_haveBigInts) { - int result_A = (h << _BITS01) | (m << _BITS) | l; - return negative ? -result_A - 1 : result_A; - } else { - if (negative) { - return -((l + 1) + (m * 4194304) + (h * 17592186044416)); - } else { - return (l + (m * 4194304)) + (h * 17592186044416); - } - } - } - Int64 toInt64() => this; - String toString() => _toRadixString(10); - String toRadixString(int radix) { - return _toRadixString(Int32._validateRadix(radix)); - } - String _toRadixString(int radix) { - int d0 = _l; - int d1 = _m; - int d2 = _h_A; - if (d0 == 0 && d1 == 0 && d2 == 0) return '0'; - String sign_A = ''; - if ((d2 & _SIGN_BIT_MASK) != 0) { - sign_A = '-'; - d0 = 0 - d0; - int borrow = (d0 >> _BITS) & 1; - d0 &= _MASK; - d1 = 0 - d1 - borrow; - borrow = (d1 >> _BITS) & 1; - d1 &= _MASK; - d2 = 0 - d2 - borrow; - d2 &= _MASK2; - } - int d4 = (d2 << 4) | (d1 >> 18); - int d3 = (d1 >> 8) & 0x3ff; - d2 = ((d1 << 2) | (d0 >> 20)) & 0x3ff; - d1 = (d0 >> 10) & 0x3ff; - d0 = d0 & 0x3ff; - int fatRadix = _fatRadixTable[radix]; - String chunk1 = "", chunk2 = "", chunk3 = ""; - while (!(d4 == 0 && d3 == 0)) { - int q = d4 ~/ fatRadix; - int r = d4 - q * fatRadix; - d4 = q; - d3 += r << 10; - q = d3 ~/ fatRadix; - r = d3 - q * fatRadix; - d3 = q; - d2 += r << 10; - q = d2 ~/ fatRadix; - r = d2 - q * fatRadix; - d2 = q; - d1 += r << 10; - q = d1 ~/ fatRadix; - r = d1 - q * fatRadix; - d1 = q; - d0 += r << 10; - q = d0 ~/ fatRadix; - r = d0 - q * fatRadix; - d0 = q; - assert(chunk3 == ""); - chunk3 = chunk2; - chunk2 = chunk1; - chunk1 = (fatRadix + r).toRadixString(radix).substring(1); - } - int residue = (d2 << 20) + (d1 << 10) + d0; - String leadingDigits = residue == 0 ? '' : residue.toRadixString(radix); - return '${sign_A}${leadingDigits}${chunk1}${chunk2}${chunk3}'; - } - static const _fatRadixTable = const[0, 0, 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2, 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3, 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4 * 4, 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5, 6 * 6 * 6 * 6 * 6 * 6 * 6, 7 * 7 * 7 * 7 * 7 * 7 * 7, 8 * 8 * 8 * 8 * 8 * 8, 9 * 9 * 9 * 9 * 9 * 9, 10 * 10 * 10 * 10 * 10 * 10, 11 * 11 * 11 * 11 * 11, 12 * 12 * 12 * 12 * 12, 13 * 13 * 13 * 13 * 13, 14 * 14 * 14 * 14 * 14, 15 * 15 * 15 * 15 * 15, 16 * 16 * 16 * 16 * 16, 17 * 17 * 17 * 17, 18 * 18 * 18 * 18, 19 * 19 * 19 * 19, 20 * 20 * 20 * 20, 21 * 21 * 21 * 21, 22 * 22 * 22 * 22, 23 * 23 * 23 * 23, 24 * 24 * 24 * 24, 25 * 25 * 25 * 25, 26 * 26 * 26 * 26, 27 * 27 * 27 * 27, 28 * 28 * 28 * 28, 29 * 29 * 29 * 29, 30 * 30 * 30 * 30, 31 * 31 * 31 * 31, 32 * 32 * 32 * 32, 33 * 33 * 33, 34 * 34 * 34, 35 * 35 * 35, 36 * 36 * 36]; - static Int64 _masked_A(int a0, int a1, int a2) => new Int64._bits(_MASK & a0, _MASK & a1, _MASK2 & a2); - static Int64 _sub(int a0, int a1, int a2, int b0, int b1, int b2) { - int diff0 = a0 - b0; - int diff1 = a1 - b1 - ((diff0 >> _BITS) & 1); - int diff2 = a2 - b2 - ((diff1 >> _BITS) & 1); - return _masked_A(diff0, diff1, diff2); - } - static Int64 _negate(int b0, int b1, int b2) { - return _sub(0, 0, 0, b0, b1, b2); - } - static bool _haveBigIntsCached = null; - static bool get _haveBigInts { - if (_haveBigIntsCached == null) { - var x_A = 9007199254740992; - if (2 + 2 != 4) { - x_A = 0; - } - var y_A = x_A + 1; - var same = y_A == x_A; - _haveBigIntsCached = !same; - } - return _haveBigIntsCached; - } - static int _shiftRight(int x_A, int n) { - if (x_A >= 0) { - return x_A >> n; - } else { - int shifted = x_A >> n; - if (shifted >= 0x80000000) { - shifted -= 4294967296; - } - return shifted; - } - } - static Int64 _divide(Int64 a, other, int what) { - Int64 b = _promote(other); - if (b.isZero) { - throw new IntegerDivisionByZeroException(); - } - if (a.isZero) return ZERO_A; - bool aNeg = a.isNegative; - bool bNeg = b.isNegative; - a = a.abs(); - b = b.abs(); - int a0 = a._l; - int a1 = a._m; - int a2 = a._h_A; - int b0 = b._l; - int b1 = b._m; - int b2 = b._h_A; - return _divideHelper(a0, a1, a2, aNeg, b0, b1, b2, bNeg, what); - } - static const _RETURN_DIV = 1; - static const _RETURN_REM = 2; - static const _RETURN_MOD = 3; - static _divideHelper(int a0, int a1, int a2, bool aNeg, int b0, int b1, int b2, bool bNeg, int what) { - int q0 = 0, q1 = 0, q2 = 0; - int r0 = 0, r1 = 0, r2 = 0; - if (b2 == 0 && b1 == 0 && b0 < (1 << (30 - _BITS))) { - q2 = a2 ~/ b0; - int carry = a2 - q2 * b0; - int d1 = a1 + (carry << _BITS); - q1 = d1 ~/ b0; - carry = d1 - q1 * b0; - int d0 = a0 + (carry << _BITS); - q0 = d0 ~/ b0; - r0 = d0 - q0 * b0; - } else { - const double K2 = 17592186044416.0; - const double K1 = 4194304.0; - double ad = a0 + K1 * a1 + K2 * a2; - double bd = b0 + K1 * b1 + K2 * b2; - double qd = (ad / bd).floorToDouble(); - double q2d = (qd / K2).floorToDouble(); - qd = qd - K2 * q2d; - double q1d = (qd / K1).floorToDouble(); - double q0d = qd - K1 * q1d; - q2 = q2d.toInt(); - q1 = q1d.toInt(); - q0 = q0d.toInt(); - assert(q0 + K1 * q1 + K2 * q2 == (ad / bd).floorToDouble()); - assert(q2 == 0 || b2 == 0); - double p0d = q0d * b0; - double p0carry = (p0d / K1).floorToDouble(); - p0d = p0d - p0carry * K1; - double p1d = q1d * b0 + q0d * b1 + p0carry; - double p1carry = (p1d / K1).floorToDouble(); - p1d = p1d - p1carry * K1; - double p2d = q2d * b0 + q1d * b1 + q0d * b2 + p1carry; - assert(p2d <= _MASK2); - int diff0 = a0 - p0d.toInt(); - int diff1 = a1 - p1d.toInt() - ((diff0 >> _BITS) & 1); - int diff2 = a2 - p2d.toInt() - ((diff1 >> _BITS) & 1); - r0 = _MASK & diff0; - r1 = _MASK & diff1; - r2 = _MASK2 & diff2; - while (r2 >= _SIGN_BIT_MASK || r2 > b2 || (r2 == b2 && (r1 > b1 || (r1 == b1 && r0 >= b0)))) { - int m = (r2 & _SIGN_BIT_MASK) == 0 ? 1 : -1; - int d0 = r0 - m * b0; - int d1 = r1 - m * (b1 + ((d0 >> _BITS) & 1)); - int d2 = r2 - m * (b2 + ((d1 >> _BITS) & 1)); - r0 = _MASK & d0; - r1 = _MASK & d1; - r2 = _MASK2 & d2; - d0 = q0 + m; - d1 = q1 + m * ((d0 >> _BITS) & 1); - d2 = q2 + m * ((d1 >> _BITS) & 1); - q0 = _MASK & d0; - q1 = _MASK & d1; - q2 = _MASK2 & d2; - } - } - assert(Int64.ZERO_A <= new Int64._bits(r0, r1, r2)); - assert(r2 < b2 || new Int64._bits(r0, r1, r2) < new Int64._bits(b0, b1, b2)); - assert(what == _RETURN_DIV || what == _RETURN_MOD || what == _RETURN_REM); - if (what == _RETURN_DIV) { - if (aNeg != bNeg) return _negate(q0, q1, q2); - return Int64._masked_A(q0, q1, q2); - } - if (!aNeg) { - return Int64._masked_A(r0, r1, r2); - } - if (what == _RETURN_MOD) { - if (r0 == 0 && r1 == 0 && r2 == 0) { - return ZERO_A; - } else { - return _sub(b0, b1, b2, r0, r1, r2); - } - } else { - return _negate(r0, r1, r2); - } - } -} -abstract class IntX implements Comparable { - IntX operator+(other); - IntX operator-(other); - IntX operator-(); - IntX operator*(other); - IntX operator%(other); - IntX operator~/(other); - IntX remainder(other); - IntX operator&(other); - IntX operator|(other); - IntX operator^(other); - IntX operator~(); - IntX operator<<(int shiftAmount); - IntX operator>>(int shiftAmount); - bool operator==(other); - bool operator<(other); - bool operator<=(other); - bool operator>(other); - bool operator>=(other); - bool get isNegative; - bool get isZero; - int get hashCode; - IntX abs(); - List toBytes(); - int toInt(); - Int64 toInt64(); - String toString(); - String toRadixString(int radix); -} -final Context url = new Context(style: Style.url_A); -final Context context_A = createInternal(); -String get current_A { - var uri_A = Uri.base; - if (Style.platform == Style.url_A) { - return uri_A.resolve('.').toString(); - } else { - var path_A = uri_A.toFilePath(); - int lastIndex = path_A.length - 1; - assert(path_A[lastIndex] == '/' || path_A[lastIndex] == '\\'); - return path_A.substring(0, lastIndex); - } -} -String withoutExtension(String path_A) => context_A.withoutExtension_A(path_A); -const SLASH_A = 0x2f; -const COLON_A = 0x3a; -const UPPER_A = 0x41; -const UPPER_Z = 0x5a; -const LOWER_A = 0x61; -const LOWER_Z = 0x7a; -const BACKSLASH_A = 0x5c; -Context createInternal() => new Context._internal_A(); -class Context { - factory Context({Style style, String current}) { - if (current == null) { - if (style == null) { - current = current_A; - } else { - current = "."; - } - } - if (style == null) { - style = Style.platform; - } else if (style is! InternalStyle) { - throw new ArgumentError("Only styles defined by the path package are " "allowed."); - } - return new Context.__A(style as InternalStyle, current); - } - Context._internal_A() : style = Style.platform as InternalStyle, _current_A = null; - Context.__A(this.style, this._current_A); - final InternalStyle style; - final String _current_A; - String get current => _current_A != null ? _current_A : current_A; - String get separator => style.separator; - String absolute(String part1, [String part2, String part3, String part4, String part5, String part6, String part7]) { - return join(current, part1, part2, part3, part4, part5, part6, part7); - } - String basenameWithoutExtension(String path_A) => _parse_A(path_A).basenameWithoutExtension; - String dirname(String path_A) { - var parsed = _parse_A(path_A); - parsed.removeTrailingSeparators(); - if (parsed.parts.isEmpty) return parsed.root == null ? '.' : parsed.root; - if (parsed.parts.length == 1) { - return parsed.root == null ? '.' : parsed.root; - } - parsed.parts.removeLast(); - parsed.separators.removeLast(); - parsed.removeTrailingSeparators(); - return parsed.toString(); - } - String extension(String path_A) => _parse_A(path_A).extension; - String rootPrefix(String path_A) => path_A.substring(0, style.rootLength(path_A)); - bool isAbsolute(String path_A) => style.rootLength(path_A) > 0; - bool isRelative(String path_A) => !this.isAbsolute(path_A); - bool isRootRelative(String path_A) => style.isRootRelative(path_A); - String join(String part1, [String part2, String part3, String part4, String part5, String part6, String part7, String part8]) { - var parts = [part1, part2, part3, part4, part5, part6, part7, part8]; - _validateArgList("join", parts); - return joinAll(parts.where((part_A) => part_A != null)); - } - String joinAll(Iterable parts) { - var buffer_A = new StringBuffer(); - var needsSeparator = false; - var isAbsoluteAndNotRootRelative = false; - for (var part_A in parts.where((part_A) => part_A != '')) { - if (this.isRootRelative(part_A) && isAbsoluteAndNotRootRelative) { - var parsed = _parse_A(part_A); - parsed.root = this.rootPrefix(buffer_A.toString()); - if (style.needsSeparator(parsed.root)) { - parsed.separators[0] = style.separator; - } - buffer_A.clear(); - buffer_A.write(parsed.toString()); - } else if (this.isAbsolute(part_A)) { - isAbsoluteAndNotRootRelative = !this.isRootRelative(part_A); - buffer_A.clear(); - buffer_A.write(part_A); - } else { - if (part_A.length > 0 && style.containsSeparator(part_A[0])) {} else if (needsSeparator) { - buffer_A.write(separator); - } - buffer_A.write(part_A); - } - needsSeparator = style.needsSeparator(part_A); - } - return buffer_A.toString(); - } - List split(String path_A) { - var parsed = _parse_A(path_A); - parsed.parts = parsed.parts.where((part_A) => !part_A.isEmpty).toList(); - if (parsed.root != null) parsed.parts.insert(0, parsed.root); - return parsed.parts; - } - String normalize(String path_A) { - var parsed = _parse_A(path_A); - parsed.normalize(); - return parsed.toString(); - } - String relative(String path_A, {String from}) { - if (from == null) { - from = current; - } else if (this.isRelative(from) || this.isRootRelative(from)) { - from = this.join(current, from); - } - if (this.isRelative(from) && this.isAbsolute(path_A)) { - return this.normalize(path_A); - } - if (this.isRelative(path_A) || this.isRootRelative(path_A)) { - path_A = this.absolute(path_A); - } - if (this.isRelative(path_A) && this.isAbsolute(from)) { - throw new PathException('Unable to find a path to "${path_A}" from "${from}".'); - } - var fromParsed = _parse_A(from) - ..normalize(); - var pathParsed = _parse_A(path_A) - ..normalize(); - if (fromParsed.parts.length > 0 && fromParsed.parts[0] == '.') { - return pathParsed.toString(); - } - if (fromParsed.root != pathParsed.root && ((fromParsed.root == null || pathParsed.root == null) || fromParsed.root.toLowerCase().replaceAll('/', '\\') != pathParsed.root.toLowerCase().replaceAll('/', '\\'))) { - return pathParsed.toString(); - } - while (fromParsed.parts.length > 0 && pathParsed.parts.length > 0 && fromParsed.parts[0] == pathParsed.parts[0]) { - fromParsed.parts.removeAt(0); - fromParsed.separators.removeAt(1); - pathParsed.parts.removeAt(0); - pathParsed.separators.removeAt(1); - } - if (fromParsed.parts.length > 0 && fromParsed.parts[0] == '..') { - throw new PathException('Unable to find a path to "${path_A}" from "${from}".'); - } - pathParsed.parts.insertAll(0, new List.filled(fromParsed.parts.length, '..')); - pathParsed.separators[0] = ''; - pathParsed.separators.insertAll(1, new List.filled(fromParsed.parts.length, style.separator)); - if (pathParsed.parts.length == 0) return '.'; - if (pathParsed.parts.length > 1 && pathParsed.parts.last == '.') { - pathParsed.parts.removeLast(); - pathParsed.separators - ..removeLast() - ..removeLast() - ..add(''); - } - pathParsed.root = ''; - pathParsed.removeTrailingSeparators(); - return pathParsed.toString(); - } - String withoutExtension_A(String path_A) { - var parsed = _parse_A(path_A); - for (var i = parsed.parts.length - 1; i >= 0; i--) { - if (!parsed.parts[i].isEmpty) { - parsed.parts[i] = parsed.basenameWithoutExtension; - break; - } - } - return parsed.toString(); - } - String fromUri_A(uri_A) { - if (uri_A is String) uri_A = Uri.parse(uri_A); - return style.pathFromUri(uri_A); - } - Uri toUri(String path_A) { - if (isRelative(path_A)) { - return style.relativePathToUri(path_A); - } else { - return style.absolutePathToUri(join(current, path_A)); - } - } - ParsedPath _parse_A(String path_A) => new ParsedPath.parse_A(path_A, style); -} -_validateArgList(String method_A, List args) { - for (var i = 1; i < args.length; i++) { - if (args[i] == null || args[i - 1] != null) continue; - var numArgs; - for (numArgs = args.length; numArgs >= 1; numArgs--) { - if (args[numArgs - 1] != null) break; - } - var message_A = new StringBuffer(); - message_A.write("${method_A}("); - message_A.write(args.take(numArgs).map((arg) => arg == null ? "null" : '"${arg}"').join(", ")); - message_A.write("): part ${i - 1} was null, but part ${i} was not."); - throw new ArgumentError(message_A.toString()); - } -} -abstract class InternalStyle extends Style { - String get separator; - bool containsSeparator(String path_A); - bool isSeparator(int codeUnit); - bool needsSeparator(String path_A); - int rootLength(String path_A); - String getRoot(String path_A) { - var length_A = rootLength(path_A); - if (length_A > 0) return path_A.substring(0, length_A); - return isRootRelative(path_A) ? path_A[0] : null; - } - bool isRootRelative(String path_A); - String pathFromUri(Uri uri_A); - Uri relativePathToUri(String path_A) { - var segments = context.split(path_A); - if (isSeparator(path_A.codeUnitAt(path_A.length - 1))) segments.add(''); - return new Uri(pathSegments: segments); - } - Uri absolutePathToUri(String path_A); -} -class ParsedPath { - InternalStyle style; - String root; - bool isRootRelative; - List parts; - List separators; - String get extension => _splitExtension()[1]; - bool get isAbsolute => root != null; - factory ParsedPath.parse_A(String path_A, InternalStyle style_A) { - var root_A = style_A.getRoot(path_A); - var isRootRelative_A = style_A.isRootRelative(path_A); - if (root_A != null) path_A = path_A.substring(root_A.length); - var parts_A = []; - var separators_A = []; - var start_A = 0; - if (path_A.isNotEmpty && style_A.isSeparator(path_A.codeUnitAt(0))) { - separators_A.add(path_A[0]); - start_A = 1; - } else { - separators_A.add(''); - } - for (var i = start_A; i < path_A.length; i++) { - if (style_A.isSeparator(path_A.codeUnitAt(i))) { - parts_A.add(path_A.substring(start_A, i)); - separators_A.add(path_A[i]); - start_A = i + 1; - } - } - if (start_A < path_A.length) { - parts_A.add(path_A.substring(start_A)); - separators_A.add(''); - } - return new ParsedPath.__B(style_A, root_A, isRootRelative_A, parts_A, separators_A); - } - ParsedPath.__B(this.style, this.root, this.isRootRelative, this.parts, this.separators); - String get basenameWithoutExtension => _splitExtension()[0]; - bool get hasTrailingSeparator => !parts.isEmpty && (parts.last == '' || separators.last != ''); - void removeTrailingSeparators() { - while (!parts.isEmpty && parts.last == '') { - parts.removeLast(); - separators.removeLast(); - } - if (separators.length > 0) separators[separators.length - 1] = ''; - } - void normalize() { - var leadingDoubles = 0; - var newParts = []; - for (var part_A in parts) { - if (part_A == '.' || part_A == '') {} else if (part_A == '..') { - if (newParts.length > 0) { - newParts.removeLast(); - } else { - leadingDoubles++; - } - } else { - newParts.add(part_A); - } - } - if (!isAbsolute) { - newParts.insertAll(0, new List.filled(leadingDoubles, '..')); - } - if (newParts.length == 0 && !isAbsolute) { - newParts.add('.'); - } - var newSeparators = new List.generate(newParts.length, (__H) => style.separator, growable: true); - newSeparators.insert(0, isAbsolute && newParts.length > 0 && style.needsSeparator(root) ? style.separator : ''); - parts = newParts; - separators = newSeparators; - if (root != null && style == Style.windows) { - root = root.replaceAll('/', '\\'); - } - removeTrailingSeparators(); - } - String toString() { - var builder_A = new StringBuffer(); - if (root != null) builder_A.write(root); - for (var i = 0; i < parts.length; i++) { - builder_A.write(separators[i]); - builder_A.write(parts[i]); - } - builder_A.write(separators.last); - return builder_A.toString(); - } - List _splitExtension() { - var file_A = parts.lastWhere((p) => p != '', orElse: () => null); - if (file_A == null) return ['', '']; - if (file_A == '..') return ['..', '']; - var lastDot = file_A.lastIndexOf('.'); - if (lastDot <= 0) return [file_A, '']; - return [file_A.substring(0, lastDot), file_A.substring(lastDot)]; - } - ParsedPath clone() => new ParsedPath.__B(style, root, isRootRelative, new List.from(parts), new List.from(separators)); -} -class PathException implements Exception { - String message; - PathException(this.message); - String toString() => "PathException: ${message}"; -} -abstract class Style { - static final Style posix = new PosixStyle(); - static final Style windows = new WindowsStyle(); - static final Style url_A = new UrlStyle(); - static final Style platform = _getPlatformStyle(); - static Style _getPlatformStyle() { - if (Uri.base.scheme != 'file') return Style.url_A; - if (!Uri.base.path.endsWith('/')) return Style.url_A; - if (new Uri(path: 'a/b').toFilePath() == 'a\\b') return Style.windows; - return Style.posix; - } - String get name; - Context get context => new Context(style: this); - String get separator; - String getRoot(String path_A); - String pathFromUri(Uri uri_A); - Uri relativePathToUri(String path_A); - Uri absolutePathToUri(String path_A); - String toString() => name; -} -class PosixStyle extends InternalStyle { - PosixStyle(); - final name = 'posix'; - final separator = '/'; - final separators = const['/']; - final separatorPattern = new RegExp(r'/'); - final needsSeparatorPattern = new RegExp(r'[^/]$'); - final rootPattern = new RegExp(r'^/'); - final relativeRootPattern = null; - bool containsSeparator(String path_A) => path_A.contains('/'); - bool isSeparator(int codeUnit) => codeUnit == SLASH_A; - bool needsSeparator(String path_A) => path_A.isNotEmpty && !isSeparator(path_A.codeUnitAt(path_A.length - 1)); - int rootLength(String path_A) { - if (path_A.isNotEmpty && isSeparator(path_A.codeUnitAt(0))) return 1; - return 0; - } - bool isRootRelative(String path_A) => false; - String pathFromUri(Uri uri_A) { - if (uri_A.scheme == '' || uri_A.scheme == 'file') { - return Uri.decodeComponent(uri_A.path); - } - throw new ArgumentError("Uri ${uri_A} must have scheme 'file:'."); - } - Uri absolutePathToUri(String path_A) { - var parsed = new ParsedPath.parse_A(path_A, this); - if (parsed.parts.isEmpty) { - parsed.parts.addAll(["", ""]); - } else if (parsed.hasTrailingSeparator) { - parsed.parts.add(""); - } - return new Uri(scheme: 'file', pathSegments: parsed.parts); - } -} -class UrlStyle extends InternalStyle { - UrlStyle(); - final name = 'url'; - final separator = '/'; - final separators = const['/']; - final separatorPattern = new RegExp(r'/'); - final needsSeparatorPattern = new RegExp(r"(^[a-zA-Z][-+.a-zA-Z\d]*://|[^/])$"); - final rootPattern = new RegExp(r"[a-zA-Z][-+.a-zA-Z\d]*://[^/]*"); - final relativeRootPattern = new RegExp(r"^/"); - bool containsSeparator(String path_A) => path_A.contains('/'); - bool isSeparator(int codeUnit) => codeUnit == SLASH_A; - bool needsSeparator(String path_A) { - if (path_A.isEmpty) return false; - if (!isSeparator(path_A.codeUnitAt(path_A.length - 1))) return true; - return path_A.endsWith("://") && rootLength(path_A) == path_A.length; - } - int rootLength(String path_A) { - if (path_A.isEmpty) return 0; - if (isSeparator(path_A.codeUnitAt(0))) return 1; - var index_A = path_A.indexOf("/"); - if (index_A > 0 && path_A.startsWith('://', index_A - 1)) { - index_A = path_A.indexOf('/', index_A + 2); - if (index_A > 0) return index_A; - return path_A.length; - } - return 0; - } - bool isRootRelative(String path_A) => path_A.isNotEmpty && isSeparator(path_A.codeUnitAt(0)); - String pathFromUri(Uri uri_A) => uri_A.toString(); - Uri relativePathToUri(String path_A) => Uri.parse(path_A); - Uri absolutePathToUri(String path_A) => Uri.parse(path_A); -} -class WindowsStyle extends InternalStyle { - WindowsStyle(); - final name = 'windows'; - final separator = '\\'; - final separators = const['/', '\\']; - final separatorPattern = new RegExp(r'[/\\]'); - final needsSeparatorPattern = new RegExp(r'[^/\\]$'); - final rootPattern = new RegExp(r'^(\\\\[^\\]+\\[^\\/]+|[a-zA-Z]:[/\\])'); - final relativeRootPattern = new RegExp(r"^[/\\](?![/\\])"); - bool containsSeparator(String path_A) => path_A.contains('/'); - bool isSeparator(int codeUnit) => codeUnit == SLASH_A || codeUnit == BACKSLASH_A; - bool needsSeparator(String path_A) { - if (path_A.isEmpty) return false; - return !isSeparator(path_A.codeUnitAt(path_A.length - 1)); - } - int rootLength(String path_A) { - if (path_A.isEmpty) return 0; - if (path_A.codeUnitAt(0) == SLASH_A) return 1; - if (path_A.codeUnitAt(0) == BACKSLASH_A) { - if (path_A.length < 2 || path_A.codeUnitAt(1) != BACKSLASH_A) return 1; - var index_A = path_A.indexOf('\\', 2); - if (index_A > 0) { - index_A = path_A.indexOf('\\', index_A + 1); - if (index_A > 0) return index_A; - } - return path_A.length; - } - if (path_A.length < 3) return 0; - if (!isAlphabetic(path_A.codeUnitAt(0))) return 0; - if (path_A.codeUnitAt(1) != COLON_A) return 0; - if (!isSeparator(path_A.codeUnitAt(2))) return 0; - return 3; - } - bool isRootRelative(String path_A) => rootLength(path_A) == 1; - String pathFromUri(Uri uri_A) { - if (uri_A.scheme != '' && uri_A.scheme != 'file') { - throw new ArgumentError("Uri ${uri_A} must have scheme 'file:'."); - } - var path_A = uri_A.path; - if (uri_A.host == '') { - if (path_A.startsWith('/')) path_A = path_A.replaceFirst("/", ""); - } else { - path_A = '\\\\${uri_A.host}${path_A}'; - } - return Uri.decodeComponent(path_A.replaceAll("/", "\\")); - } - Uri absolutePathToUri(String path_A) { - var parsed = new ParsedPath.parse_A(path_A, this); - if (parsed.root.startsWith(r'\\')) { - var rootParts = parsed.root.split('\\').where((part_A) => part_A != ''); - parsed.parts.insert(0, rootParts.last); - if (parsed.hasTrailingSeparator) { - parsed.parts.add(""); - } - return new Uri(scheme: 'file', host: rootParts.first, pathSegments: parsed.parts); - } else { - if (parsed.parts.length == 0 || parsed.hasTrailingSeparator) { - parsed.parts.add(""); - } - parsed.parts.insert(0, parsed.root.replaceAll("/", "").replaceAll("\\", "")); - return new Uri(scheme: 'file', pathSegments: parsed.parts); - } - } -} -bool isAlphabetic(int char) => (char >= UPPER_A && char <= UPPER_Z) || (char >= LOWER_A && char <= LOWER_Z); -class CodeGeneratorRequest extends GeneratedMessage { - static final BuilderInfo _i = new BuilderInfo('CodeGeneratorRequest') - ..p(1, 'fileToGenerate', PbFieldType.PS) - ..a(2, 'parameter', PbFieldType.OS) - ..pp(15, 'protoFile', PbFieldType.PM, FileDescriptorProto.$checkItem, FileDescriptorProto.create_A); - CodeGeneratorRequest() : super(); - CodeGeneratorRequest.fromBuffer(List i, [ExtensionRegistry r = ExtensionRegistry.EMPTY]) : super.fromBuffer_A(i, r); - CodeGeneratorRequest clone() => new CodeGeneratorRequest() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i; - List get fileToGenerate => getField(1); - String get parameter => getField(2); - List get protoFile => getField(15); -} -class CodeGeneratorResponse_File extends GeneratedMessage { - static final BuilderInfo _i_A = new BuilderInfo('CodeGeneratorResponse_File') - ..a(1, 'name', PbFieldType.OS) - ..a(2, 'insertionPoint', PbFieldType.OS) - ..a(15, 'content', PbFieldType.OS) - ..hasRequiredFields = false; - CodeGeneratorResponse_File() : super(); - CodeGeneratorResponse_File clone() => new CodeGeneratorResponse_File() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_A; - static CodeGeneratorResponse_File create_B() => new CodeGeneratorResponse_File(); - static void $checkItem_A(CodeGeneratorResponse_File v) { - if (v is! CodeGeneratorResponse_File) checkItemFailed(v, 'CodeGeneratorResponse_File'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - void set content(String v) { - setField(15, v); - } -} -class CodeGeneratorResponse extends GeneratedMessage { - static final BuilderInfo _i_B = new BuilderInfo('CodeGeneratorResponse') - ..a(1, 'error', PbFieldType.OS) - ..pp(15, 'file', PbFieldType.PM, CodeGeneratorResponse_File.$checkItem_A, CodeGeneratorResponse_File.create_B) - ..hasRequiredFields = false; - CodeGeneratorResponse() : super(); - CodeGeneratorResponse clone() => new CodeGeneratorResponse() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_B; - String get error => getField(1); - void set error(String v) { - setField(1, v); - } - List get file => getField(15); -} -class FileDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_C = new BuilderInfo('FileDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..a(2, 'package', PbFieldType.OS) - ..p(3, 'dependency', PbFieldType.PS) - ..p(10, 'publicDependency', PbFieldType.P3) - ..p(11, 'weakDependency', PbFieldType.P3) - ..pp(4, 'messageType', PbFieldType.PM, DescriptorProto.$checkItem_B, DescriptorProto.create_C) - ..pp(5, 'enumType', PbFieldType.PM, EnumDescriptorProto.$checkItem_C, EnumDescriptorProto.create_D) - ..pp(6, 'service', PbFieldType.PM, ServiceDescriptorProto.$checkItem_D, ServiceDescriptorProto.create_E) - ..pp(7, 'extension', PbFieldType.PM, FieldDescriptorProto.$checkItem_E, FieldDescriptorProto.create_F) - ..a(8, 'options', PbFieldType.OM, FileOptions.getDefault, FileOptions.create_G) - ..a(9, 'sourceCodeInfo', PbFieldType.OM, SourceCodeInfo.getDefault_A, SourceCodeInfo.create_H); - FileDescriptorProto() : super(); - FileDescriptorProto clone() => new FileDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_C; - static FileDescriptorProto create_A() => new FileDescriptorProto(); - static void $checkItem(FileDescriptorProto v) { - if (v is! FileDescriptorProto) checkItemFailed(v, 'FileDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - String get package => getField(2); - List get messageType => getField(4); - List get enumType => getField(5); - List get service => getField(6); - List get extension => getField(7); - FileOptions get options => getField(8); - bool hasOptions() => hasField(8); -} -class DescriptorProto_ExtensionRange extends GeneratedMessage { - static final BuilderInfo _i_D = new BuilderInfo('DescriptorProto_ExtensionRange') - ..a(1, 'start', PbFieldType.O3) - ..a(2, 'end', PbFieldType.O3) - ..hasRequiredFields = false; - DescriptorProto_ExtensionRange() : super(); - DescriptorProto_ExtensionRange clone() => new DescriptorProto_ExtensionRange() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_D; - static DescriptorProto_ExtensionRange create_I() => new DescriptorProto_ExtensionRange(); - static void $checkItem_F(DescriptorProto_ExtensionRange v) { - if (v is! DescriptorProto_ExtensionRange) checkItemFailed(v, 'DescriptorProto_ExtensionRange'); - } - int get start => getField(1); - int get end => getField(2); -} -class DescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_E = new BuilderInfo('DescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..pp(2, 'field', PbFieldType.PM, FieldDescriptorProto.$checkItem_E, FieldDescriptorProto.create_F) - ..pp(6, 'extension', PbFieldType.PM, FieldDescriptorProto.$checkItem_E, FieldDescriptorProto.create_F) - ..pp(3, 'nestedType', PbFieldType.PM, DescriptorProto.$checkItem_B, DescriptorProto.create_C) - ..pp(4, 'enumType', PbFieldType.PM, EnumDescriptorProto.$checkItem_C, EnumDescriptorProto.create_D) - ..pp(5, 'extensionRange', PbFieldType.PM, DescriptorProto_ExtensionRange.$checkItem_F, DescriptorProto_ExtensionRange.create_I) - ..a(7, 'options', PbFieldType.OM, MessageOptions.getDefault_B, MessageOptions.create_J); - DescriptorProto() : super(); - DescriptorProto clone() => new DescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_E; - static DescriptorProto create_C() => new DescriptorProto(); - static void $checkItem_B(DescriptorProto v) { - if (v is! DescriptorProto) checkItemFailed(v, 'DescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - List get field => getField(2); - List get extension => getField(6); - List get nestedType => getField(3); - List get enumType => getField(4); - List get extensionRange => getField(5); - MessageOptions get options => getField(7); - bool hasOptions() => hasField(7); -} -class FieldDescriptorProto_Type extends ProtobufEnum { - static const FieldDescriptorProto_Type TYPE_DOUBLE = const FieldDescriptorProto_Type.__C(1, 'TYPE_DOUBLE'); - static const FieldDescriptorProto_Type TYPE_FLOAT = const FieldDescriptorProto_Type.__C(2, 'TYPE_FLOAT'); - static const FieldDescriptorProto_Type TYPE_INT64 = const FieldDescriptorProto_Type.__C(3, 'TYPE_INT64'); - static const FieldDescriptorProto_Type TYPE_UINT64 = const FieldDescriptorProto_Type.__C(4, 'TYPE_UINT64'); - static const FieldDescriptorProto_Type TYPE_INT32 = const FieldDescriptorProto_Type.__C(5, 'TYPE_INT32'); - static const FieldDescriptorProto_Type TYPE_FIXED64 = const FieldDescriptorProto_Type.__C(6, 'TYPE_FIXED64'); - static const FieldDescriptorProto_Type TYPE_FIXED32 = const FieldDescriptorProto_Type.__C(7, 'TYPE_FIXED32'); - static const FieldDescriptorProto_Type TYPE_BOOL = const FieldDescriptorProto_Type.__C(8, 'TYPE_BOOL'); - static const FieldDescriptorProto_Type TYPE_STRING = const FieldDescriptorProto_Type.__C(9, 'TYPE_STRING'); - static const FieldDescriptorProto_Type TYPE_GROUP = const FieldDescriptorProto_Type.__C(10, 'TYPE_GROUP'); - static const FieldDescriptorProto_Type TYPE_MESSAGE = const FieldDescriptorProto_Type.__C(11, 'TYPE_MESSAGE'); - static const FieldDescriptorProto_Type TYPE_BYTES = const FieldDescriptorProto_Type.__C(12, 'TYPE_BYTES'); - static const FieldDescriptorProto_Type TYPE_UINT32 = const FieldDescriptorProto_Type.__C(13, 'TYPE_UINT32'); - static const FieldDescriptorProto_Type TYPE_ENUM = const FieldDescriptorProto_Type.__C(14, 'TYPE_ENUM'); - static const FieldDescriptorProto_Type TYPE_SFIXED32 = const FieldDescriptorProto_Type.__C(15, 'TYPE_SFIXED32'); - static const FieldDescriptorProto_Type TYPE_SFIXED64 = const FieldDescriptorProto_Type.__C(16, 'TYPE_SFIXED64'); - static const FieldDescriptorProto_Type TYPE_SINT32 = const FieldDescriptorProto_Type.__C(17, 'TYPE_SINT32'); - static const FieldDescriptorProto_Type TYPE_SINT64 = const FieldDescriptorProto_Type.__C(18, 'TYPE_SINT64'); - static const List values_A = const[TYPE_DOUBLE, TYPE_FLOAT, TYPE_INT64, TYPE_UINT64, TYPE_INT32, TYPE_FIXED64, TYPE_FIXED32, TYPE_BOOL, TYPE_STRING, TYPE_GROUP, TYPE_MESSAGE, TYPE_BYTES, TYPE_UINT32, TYPE_ENUM, TYPE_SFIXED32, TYPE_SFIXED64, TYPE_SINT32, TYPE_SINT64]; - static final Map _byValue = ProtobufEnum.initByValue(values_A); - static FieldDescriptorProto_Type valueOf(int value_A) => _byValue[value_A]; - const FieldDescriptorProto_Type.__C(int v, String n) : super(v, n); -} -class FieldDescriptorProto_Label extends ProtobufEnum { - static const FieldDescriptorProto_Label LABEL_OPTIONAL = const FieldDescriptorProto_Label.__D(1, 'LABEL_OPTIONAL'); - static const FieldDescriptorProto_Label LABEL_REQUIRED = const FieldDescriptorProto_Label.__D(2, 'LABEL_REQUIRED'); - static const FieldDescriptorProto_Label LABEL_REPEATED = const FieldDescriptorProto_Label.__D(3, 'LABEL_REPEATED'); - static const List values_B = const[LABEL_OPTIONAL, LABEL_REQUIRED, LABEL_REPEATED]; - static final Map _byValue_A = ProtobufEnum.initByValue(values_B); - static FieldDescriptorProto_Label valueOf_A(int value_A) => _byValue_A[value_A]; - const FieldDescriptorProto_Label.__D(int v, String n) : super(v, n); -} -class FieldDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_F = new BuilderInfo('FieldDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..a(3, 'number', PbFieldType.O3) - ..e(4, 'label', PbFieldType.OE, FieldDescriptorProto_Label.LABEL_OPTIONAL, FieldDescriptorProto_Label.valueOf_A) - ..e(5, 'type', PbFieldType.OE, FieldDescriptorProto_Type.TYPE_DOUBLE, FieldDescriptorProto_Type.valueOf) - ..a(6, 'typeName', PbFieldType.OS) - ..a(2, 'extendee', PbFieldType.OS) - ..a(7, 'defaultValue', PbFieldType.OS) - ..a(8, 'options', PbFieldType.OM, FieldOptions.getDefault_C, FieldOptions.create_K); - FieldDescriptorProto() : super(); - FieldDescriptorProto clone() => new FieldDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_F; - static FieldDescriptorProto create_F() => new FieldDescriptorProto(); - static void $checkItem_E(FieldDescriptorProto v) { - if (v is! FieldDescriptorProto) checkItemFailed(v, 'FieldDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - int get number => getField(3); - FieldDescriptorProto_Label get label => getField(4); - FieldDescriptorProto_Type get type => getField(5); - String get typeName => getField(6); - String get extendee => getField(2); - String get defaultValue => getField(7); - bool hasDefaultValue() => hasField(7); - FieldOptions get options => getField(8); - bool hasOptions() => hasField(8); -} -class EnumDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_G = new BuilderInfo('EnumDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..pp(2, 'value', PbFieldType.PM, EnumValueDescriptorProto.$checkItem_G, EnumValueDescriptorProto.create_L) - ..a(3, 'options', PbFieldType.OM, EnumOptions.getDefault_D, EnumOptions.create_M); - EnumDescriptorProto() : super(); - EnumDescriptorProto clone() => new EnumDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_G; - static EnumDescriptorProto create_D() => new EnumDescriptorProto(); - static void $checkItem_C(EnumDescriptorProto v) { - if (v is! EnumDescriptorProto) checkItemFailed(v, 'EnumDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - List get value => getField(2); - EnumOptions get options => getField(3); - bool hasOptions() => hasField(3); -} -class EnumValueDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_H = new BuilderInfo('EnumValueDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..a(2, 'number', PbFieldType.O3) - ..a(3, 'options', PbFieldType.OM, EnumValueOptions.getDefault_E, EnumValueOptions.create_N); - EnumValueDescriptorProto() : super(); - EnumValueDescriptorProto clone() => new EnumValueDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_H; - static EnumValueDescriptorProto create_L() => new EnumValueDescriptorProto(); - static void $checkItem_G(EnumValueDescriptorProto v) { - if (v is! EnumValueDescriptorProto) checkItemFailed(v, 'EnumValueDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - int get number => getField(2); - EnumValueOptions get options => getField(3); - bool hasOptions() => hasField(3); -} -class ServiceDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_I = new BuilderInfo('ServiceDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..pp(2, 'method', PbFieldType.PM, MethodDescriptorProto.$checkItem_H, MethodDescriptorProto.create_O) - ..pp(4, 'stream', PbFieldType.PM, StreamDescriptorProto.$checkItem_I, StreamDescriptorProto.create_P) - ..a(3, 'options', PbFieldType.OM, ServiceOptions.getDefault_F, ServiceOptions.create_Q); - ServiceDescriptorProto() : super(); - ServiceDescriptorProto clone() => new ServiceDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_I; - static ServiceDescriptorProto create_E() => new ServiceDescriptorProto(); - static void $checkItem_D(ServiceDescriptorProto v) { - if (v is! ServiceDescriptorProto) checkItemFailed(v, 'ServiceDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - List get method => getField(2); - ServiceOptions get options => getField(3); - bool hasOptions() => hasField(3); -} -class MethodDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_J = new BuilderInfo('MethodDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..a(2, 'inputType', PbFieldType.OS) - ..a(3, 'outputType', PbFieldType.OS) - ..a(4, 'options', PbFieldType.OM, MethodOptions.getDefault_G, MethodOptions.create_R); - MethodDescriptorProto() : super(); - MethodDescriptorProto clone() => new MethodDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_J; - static MethodDescriptorProto create_O() => new MethodDescriptorProto(); - static void $checkItem_H(MethodDescriptorProto v) { - if (v is! MethodDescriptorProto) checkItemFailed(v, 'MethodDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - String get inputType => getField(2); - String get outputType => getField(3); - MethodOptions get options => getField(4); - bool hasOptions() => hasField(4); -} -class StreamDescriptorProto extends GeneratedMessage { - static final BuilderInfo _i_K = new BuilderInfo('StreamDescriptorProto') - ..a(1, 'name', PbFieldType.OS) - ..a(2, 'clientMessageType', PbFieldType.OS) - ..a(3, 'serverMessageType', PbFieldType.OS) - ..a(4, 'options', PbFieldType.OM, StreamOptions.getDefault_H, StreamOptions.create_S); - StreamDescriptorProto() : super(); - StreamDescriptorProto clone() => new StreamDescriptorProto() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_K; - static StreamDescriptorProto create_P() => new StreamDescriptorProto(); - static void $checkItem_I(StreamDescriptorProto v) { - if (v is! StreamDescriptorProto) checkItemFailed(v, 'StreamDescriptorProto'); - } - String get name => getField(1); - void set name(String v) { - setField(1, v); - } - StreamOptions get options => getField(4); - bool hasOptions() => hasField(4); -} -class FileOptions_OptimizeMode extends ProtobufEnum { - static const FileOptions_OptimizeMode SPEED = const FileOptions_OptimizeMode.__E(1, 'SPEED'); - static const FileOptions_OptimizeMode CODE_SIZE = const FileOptions_OptimizeMode.__E(2, 'CODE_SIZE'); - static const FileOptions_OptimizeMode LITE_RUNTIME = const FileOptions_OptimizeMode.__E(3, 'LITE_RUNTIME'); - static const List values_C = const[SPEED, CODE_SIZE, LITE_RUNTIME]; - static final Map _byValue_B = ProtobufEnum.initByValue(values_C); - static FileOptions_OptimizeMode valueOf_B(int value_A) => _byValue_B[value_A]; - const FileOptions_OptimizeMode.__E(int v, String n) : super(v, n); -} -class FileOptions extends GeneratedMessage { - static final BuilderInfo _i_L = new BuilderInfo('FileOptions') - ..a(1, 'javaPackage', PbFieldType.OS) - ..a(8, 'javaOuterClassname', PbFieldType.OS) - ..a(10, 'javaMultipleFiles', PbFieldType.OB) - ..a(20, 'javaGenerateEqualsAndHash', PbFieldType.OB) - ..e(9, 'optimizeFor', PbFieldType.OE, FileOptions_OptimizeMode.SPEED, FileOptions_OptimizeMode.valueOf_B) - ..a(16, 'ccGenericServices', PbFieldType.OB) - ..a(17, 'javaGenericServices', PbFieldType.OB) - ..a(18, 'pyGenericServices', PbFieldType.OB) - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - FileOptions() : super(); - FileOptions clone() => new FileOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_L; - static FileOptions create_G() => new FileOptions(); - static FileOptions getDefault() { - if (_defaultInstance == null) _defaultInstance = new _ReadonlyFileOptions(); - return _defaultInstance; - } - static FileOptions _defaultInstance; -} -class _ReadonlyFileOptions extends FileOptions with ReadonlyMessageMixin {} -class MessageOptions extends GeneratedMessage { - static final BuilderInfo _i_M = new BuilderInfo('MessageOptions') - ..a(1, 'messageSetWireFormat', PbFieldType.OB) - ..a(2, 'noStandardDescriptorAccessor', PbFieldType.OB) - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - MessageOptions() : super(); - MessageOptions clone() => new MessageOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_M; - static MessageOptions create_J() => new MessageOptions(); - static MessageOptions getDefault_B() { - if (_defaultInstance_A == null) _defaultInstance_A = new _ReadonlyMessageOptions(); - return _defaultInstance_A; - } - static MessageOptions _defaultInstance_A; -} -class _ReadonlyMessageOptions extends MessageOptions with ReadonlyMessageMixin {} -class FieldOptions_CType extends ProtobufEnum { - static const FieldOptions_CType STRING = const FieldOptions_CType.__F(0, 'STRING'); - static const List values_D = const[STRING]; - static final Map _byValue_C = ProtobufEnum.initByValue(values_D); - static FieldOptions_CType valueOf_C(int value_A) => _byValue_C[value_A]; - const FieldOptions_CType.__F(int v, String n) : super(v, n); -} -class FieldOptions extends GeneratedMessage { - static final BuilderInfo _i_N = new BuilderInfo('FieldOptions') - ..e(1, 'ctype', PbFieldType.OE, FieldOptions_CType.STRING, FieldOptions_CType.valueOf_C) - ..a(2, 'packed', PbFieldType.OB) - ..a(5, 'lazy', PbFieldType.OB) - ..a(3, 'deprecated', PbFieldType.OB) - ..a(9, 'experimentalMapKey', PbFieldType.OS) - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - FieldOptions() : super(); - FieldOptions clone() => new FieldOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_N; - static FieldOptions create_K() => new FieldOptions(); - static FieldOptions getDefault_C() { - if (_defaultInstance_B == null) _defaultInstance_B = new _ReadonlyFieldOptions(); - return _defaultInstance_B; - } - static FieldOptions _defaultInstance_B; - bool get packed => getField(2); -} -class _ReadonlyFieldOptions extends FieldOptions with ReadonlyMessageMixin {} -class EnumOptions extends GeneratedMessage { - static final BuilderInfo _i_O = new BuilderInfo('EnumOptions') - ..a(2, 'allowAlias', PbFieldType.OB, true) - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - EnumOptions() : super(); - EnumOptions clone() => new EnumOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_O; - static EnumOptions create_M() => new EnumOptions(); - static EnumOptions getDefault_D() { - if (_defaultInstance_C == null) _defaultInstance_C = new _ReadonlyEnumOptions(); - return _defaultInstance_C; - } - static EnumOptions _defaultInstance_C; -} -class _ReadonlyEnumOptions extends EnumOptions with ReadonlyMessageMixin {} -class EnumValueOptions extends GeneratedMessage { - static final BuilderInfo _i_P = new BuilderInfo('EnumValueOptions') - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - EnumValueOptions() : super(); - EnumValueOptions clone() => new EnumValueOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_P; - static EnumValueOptions create_N() => new EnumValueOptions(); - static EnumValueOptions getDefault_E() { - if (_defaultInstance_D == null) _defaultInstance_D = new _ReadonlyEnumValueOptions(); - return _defaultInstance_D; - } - static EnumValueOptions _defaultInstance_D; -} -class _ReadonlyEnumValueOptions extends EnumValueOptions with ReadonlyMessageMixin {} -class ServiceOptions extends GeneratedMessage { - static final BuilderInfo _i_Q = new BuilderInfo('ServiceOptions') - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - ServiceOptions() : super(); - ServiceOptions clone() => new ServiceOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_Q; - static ServiceOptions create_Q() => new ServiceOptions(); - static ServiceOptions getDefault_F() { - if (_defaultInstance_E == null) _defaultInstance_E = new _ReadonlyServiceOptions(); - return _defaultInstance_E; - } - static ServiceOptions _defaultInstance_E; -} -class _ReadonlyServiceOptions extends ServiceOptions with ReadonlyMessageMixin {} -class MethodOptions extends GeneratedMessage { - static final BuilderInfo _i_R = new BuilderInfo('MethodOptions') - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - MethodOptions() : super(); - MethodOptions clone() => new MethodOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_R; - static MethodOptions create_R() => new MethodOptions(); - static MethodOptions getDefault_G() { - if (_defaultInstance_F == null) _defaultInstance_F = new _ReadonlyMethodOptions(); - return _defaultInstance_F; - } - static MethodOptions _defaultInstance_F; -} -class _ReadonlyMethodOptions extends MethodOptions with ReadonlyMessageMixin {} -class StreamOptions extends GeneratedMessage { - static final BuilderInfo _i_S = new BuilderInfo('StreamOptions') - ..pp(999, 'uninterpretedOption', PbFieldType.PM, UninterpretedOption.$checkItem_J, UninterpretedOption.create_T) - ..hasExtensions = true; - StreamOptions() : super(); - StreamOptions clone() => new StreamOptions() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_S; - static StreamOptions create_S() => new StreamOptions(); - static StreamOptions getDefault_H() { - if (_defaultInstance_G == null) _defaultInstance_G = new _ReadonlyStreamOptions(); - return _defaultInstance_G; - } - static StreamOptions _defaultInstance_G; -} -class _ReadonlyStreamOptions extends StreamOptions with ReadonlyMessageMixin {} -class UninterpretedOption_NamePart extends GeneratedMessage { - static final BuilderInfo _i_T = new BuilderInfo('UninterpretedOption_NamePart') - ..a(1, 'namePart', PbFieldType.QS) - ..a(2, 'isExtension', PbFieldType.QB); - UninterpretedOption_NamePart() : super(); - UninterpretedOption_NamePart clone() => new UninterpretedOption_NamePart() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_T; - static UninterpretedOption_NamePart create_U() => new UninterpretedOption_NamePart(); - static void $checkItem_K(UninterpretedOption_NamePart v) { - if (v is! UninterpretedOption_NamePart) checkItemFailed(v, 'UninterpretedOption_NamePart'); - } -} -class UninterpretedOption extends GeneratedMessage { - static final BuilderInfo _i_U = new BuilderInfo('UninterpretedOption') - ..pp(2, 'name', PbFieldType.PM, UninterpretedOption_NamePart.$checkItem_K, UninterpretedOption_NamePart.create_U) - ..a(3, 'identifierValue', PbFieldType.OS) - ..a(4, 'positiveIntValue', PbFieldType.OU6, Int64.ZERO_A) - ..a(5, 'negativeIntValue', PbFieldType.O6, Int64.ZERO_A) - ..a(6, 'doubleValue', PbFieldType.OD) - ..a(7, 'stringValue', PbFieldType.OY) - ..a(8, 'aggregateValue', PbFieldType.OS); - UninterpretedOption() : super(); - UninterpretedOption clone() => new UninterpretedOption() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_U; - static UninterpretedOption create_T() => new UninterpretedOption(); - static void $checkItem_J(UninterpretedOption v) { - if (v is! UninterpretedOption) checkItemFailed(v, 'UninterpretedOption'); - } - List get name => getField(2); -} -class SourceCodeInfo_Location extends GeneratedMessage { - static final BuilderInfo _i_V = new BuilderInfo('SourceCodeInfo_Location') - ..p(1, 'path', PbFieldType.K3) - ..p(2, 'span', PbFieldType.K3) - ..hasRequiredFields = false; - SourceCodeInfo_Location() : super(); - SourceCodeInfo_Location clone() => new SourceCodeInfo_Location() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_V; - static SourceCodeInfo_Location create_V() => new SourceCodeInfo_Location(); - static void $checkItem_L(SourceCodeInfo_Location v) { - if (v is! SourceCodeInfo_Location) checkItemFailed(v, 'SourceCodeInfo_Location'); - } - List get path => getField(1); -} -class SourceCodeInfo extends GeneratedMessage { - static final BuilderInfo _i_W = new BuilderInfo('SourceCodeInfo') - ..pp(1, 'location', PbFieldType.PM, SourceCodeInfo_Location.$checkItem_L, SourceCodeInfo_Location.create_V) - ..hasRequiredFields = false; - SourceCodeInfo() : super(); - SourceCodeInfo clone() => new SourceCodeInfo() - ..mergeFromMessage(this); - BuilderInfo get info_ => _i_W; - static SourceCodeInfo create_H() => new SourceCodeInfo(); - static SourceCodeInfo getDefault_A() { - if (_defaultInstance_H == null) _defaultInstance_H = new _ReadonlySourceCodeInfo(); - return _defaultInstance_H; - } - static SourceCodeInfo _defaultInstance_H; -} -class _ReadonlySourceCodeInfo extends SourceCodeInfo with ReadonlyMessageMixin {} -const _UTF8 = const Utf8Codec(allowMalformed: true); -class BuilderInfo { - final String messageName; - final Map fieldInfo = new Map(); - final Map byTagAsString = {}; - final Map byName = {}; - bool hasExtensions = false; - bool hasRequiredFields = true; - List _sortedByTag; - BuilderInfo(this.messageName); - void add(int tagNumber_A, String name_A, int fieldType_A, dynamic defaultOrMaker, CreateBuilderFunc subBuilder_A, ValueOfFunc valueOf_D) { - var index_A = fieldInfo.length; - addField(new FieldInfo(name_A, tagNumber_A, index_A, fieldType_A, defaultOrMaker, subBuilder_A, valueOf_D)); - } - void addRepeated(int tagNumber_A, String name_A, int fieldType_A, CheckFunc check_A, CreateBuilderFunc subBuilder_A, ValueOfFunc valueOf_D) { - var index_A = fieldInfo.length; - addField(new FieldInfo.repeated(name_A, tagNumber_A, index_A, fieldType_A, check_A, subBuilder_A, valueOf_D)); - } - void addField(FieldInfo fi) { - fieldInfo[fi.tagNumber] = fi; - byTagAsString["${fi.tagNumber}"] = fi; - byName[fi.name] = fi; - } - void a(int tagNumber_A, String name_A, int fieldType_A, [dynamic defaultOrMaker, CreateBuilderFunc subBuilder_A, ValueOfFunc valueOf_D]) { - add(tagNumber_A, name_A, fieldType_A, defaultOrMaker, subBuilder_A, valueOf_D); - } - void e(int tagNumber_A, String name_A, int fieldType_A, dynamic defaultOrMaker, ValueOfFunc valueOf_D) { - add(tagNumber_A, name_A, fieldType_A, defaultOrMaker, null, valueOf_D); - } - void p(int tagNumber_A, String name_A, int fieldType_A) { - assert(!_isGroupOrMessage(fieldType_A) && !_isEnum(fieldType_A)); - addRepeated(tagNumber_A, name_A, fieldType_A, getCheckFunction(fieldType_A), null, null); - } - void pp(int tagNumber_A, String name_A, int fieldType_A, CheckFunc check_A, [CreateBuilderFunc subBuilder_A, ValueOfFunc valueOf_D]) { - assert(_isGroupOrMessage(fieldType_A) || _isEnum(fieldType_A)); - addRepeated(tagNumber_A, name_A, fieldType_A, check_A, subBuilder_A, valueOf_D); - } - defaultValue(int tagNumber_A) { - MakeDefaultFunc func = makeDefault(tagNumber_A); - return func == null ? null : func(); - } - MakeDefaultFunc makeDefault(int tagNumber_A) { - FieldInfo i = fieldInfo[tagNumber_A]; - return i != null ? i.makeDefault : null; - } - CreateBuilderFunc subBuilder(int tagNumber_A) { - FieldInfo i = fieldInfo[tagNumber_A]; - return i != null ? i.subBuilder : null; - } - int tagNumber(String fieldName_A) { - FieldInfo i = byName[fieldName_A]; - return i != null ? i.tagNumber : null; - } - ValueOfFunc valueOfFunc(int tagNumber_A) { - FieldInfo i = fieldInfo[tagNumber_A]; - return i != null ? i.valueOf_D : null; - } - List get sortedByTag { - if (_sortedByTag != null) return _sortedByTag; - _sortedByTag = new List.from(fieldInfo.values) - ..sort((a_A, b) => a_A.tagNumber.compareTo(b.tagNumber)); - return _sortedByTag; - } - GeneratedMessage _makeEmptyMessage(int tagNumber_A, ExtensionRegistry extensionRegistry) { - CreateBuilderFunc subBuilderFunc = subBuilder(tagNumber_A); - if (subBuilderFunc == null && extensionRegistry != null) { - subBuilderFunc = extensionRegistry.getExtension(messageName, tagNumber_A).subBuilder; - } - return subBuilderFunc(); - } - _decodeEnum(int tagNumber_A, ExtensionRegistry registry, int rawValue) { - ValueOfFunc f = valueOfFunc(tagNumber_A); - if (f == null && registry != null) { - f = registry.getExtension(messageName, tagNumber_A).valueOf_D; - } - return f(rawValue); - } -} -void _writeToCodedBufferWriter(_FieldSet fs, CodedBufferWriter out) { - for (var fi in fs._infosSortedByTag) { - var value_A = fs._values_A[fi.index]; - if (value_A == null) continue; - out.writeField(fi.tagNumber, fi.type, value_A); - } - if (fs._hasExtensions) { - for (var tagNumber in sorted(fs._extensions._tagNumbers)) { - var fi = fs._extensions._getInfoOrNull(tagNumber); - out.writeField(tagNumber, fi.type, fs._extensions._getFieldOrNull(fi)); - } - } - if (fs.hasUnknownFields) { - fs._unknownFields.writeToCodedBufferWriter(out); - } -} -void _mergeFromCodedBufferReader(_FieldSet fs, CodedBufferReader input_A, ExtensionRegistry registry) { - assert(registry != null); - void readPackableToList(int wireType, FieldInfo fi, Function readToList) { - List list_A = fs._ensureRepeatedField(fi); - if (wireType == WIRETYPE_LENGTH_DELIMITED) { - input_A._withLimit(input_A.readInt32(), () { - while (!input_A.isAtEnd()) { - readToList(list_A); - } - }); - } else { - readToList(list_A); - } - } - void readPackable(int wireType, FieldInfo fi, Function readFunc) { - void readToList(List list_A) => list_A.add(readFunc()); - readPackableToList(wireType, fi, readToList); - } - while (true) { - int tag = input_A.readTag(); - if (tag == 0) return; - int wireType = tag & 0x7; - int tagNumber = tag >> 3; - FieldInfo fi = fs._nonExtensionInfo(tagNumber); - if (fi == null) { - fi = registry.getExtension(fs._messageName, tagNumber); - } - if (fi == null || !_wireTypeMatches(fi.type, wireType)) { - if (!fs._ensureUnknownFields().mergeFieldFromBuffer(tag, input_A)) { - return; - } - continue; - } - int fieldType = fi.type; - fieldType &= ~(PbFieldType._PACKED_BIT | PbFieldType._REQUIRED_BIT); - switch (fieldType) { - case PbFieldType._OPTIONAL_BOOL: - fs._setFieldUnchecked(fi, input_A.readBool()); - break; - - case PbFieldType._OPTIONAL_BYTES: - fs._setFieldUnchecked(fi, input_A.readBytes()); - break; - - case PbFieldType._OPTIONAL_STRING: - fs._setFieldUnchecked(fi, input_A.readString()); - break; - - case PbFieldType._OPTIONAL_FLOAT: - fs._setFieldUnchecked(fi, input_A.readFloat()); - break; - - case PbFieldType._OPTIONAL_DOUBLE: - fs._setFieldUnchecked(fi, input_A.readDouble()); - break; - - case PbFieldType._OPTIONAL_ENUM: - int rawValue = input_A.readEnum(); - var value_A = fs._meta._decodeEnum(tagNumber, registry, rawValue); - if (value_A == null) { - var unknown = fs._ensureUnknownFields(); - unknown.mergeVarintField(tagNumber, new Int64(rawValue)); - } else { - fs._setFieldUnchecked(fi, value_A); - } - break; - - case PbFieldType._OPTIONAL_GROUP: - GeneratedMessage subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); - var oldValue = fs._getFieldOrNull(fi); - if (oldValue != null) { - subMessage.mergeFromMessage(oldValue); - } - input_A.readGroup(tagNumber, subMessage, registry); - fs._setFieldUnchecked(fi, subMessage); - break; - - case PbFieldType._OPTIONAL_INT32: - fs._setFieldUnchecked(fi, input_A.readInt32()); - break; - - case PbFieldType._OPTIONAL_INT64: - fs._setFieldUnchecked(fi, input_A.readInt64()); - break; - - case PbFieldType._OPTIONAL_SINT32: - fs._setFieldUnchecked(fi, input_A.readSint32()); - break; - - case PbFieldType._OPTIONAL_SINT64: - fs._setFieldUnchecked(fi, input_A.readSint64()); - break; - - case PbFieldType._OPTIONAL_UINT32: - fs._setFieldUnchecked(fi, input_A.readUint32()); - break; - - case PbFieldType._OPTIONAL_UINT64: - fs._setFieldUnchecked(fi, input_A.readUint64()); - break; - - case PbFieldType._OPTIONAL_FIXED32: - fs._setFieldUnchecked(fi, input_A.readFixed32()); - break; - - case PbFieldType._OPTIONAL_FIXED64: - fs._setFieldUnchecked(fi, input_A.readFixed64()); - break; - - case PbFieldType._OPTIONAL_SFIXED32: - fs._setFieldUnchecked(fi, input_A.readSfixed32()); - break; - - case PbFieldType._OPTIONAL_SFIXED64: - fs._setFieldUnchecked(fi, input_A.readSfixed64()); - break; - - case PbFieldType._OPTIONAL_MESSAGE: - GeneratedMessage subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); - var oldValue = fs._getFieldOrNull(fi); - if (oldValue != null) { - subMessage.mergeFromMessage(oldValue); - } - input_A.readMessage(subMessage, registry); - fs._setFieldUnchecked(fi, subMessage); - break; - - case PbFieldType._REPEATED_BOOL: - readPackable(wireType, fi, input_A.readBool); - break; - - case PbFieldType._REPEATED_BYTES: - fs._ensureRepeatedField(fi).add(input_A.readBytes()); - break; - - case PbFieldType._REPEATED_STRING: - fs._ensureRepeatedField(fi).add(input_A.readString()); - break; - - case PbFieldType._REPEATED_FLOAT: - readPackable(wireType, fi, input_A.readFloat); - break; - - case PbFieldType._REPEATED_DOUBLE: - readPackable(wireType, fi, input_A.readDouble); - break; - - case PbFieldType._REPEATED_ENUM: - readPackableToList(wireType, fi, (List list_A) { - int rawValue = input_A.readEnum(); - var value_A = fs._meta._decodeEnum(tagNumber, registry, rawValue); - if (value_A == null) { - var unknown = fs._ensureUnknownFields(); - unknown.mergeVarintField(tagNumber, new Int64(rawValue)); - } else { - list_A.add(value_A); - } - }); - break; - - case PbFieldType._REPEATED_GROUP: - GeneratedMessage subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); - input_A.readGroup(tagNumber, subMessage, registry); - fs._ensureRepeatedField(fi).add(subMessage); - break; - - case PbFieldType._REPEATED_INT32: - readPackable(wireType, fi, input_A.readInt32); - break; - - case PbFieldType._REPEATED_INT64: - readPackable(wireType, fi, input_A.readInt64); - break; - - case PbFieldType._REPEATED_SINT32: - readPackable(wireType, fi, input_A.readSint32); - break; - - case PbFieldType._REPEATED_SINT64: - readPackable(wireType, fi, input_A.readSint64); - break; - - case PbFieldType._REPEATED_UINT32: - readPackable(wireType, fi, input_A.readUint32); - break; - - case PbFieldType._REPEATED_UINT64: - readPackable(wireType, fi, input_A.readUint64); - break; - - case PbFieldType._REPEATED_FIXED32: - readPackable(wireType, fi, input_A.readFixed32); - break; - - case PbFieldType._REPEATED_FIXED64: - readPackable(wireType, fi, input_A.readFixed64); - break; - - case PbFieldType._REPEATED_SFIXED32: - readPackable(wireType, fi, input_A.readSfixed32); - break; - - case PbFieldType._REPEATED_SFIXED64: - readPackable(wireType, fi, input_A.readSfixed64); - break; - - case PbFieldType._REPEATED_MESSAGE: - GeneratedMessage subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); - input_A.readMessage(subMessage, registry); - fs._ensureRepeatedField(fi).add(subMessage); - break; - - default: - throw 'Unknown field type ${fieldType}'; - } - } -} -class CodedBufferReader { - static const int DEFAULT_RECURSION_LIMIT = 64; - static const int DEFAULT_SIZE_LIMIT = 64 << 20; - final Uint8List _buffer_B; - int _bufferPos = 0; - int _currentLimit = -1; - int _lastTag = 0; - int _recursionDepth = 0; - final int _recursionLimit; - final int _sizeLimit; - CodedBufferReader(List buffer_A, {int recursionLimit: DEFAULT_RECURSION_LIMIT, int sizeLimit: DEFAULT_SIZE_LIMIT}) : _buffer_B = buffer_A is Uint8List ? buffer_A : new Uint8List(buffer_A.length) - ..setRange(0, buffer_A.length, buffer_A), _recursionLimit = recursionLimit, _sizeLimit = _A.min(sizeLimit, buffer_A.length) { - _currentLimit = _sizeLimit; - } - void checkLastTagWas(int value_A) { - if (_lastTag != value_A) { - throw new InvalidProtocolBufferException.invalidEndTag(); - } - } - bool isAtEnd() => _bufferPos >= _currentLimit; - void _withLimit(int byteLimit, callback_A) { - if (byteLimit < 0) { - throw new ArgumentError('CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.'); - } - byteLimit += _bufferPos; - int oldLimit = _currentLimit; - if ((oldLimit != -1 && byteLimit > oldLimit) || byteLimit > _sizeLimit) { - throw new InvalidProtocolBufferException.truncatedMessage(); - } - _currentLimit = byteLimit; - callback_A(); - _currentLimit = oldLimit; - } - void _checkLimit(int increment) { - assert(_currentLimit != -1); - _bufferPos += increment; - if (_bufferPos > _currentLimit) { - throw new InvalidProtocolBufferException.truncatedMessage(); - } - } - void readGroup(int fieldNumber, GeneratedMessage message_A, ExtensionRegistry extensionRegistry) { - if (_recursionDepth >= _recursionLimit) { - throw new InvalidProtocolBufferException.recursionLimitExceeded(); - } - ++_recursionDepth; - message_A.mergeFromCodedBufferReader(this, extensionRegistry); - checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); - --_recursionDepth; - } - UnknownFieldSet readUnknownFieldSetGroup(int fieldNumber) { - if (_recursionDepth >= _recursionLimit) { - throw new InvalidProtocolBufferException.recursionLimitExceeded(); - } - ++_recursionDepth; - UnknownFieldSet unknownFieldSet = new UnknownFieldSet(); - unknownFieldSet.mergeFromCodedBufferReader(this); - checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); - --_recursionDepth; - return unknownFieldSet; - } - void readMessage(GeneratedMessage message_A, ExtensionRegistry extensionRegistry) { - int length_A = readInt32(); - if (_recursionDepth >= _recursionLimit) { - throw new InvalidProtocolBufferException.recursionLimitExceeded(); - } - if (length_A < 0) { - throw new ArgumentError('CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.'); - } - int oldLimit = _currentLimit; - _currentLimit = _bufferPos + length_A; - if (_currentLimit > oldLimit) { - throw new InvalidProtocolBufferException.truncatedMessage(); - } - ++_recursionDepth; - message_A.mergeFromCodedBufferReader(this, extensionRegistry); - checkLastTagWas(0); - --_recursionDepth; - _currentLimit = oldLimit; - } - int readEnum() => readInt32(); - int readInt32() => _readRawVarint32(); - Int64 readInt64() => _readRawVarint64(); - int readUint32() => _readRawVarint32(false); - Int64 readUint64() => _readRawVarint64(); - int readSint32() => _decodeZigZag32(readUint32()); - Int64 readSint64() => _decodeZigZag64(readUint64()); - int readFixed32() => _readByteData(4).getUint32(0, Endianness.LITTLE_ENDIAN); - Int64 readFixed64() => readSfixed64(); - int readSfixed32() => _readByteData(4).getInt32(0, Endianness.LITTLE_ENDIAN); - Int64 readSfixed64() { - var data_A = _readByteData(8); - var view_A = new Uint8List.view(data_A.buffer, data_A.offsetInBytes, 8); - return new Int64.fromBytes(view_A); - } - bool readBool() => _readRawVarint32() != 0; - List readBytes() { - int length_A = readInt32(); - _checkLimit(length_A); - return new Uint8List.view(_buffer_B.buffer, _buffer_B.offsetInBytes + _bufferPos - length_A, length_A); - } - String readString() => _UTF8.decode(readBytes()); - double readFloat() => _readByteData(4).getFloat32(0, Endianness.LITTLE_ENDIAN); - double readDouble() => _readByteData(8).getFloat64(0, Endianness.LITTLE_ENDIAN); - int readTag() { - if (isAtEnd()) { - _lastTag = 0; - return 0; - } - _lastTag = readInt32(); - if (getTagFieldNumber(_lastTag) == 0) { - throw new InvalidProtocolBufferException.invalidTag(); - } - return _lastTag; - } - static int _decodeZigZag32(int value_A) { - if ((value_A & 0x1) == 1) value_A = -value_A; - return value_A >> 1; - } - static Int64 _decodeZigZag64(Int64 value_A) { - if ((value_A & 0x1) == 1) value_A = -value_A; - return value_A >> 1; - } - int _readRawVarintByte() { - _checkLimit(1); - return _buffer_B[_bufferPos - 1]; - } - int _readRawVarint32([bool signed = true]) { - int bytes = _currentLimit - _bufferPos; - if (bytes > 10) bytes = 10; - int result_A = 0; - for (int i = 0; i < bytes; i++) { - int byte = _buffer_B[_bufferPos++]; - result_A |= (byte & 0x7f) << (i * 7); - if ((byte & 0x80) == 0) { - result_A &= 0xffffffff; - return signed ? result_A - 2 * (0x80000000 & result_A) : result_A; - } - } - throw new InvalidProtocolBufferException.malformedVarint(); - } - Int64 _readRawVarint64() { - int lo = 0; - int hi = 0; - for (int i = 0; i < 4; i++) { - int byte = _readRawVarintByte(); - lo |= (byte & 0x7f) << (i * 7); - if ((byte & 0x80) == 0) return new Int64.fromInts(hi, lo); - } - int byte = _readRawVarintByte(); - lo |= (byte & 0xf) << 28; - hi = (byte >> 4) & 0x7; - if ((byte & 0x80) == 0) { - return new Int64.fromInts(hi, lo); - } - for (int i = 0; i < 5; i++) { - int byte = _readRawVarintByte(); - hi |= (byte & 0x7f) << ((i * 7) + 3); - if ((byte & 0x80) == 0) return new Int64.fromInts(hi, lo); - } - throw new InvalidProtocolBufferException.malformedVarint(); - } - ByteData _readByteData(int sizeInBytes) { - _checkLimit(sizeInBytes); - return new ByteData.view(_buffer_B.buffer, _buffer_B.offsetInBytes + _bufferPos - sizeInBytes, sizeInBytes); - } -} -class CodedBufferWriter { - final List _output = []; - int _runningSizeInBytes = 0; - static final _WRITE_FUNCTION_MAP = _makeWriteFunctionMap(); - static ByteData _toVarint32(int value_A) { - Uint8List result_A = new Uint8List(5); - int i = 0; - while (value_A >= 0x80) { - result_A[i++] = 0x80 | (value_A & 0x7f); - value_A >>= 7; - } - result_A[i++] = value_A; - return new ByteData.view(result_A.buffer, 0, i); - } - static ByteData _toVarint64(Int64 value_A) { - Uint8List result_A = new Uint8List(10); - int i = 0; - ByteData bytes = new ByteData.view(new Uint8List.fromList(value_A.toBytes()).buffer, 0, 8); - int lo = bytes.getUint32(0, Endianness.LITTLE_ENDIAN); - int hi = bytes.getUint32(4, Endianness.LITTLE_ENDIAN); - while (hi > 0 || lo >= 0x80) { - result_A[i++] = 0x80 | (lo & 0x7f); - lo = (lo >> 7) | ((hi & 0x7f) << 25); - hi >>= 7; - } - result_A[i++] = lo; - return new ByteData.view(result_A.buffer, 0, i); - } - static ByteData _int32ToBytes(int value_A) => _toVarint32(value_A & 0xffffffff); - static _makeWriteFunctionMap() { - writeBytesNoTag(output, List value_A) { - output.writeInt32NoTag(value_A.length); - output.writeRawBytes(new Uint8List(value_A.length) - ..setRange(0, value_A.length, value_A)); - } - makeWriter(convertor) => ((output, value_A) { - output.writeRawBytes(convertor(value_A)); - }); - int _encodeZigZag32(int value_A) => (value_A << 1) ^ (value_A >> 31); - Int64 _encodeZigZag64(Int64 value_A) => (value_A << 1) ^ (value_A >> 63); - ByteData makeByteData32(int value_A) => new ByteData(4) - ..setUint32(0, value_A, Endianness.LITTLE_ENDIAN); - ByteData makeByteData64(Int64 value_A) { - var data_A = new Uint8List.fromList(value_A.toBytes()); - return new ByteData.view(data_A.buffer, 0, 8); - } - return new Map() - ..[PbFieldType._BOOL_BIT] = makeWriter((value_A) => _int32ToBytes(value_A ? 1 : 0)) - ..[PbFieldType._BYTES_BIT] = writeBytesNoTag - ..[PbFieldType._STRING_BIT] = (output, value_A) { - writeBytesNoTag(output, _UTF8.encode(value_A)); - } - ..[PbFieldType._DOUBLE_BIT] = makeWriter((double value_A) { - if (value_A.isNaN) return new ByteData(8) - ..setUint32(0, 0x00000000, Endianness.LITTLE_ENDIAN) - ..setUint32(4, 0x7ff80000, Endianness.LITTLE_ENDIAN); - return new ByteData(8) - ..setFloat64(0, value_A, Endianness.LITTLE_ENDIAN); - }) - ..[PbFieldType._FLOAT_BIT] = makeWriter((double value_A) { - const double MIN_FLOAT_DENORM = 1.401298464324817E-45; - const double MAX_FLOAT = 3.4028234663852886E38; - if (value_A.isNaN) return makeByteData32(0x7fc00000); - if (value_A.abs() < MIN_FLOAT_DENORM) { - return makeByteData32(value_A.isNegative ? 0x80000000 : 0x00000000); - } - if (value_A.isInfinite || value_A.abs() > MAX_FLOAT) { - return makeByteData32(value_A.isNegative ? 0xff800000 : 0x7f800000); - } - return new ByteData(4) - ..setFloat32(0, value_A, Endianness.LITTLE_ENDIAN); - }) - ..[PbFieldType._ENUM_BIT] = makeWriter((value_A) => _int32ToBytes(value_A.value)) - ..[PbFieldType._GROUP_BIT] = (output, value_A) { - value_A.writeToCodedBufferWriter(output); - } - ..[PbFieldType._INT32_BIT] = makeWriter(_int32ToBytes) - ..[PbFieldType._INT64_BIT] = makeWriter((value_A) => _toVarint64(value_A)) - ..[PbFieldType._SINT32_BIT] = makeWriter((int value_A) => _int32ToBytes(_encodeZigZag32(value_A))) - ..[PbFieldType._SINT64_BIT] = makeWriter((Int64 value_A) => _toVarint64(_encodeZigZag64(value_A))) - ..[PbFieldType._UINT32_BIT] = makeWriter(_toVarint32) - ..[PbFieldType._UINT64_BIT] = makeWriter(_toVarint64) - ..[PbFieldType._FIXED32_BIT] = makeWriter(makeByteData32) - ..[PbFieldType._FIXED64_BIT] = makeWriter(makeByteData64) - ..[PbFieldType._SFIXED32_BIT] = makeWriter(makeByteData32) - ..[PbFieldType._SFIXED64_BIT] = makeWriter(makeByteData64) - ..[PbFieldType._MESSAGE_BIT] = (output, value_A) { - output._withDeferredSizeCalculation(() { - value_A.writeToCodedBufferWriter(output); - }); - }; - } - static final _OPEN_TAG_MAP = _makeOpenTagMap(); - static _makeOpenTagMap() { - return new Map() - ..[PbFieldType._BOOL_BIT] = WIRETYPE_VARINT - ..[PbFieldType._BYTES_BIT] = WIRETYPE_LENGTH_DELIMITED - ..[PbFieldType._STRING_BIT] = WIRETYPE_LENGTH_DELIMITED - ..[PbFieldType._DOUBLE_BIT] = WIRETYPE_FIXED64 - ..[PbFieldType._FLOAT_BIT] = WIRETYPE_FIXED32 - ..[PbFieldType._ENUM_BIT] = WIRETYPE_VARINT - ..[PbFieldType._GROUP_BIT] = WIRETYPE_START_GROUP - ..[PbFieldType._INT32_BIT] = WIRETYPE_VARINT - ..[PbFieldType._INT64_BIT] = WIRETYPE_VARINT - ..[PbFieldType._SINT32_BIT] = WIRETYPE_VARINT - ..[PbFieldType._SINT64_BIT] = WIRETYPE_VARINT - ..[PbFieldType._UINT32_BIT] = WIRETYPE_VARINT - ..[PbFieldType._UINT64_BIT] = WIRETYPE_VARINT - ..[PbFieldType._FIXED32_BIT] = WIRETYPE_FIXED32 - ..[PbFieldType._FIXED64_BIT] = WIRETYPE_FIXED64 - ..[PbFieldType._SFIXED32_BIT] = WIRETYPE_FIXED32 - ..[PbFieldType._SFIXED64_BIT] = WIRETYPE_FIXED64 - ..[PbFieldType._MESSAGE_BIT] = WIRETYPE_LENGTH_DELIMITED; - } - void _withDeferredSizeCalculation(continuation) { - int index_A = _output.length; - _output.add(null); - int currentRunningSizeInBytes = _runningSizeInBytes; - continuation(); - int writtenSizeInBytes = _runningSizeInBytes - currentRunningSizeInBytes; - TypedData sizeMarker = _int32ToBytes(writtenSizeInBytes); - _output[index_A] = sizeMarker; - _runningSizeInBytes += sizeMarker.lengthInBytes; - } - void writeField(int fieldNumber, int fieldType, fieldValue) { - var valueType = fieldType & ~0x07; - var writeFunction = _WRITE_FUNCTION_MAP[valueType]; - writeTag(int wireFormat) { - writeInt32NoTag(makeTag(fieldNumber, wireFormat)); - } - if ((fieldType & PbFieldType._PACKED_BIT) != 0) { - if (!fieldValue.isEmpty) { - writeTag(WIRETYPE_LENGTH_DELIMITED); - _withDeferredSizeCalculation(() { - for (var value_A in fieldValue) { - writeFunction(this, value_A); - } - }); - } - return; - } - writeValue(value_A) { - writeTag(_OPEN_TAG_MAP[valueType]); - writeFunction(this, value_A); - if (valueType == PbFieldType._GROUP_BIT) { - writeTag(WIRETYPE_END_GROUP); - } - } - if ((fieldType & PbFieldType._REPEATED_BIT) != 0) { - fieldValue.forEach(writeValue); - return; - } - writeValue(fieldValue); - } - void writeInt32NoTag(int value_A) { - writeRawBytes(_int32ToBytes(value_A)); - } - void writeRawBytes(TypedData value_A) { - _output.add(value_A); - _runningSizeInBytes += value_A.lengthInBytes; - } - Uint8List toBuffer() { - Uint8List result_A = new Uint8List(_runningSizeInBytes); - int position_A = 0; - for (var typedData in _output) { - Uint8List asBytes = new Uint8List.view(typedData.buffer, typedData.offsetInBytes, typedData.lengthInBytes); - result_A.setRange(position_A, position_A + typedData.lengthInBytes, asBytes); - position_A += typedData.lengthInBytes; - } - return result_A; - } -} -abstract class EventPlugin {} -class InvalidProtocolBufferException implements Exception { - final String message; - InvalidProtocolBufferException.__G(this.message); - String toString() => 'InvalidProtocolBufferException: ${message}'; - InvalidProtocolBufferException.invalidEndTag() : this.__G('Protocol message end-group tag did not match expected tag.'); - InvalidProtocolBufferException.invalidTag() : this.__G('Protocol message contained an invalid tag (zero).'); - InvalidProtocolBufferException.invalidWireType() : this.__G('Protocol message tag had invalid wire type.'); - InvalidProtocolBufferException.malformedVarint() : this.__G('CodedBufferReader encountered a malformed varint.'); - InvalidProtocolBufferException.recursionLimitExceeded() : this.__G(''' -Protocol message had too many levels of nesting. May be malicious. -Use CodedBufferReader.setRecursionLimit() to increase the depth limit. -'''); - InvalidProtocolBufferException.truncatedMessage() : this.__G(''' -While parsing a protocol message, the input ended unexpectedly -in the middle of a field. This could mean either than the -input has been truncated or that an embedded message -misreported its own length. -'''); -} -class Extension extends FieldInfo { - final String extendee; - Extension(this.extendee, String name_A, int tagNumber, int fieldType, [dynamic defaultOrMaker, CreateBuilderFunc subBuilder, ValueOfFunc valueOf_D]) : super(name_A, tagNumber, null, fieldType, defaultOrMaker, subBuilder, valueOf_D); - int get hashCode => extendee.hashCode * 31 + tagNumber; - bool operator==(other) { - if (other is! Extension) return false; - Extension o = other; - return extendee == o.extendee && tagNumber == o.tagNumber; - } -} -class _ExtensionFieldSet { - final _FieldSet _parent; - final Map _info = {}; - final Map _values_A = {}; - _ExtensionFieldSet(this._parent) { - assert(!_parent._isReadOnly); - } - Extension _getInfoOrNull(int tagNumber) => _info[tagNumber]; - _getFieldOrDefault(Extension fi) { - if (fi.isRepeated) return _ensureRepeatedField(fi); - _validateInfo(fi); - _addInfoUnchecked(fi); - var value_A = _getFieldOrNull(fi); - if (value_A == null) return fi.makeDefault(); - return value_A; - } - bool _hasField(int tagNumber) { - var value_A = _values_A[tagNumber]; - if (value_A == null) return false; - if (value_A is List) return value_A.isNotEmpty; - return true; - } - List _ensureRepeatedField(Extension fi) { - assert(fi.isRepeated); - assert(fi.extendee == _parent._messageName); - var list_A = _values_A[fi.tagNumber]; - if (list_A != null) return list_A; - _validateInfo(fi); - list_A = _parent._message.createRepeatedField(fi.tagNumber, fi); - _addInfoUnchecked(fi); - _setFieldUnchecked(fi, list_A); - return list_A; - } - _getFieldOrNull(Extension extension) => _values_A[extension.tagNumber]; - void _setField(int tagNumber, value_A) { - var fi = _getInfoOrNull(tagNumber); - if (fi == null) { - throw new ArgumentError("tag ${tagNumber} not defined in ${_parent}._messageName"); - } - if (fi.isRepeated) { - throw new ArgumentError(_parent._setFieldFailedMessage(fi, value_A, 'repeating field (use get + .add())')); - } - _parent._validateField_A(fi, value_A); - _setFieldUnchecked(fi, value_A); - } - void _setFieldAndInfo(Extension fi, value_A) { - if (fi.isRepeated) { - throw new ArgumentError(_parent._setFieldFailedMessage(fi, value_A, 'repeating field (use get + .add())')); - } - _validateInfo(fi); - _parent._validateField_A(fi, value_A); - _addInfoUnchecked(fi); - _setFieldUnchecked(fi, value_A); - } - void _validateInfo(Extension fi) { - if (fi.extendee != _parent._messageName) { - throw new ArgumentError('Extension ${fi} not legal for message ${_parent._messageName}'); - } - } - void _addInfoUnchecked(Extension fi) { - assert(fi.extendee == _parent._messageName); - _info[fi.tagNumber] = fi; - } - void _setFieldUnchecked(Extension fi, value_A) { - if (_parent._hasObservers) { - _parent._eventPlugin.beforeSetField(fi, value_A); - } - _values_A[fi.tagNumber] = value_A; - } - Iterable get _tagNumbers => _values_A.keys; - Iterable get _infos => _info.values; - get _hasValues => _values_A.isNotEmpty; - bool _equalValues(_ExtensionFieldSet other) => _areMapsEqual(_values_A, other._values_A); - void _clearValues() => _values_A.clear(); -} -class ExtensionRegistry { - final Map> _extensions = >{}; - static const ExtensionRegistry EMPTY = const _EmptyExtensionRegistry(); - void add(Extension extension) { - var map_A = _extensions.putIfAbsent(extension.extendee, () => new Map()); - map_A[extension.tagNumber] = extension; - } - Extension getExtension(String messageName, int tagNumber) { - var map_A = _extensions[messageName]; - if (map_A != null) { - return map_A[tagNumber]; - } - return null; - } -} -class _EmptyExtensionRegistry implements ExtensionRegistry { - const _EmptyExtensionRegistry(); - get _extensions => null; - void add(Extension extension) { - throw new UnsupportedError('Immutable ExtensionRegistry'); - } - Extension getExtension(String messageName, int tagNumber) => null; -} -String _getFieldError(int fieldType, var value_A) { - switch (PbFieldType._baseType(fieldType)) { - case PbFieldType._BOOL_BIT: - if (value_A is! bool) return 'not type bool'; - return null; - - case PbFieldType._BYTES_BIT: - if (value_A is! List) return 'not List'; - return null; - - case PbFieldType._STRING_BIT: - if (value_A is! String) return 'not type String'; - return null; - - case PbFieldType._FLOAT_BIT: - if (value_A is! double) return 'not type double'; - if (!_isFloat32(value_A)) return 'out of range for float'; - return null; - - case PbFieldType._DOUBLE_BIT: - if (value_A is! double) return 'not type double'; - return null; - - case PbFieldType._ENUM_BIT: - if (value_A is! ProtobufEnum) return 'not type ProtobufEnum'; - return null; - - case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SFIXED32_BIT: - if (value_A is! int) return 'not type int'; - if (!_isSigned32(value_A)) return 'out of range for signed 32-bit int'; - return null; - - case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: - if (value_A is! int) return 'not type int'; - if (!_isUnsigned32(value_A)) return 'out of range for unsigned 32-bit int'; - return null; - - case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: - if (value_A is! Int64) return 'not Int64'; - return null; - - case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: - if (value_A is! GeneratedMessage) return 'not a GeneratedMessage'; - return null; - - default: - return 'field has unknown type ${fieldType}'; - } -} -void checkItemFailed(val, String className) { - throw new ArgumentError('Value (${val}) is not an instance of ${className}'); -} -CheckFunc getCheckFunction(int fieldType) { - switch (fieldType & ~0x7) { - case PbFieldType._BOOL_BIT: - return _checkBool; - - case PbFieldType._BYTES_BIT: - return _checkBytes; - - case PbFieldType._STRING_BIT: - return _checkString; - - case PbFieldType._FLOAT_BIT: - return _checkFloat; - - case PbFieldType._DOUBLE_BIT: - return _checkDouble; - - case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SFIXED32_BIT: - return _checkSigned32; - - case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: - return _checkUnsigned32; - - case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: - return _checkAnyInt64; - - case PbFieldType._ENUM_BIT: - return _checkAnyEnum; - - case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: - return _checkAnyMessage; - } - throw new ArgumentError('check function not implemented: ${fieldType}'); -} -void _checkNotNull(val) { - if (val == null) { - throw new ArgumentError("Can't add a null to a repeated field"); - } -} -void _checkBool(bool val) { - if (val is! bool) throw _createFieldTypeError(val, 'a bool'); -} -void _checkBytes(List val) { - if (val is! List) throw _createFieldTypeError(val, 'a List'); -} -void _checkString(String val) { - if (val is! String) throw _createFieldTypeError(val, 'a String'); -} -void _checkFloat(double val) { - _checkDouble(val); - if (!_isFloat32(val)) throw _createFieldRangeError(val, 'a float'); -} -void _checkDouble(double val) { - if (val is! double) throw _createFieldTypeError(val, 'a double'); -} -void _checkInt(int val) { - if (val is! int) throw _createFieldTypeError(val, 'an int'); -} -void _checkSigned32(int val) { - _checkInt(val); - if (!_isSigned32(val)) throw _createFieldRangeError(val, 'a signed int32'); -} -void _checkUnsigned32(int val) { - _checkInt(val); - if (!_isUnsigned32(val)) { - throw _createFieldRangeError(val, 'an unsigned int32'); - } -} -void _checkAnyInt64(Int64 val) { - if (val is! Int64) throw _createFieldTypeError(val, 'an Int64'); -} -_checkAnyEnum(ProtobufEnum val) { - if (val is! ProtobufEnum) throw _createFieldTypeError(val, 'a ProtobufEnum'); -} -_checkAnyMessage(GeneratedMessage val) { - if (val is! GeneratedMessage) { - throw _createFieldTypeError(val, 'a GeneratedMessage'); - } -} -ArgumentError _createFieldTypeError(val, String wantedType) => new ArgumentError('Value (${val}) is not ${wantedType}'); -RangeError _createFieldRangeError(val, String wantedType) => new RangeError('Value (${val}) is not ${wantedType}'); -bool _inRange(min_A, value_A, max_A) => (min_A <= value_A) && (value_A <= max_A); -bool _isSigned32(int value_A) => _inRange(-2147483648, value_A, 2147483647); -bool _isUnsigned32(int value_A) => _inRange(0, value_A, 4294967295); -bool _isFloat32(double value_A) => value_A.isNaN || value_A.isInfinite || _inRange(-3.4028234663852886E38, value_A, 3.4028234663852886E38); -class FieldInfo { - final String name; - final int tagNumber; - final int index; - final int type; - final MakeDefaultFunc makeDefault; - final CreateBuilderFunc subBuilder; - final ValueOfFunc valueOf_D; - final CheckFunc check; - FieldInfo(this.name, this.tagNumber, this.index, int type_A, [dynamic defaultOrMaker, this.subBuilder, this.valueOf_D]) : this.type = type_A, this.makeDefault = findMakeDefault(type_A, defaultOrMaker), this.check = null { - assert(type_A != 0); - assert(!_isGroupOrMessage(type_A) || subBuilder != null); - assert(!_isEnum(type_A) || valueOf_D != null); - } - FieldInfo.repeated(this.name, this.tagNumber, this.index, int type_A, CheckFunc check_A, this.subBuilder, [this.valueOf_D]) : this.type = type_A, this.check = check_A, this.makeDefault = (() => new PbList(check: check_A)) { - assert(name != null); - assert(tagNumber != null); - assert(_isRepeated(type_A)); - assert(check_A != null); - assert(!_isEnum(type_A) || valueOf_D != null); - } - static MakeDefaultFunc findMakeDefault(int type_A, dynamic defaultOrMaker) { - if (defaultOrMaker == null) return PbFieldType._defaultForType(type_A); - if (defaultOrMaker is MakeDefaultFunc) return defaultOrMaker; - return () => defaultOrMaker; - } - bool get isRequired => _isRequired(type); - bool get isRepeated => _isRepeated(type); - get readonlyDefault { - if (isRepeated) return _emptyList; - return makeDefault(); - } - bool _hasRequiredValues(value_A) { - if (value_A == null) return !isRequired; - if (!_isGroupOrMessage(type)) return true; - if (!isRepeated) { - GeneratedMessage message_A = value_A; - return message_A._fieldSet._hasRequiredValues(); - } - List list_A = value_A; - if (list_A.isEmpty) return true; - if (!list_A[0]._fieldSet._hasRequiredFields) return true; - return list_A.every((GeneratedMessage m) => m._fieldSet._hasRequiredValues()); - } - void _appendInvalidFields(List problems, value_A, String prefix) { - if (value_A == null) { - if (isRequired) problems.add('${prefix}${name}'); - } else if (!_isGroupOrMessage(type)) {} else if (!isRepeated) { - GeneratedMessage message_A = value_A; - message_A._fieldSet._appendInvalidFields(problems, '${prefix}${name}.'); - } else { - List list_A = value_A; - if (list_A.isEmpty) return; - if (!list_A[0]._fieldSet._hasRequiredFields) return; - int position_A = 0; - for (GeneratedMessage message_A in list_A) { - message_A._fieldSet._appendInvalidFields(problems, '${prefix}${name}[${position_A}].'); - position_A++; - } - } - } - String toString() => name; -} -final _emptyList = new List.unmodifiable([]); -class _FieldSet { - final GeneratedMessage _message; - final BuilderInfo _meta; - final EventPlugin _eventPlugin; - final List _values_A; - _ExtensionFieldSet _extensions; - UnknownFieldSet _unknownFields; - _FieldSet(this._message, BuilderInfo meta, this._eventPlugin) : this._meta = meta, _values_A = _makeValueList(meta.fieldInfo); - static _makeValueList(Map infos) { - if (infos.isEmpty) return _emptyList; - return new List(infos.length); - } - String get _messageName => _meta.messageName; - bool get _isReadOnly => _message._isReadOnly; - bool get _hasRequiredFields => _meta.hasRequiredFields; - Iterable get _infos => _meta.fieldInfo.values; - Iterable get _infosSortedByTag => _meta.sortedByTag; - bool get _hasObservers => _eventPlugin != null && _eventPlugin.hasObservers; - bool get _hasExtensions => _extensions != null; - bool get hasUnknownFields => _unknownFields != null; - _ExtensionFieldSet _ensureExtensions() { - assert(!_isReadOnly); - if (!_hasExtensions) _extensions = new _ExtensionFieldSet(this); - return _extensions; - } - UnknownFieldSet _ensureUnknownFields() { - if (_isReadOnly) return _ReadonlyUnknownFieldSet._empty_A; - if (_unknownFields == null) _unknownFields = new UnknownFieldSet(); - return _unknownFields; - } - FieldInfo _nonExtensionInfo(int tagNumber) => _meta.fieldInfo[tagNumber]; - _getField(int tagNumber) { - var fi = _nonExtensionInfo(tagNumber); - if (fi != null) { - var value_A = _values_A[fi.index]; - if (value_A != null) return value_A; - return _getDefault(fi); - } - if (_hasExtensions) { - var fi = _extensions._getInfoOrNull(tagNumber); - if (fi != null) { - return _extensions._getFieldOrDefault(fi); - } - } - throw new ArgumentError("tag ${tagNumber} not defined in ${_messageName}"); - } - _getDefault(FieldInfo fi) { - if (!fi.isRepeated) return fi.makeDefault(); - if (_isReadOnly) return _emptyList; - var value_A = _message.createRepeatedField(fi.tagNumber, fi); - _setNonExtensionFieldUnchecked(fi, value_A); - return value_A; - } - _getFieldOrNull(FieldInfo fi) { - if (fi.index != null) return _values_A[fi.index]; - if (!_hasExtensions) return null; - return _extensions._getFieldOrNull(fi); - } - bool _hasField(int tagNumber) { - var fi = _nonExtensionInfo(tagNumber); - if (fi != null) return _$has(fi.index, tagNumber); - if (!_hasExtensions) return false; - return _extensions._hasField(tagNumber); - } - void _setField(int tagNumber, value_A) { - if (value_A == null) throw new ArgumentError('value is null'); - var fi = _nonExtensionInfo(tagNumber); - if (fi == null) { - if (!_hasExtensions) { - throw new ArgumentError("tag ${tagNumber} not defined in ${_messageName}"); - } - _extensions._setField(tagNumber, value_A); - return; - } - if (fi.isRepeated) { - throw new ArgumentError(_setFieldFailedMessage(fi, value_A, 'repeating field (use get + .add())')); - } - _validateField_A(fi, value_A); - _setNonExtensionFieldUnchecked(fi, value_A); - } - void _setFieldUnchecked(FieldInfo fi, value_A) { - assert(fi != null); - assert(!fi.isRepeated); - if (fi.index == null) { - _ensureExtensions() - .._addInfoUnchecked(fi) - .._setFieldUnchecked(fi, value_A); - } else { - _setNonExtensionFieldUnchecked(fi, value_A); - } - } - List _ensureRepeatedField(FieldInfo fi) { - assert(!_isReadOnly); - assert(fi.isRepeated); - if (fi.index == null) { - return _ensureExtensions()._ensureRepeatedField(fi); - } - var value_A = _getFieldOrNull(fi); - if (value_A != null) return value_A; - value_A = _message.createRepeatedField(fi.tagNumber, fi); - _setNonExtensionFieldUnchecked(fi, value_A); - return value_A; - } - void _setNonExtensionFieldUnchecked(FieldInfo fi, value_A) { - if (_hasObservers) { - _eventPlugin.beforeSetField(fi, value_A); - } - _values_A[fi.index] = value_A; - } - bool _$has(int index_A, int tagNumber) { - assert(_nonExtensionInfo(tagNumber).index == index_A); - var value_A = _values_A[index_A]; - if (value_A == null) return false; - if (value_A is List) return value_A.isNotEmpty; - return true; - } - void _clear_A() { - if (_unknownFields != null) { - _unknownFields.clear(); - } - if (_hasObservers) { - for (var fi in _infos) { - if (_values_A[fi.index] != null) { - _eventPlugin.beforeClearField(fi); - } - } - if (_hasExtensions) { - for (int key_A in _extensions._tagNumbers) { - var fi = _extensions._getInfoOrNull(key_A); - _eventPlugin.beforeClearField(fi); - } - } - } - if (_values_A.isNotEmpty) _values_A.fillRange(0, _values_A.length, null); - if (_hasExtensions) _extensions._clearValues(); - } - bool _equals_A(_FieldSet o) { - if (_meta != o._meta) return false; - if (!_areListsEqual(_values_A, o._values_A)) return false; - if (!_hasExtensions || !_extensions._hasValues) { - if (o._hasExtensions && o._extensions._hasValues) { - return false; - } - } else { - if (!_extensions._equalValues(o._extensions)) return false; - } - if (_unknownFields == null || _unknownFields.isEmpty) { - if (o._unknownFields != null && o._unknownFields.isNotEmpty) return false; - } else { - if (_unknownFields != o._unknownFields) return false; - } - return true; - } - int get _hashCode { - int hash; - void hashEnumList(PbList enums) { - enums.forEach((ProtobufEnum enm) { - hash = (31 * hash + enm.value) & 0x3fffffff; - }); - } - void hashField(FieldInfo fi, value_A) { - if (value_A is List && value_A.isEmpty) { - return; - } - hash = ((37 * hash) + fi.tagNumber) & 0x3fffffff; - if (!_isEnum(fi.type)) { - hash = ((53 * hash) + (value_A as Object).hashCode) & 0x3fffffff; - } else if (fi.isRepeated) { - hashEnumList(value_A); - } else { - ProtobufEnum enm = value_A; - hash = ((53 * hash) + enm.value) & 0x3fffffff; - } - } - void hashEachField() { - for (var fi in _infosSortedByTag) { - var v = _values_A[fi.index]; - if (v != null) hashField(fi, v); - } - if (!_hasExtensions) return; - for (int tagNumber in sorted(_extensions._tagNumbers)) { - var fi = _extensions._getInfoOrNull(tagNumber); - hashField(fi, _extensions._getFieldOrNull(fi)); - } - } - hash = 41; - hash = ((19 * hash) + _meta.hashCode) & 0x3fffffff; - hashEachField(); - if (hasUnknownFields) { - hash = ((29 * hash) + _unknownFields.hashCode) & 0x3fffffff; - } - return hash; - } - void writeString(StringBuffer out, String indent_A) { - void renderValue(key_A, value_A) { - if (value_A is GeneratedMessage) { - out.write('${indent_A}${key_A}: {\n'); - value_A._fieldSet.writeString(out, '${indent_A} '); - out.write('${indent_A}}\n'); - } else { - out.write('${indent_A}${key_A}: ${value_A}\n'); - } - } - for (FieldInfo fi in _infosSortedByTag) { - var fieldValue = _values_A[fi.index]; - if (fieldValue == null) continue; - if (fieldValue is ByteData) { - final value_A = fieldValue.getUint64(0, Endianness.LITTLE_ENDIAN); - renderValue(fi.name, value_A); - } else if (fieldValue is List) { - for (var value_A in fieldValue) { - renderValue(fi.name, value_A); - } - } else { - renderValue(fi.name, fieldValue); - } - } - if (hasUnknownFields) { - out.write(_unknownFields.toString()); - } else { - out.write(new UnknownFieldSet().toString()); - } - } - void _mergeFromMessage(_FieldSet other) { - void mergeField(FieldInfo otherFi, fieldValue) { - int tagNumber = otherFi.tagNumber; - var fi = _nonExtensionInfo(tagNumber); - if (fi == null && otherFi is Extension) { - fi = otherFi; - } - var cloner = (x_A) => x_A; - if (_isGroupOrMessage(otherFi.type)) { - cloner = (message_A) => message_A.clone(); - } - if (fi.isRepeated) { - _ensureRepeatedField(fi).addAll(new List.from(fieldValue).map(cloner)); - return; - } - fieldValue = cloner(fieldValue); - if (fi.index == null) { - _ensureExtensions()._setFieldAndInfo(fi, fieldValue); - } else { - _validateField_A(fi, fieldValue); - _setNonExtensionFieldUnchecked(fi, fieldValue); - } - } - for (var fi in other._infos) { - var value_A = other._values_A[fi.index]; - if (value_A != null) mergeField(fi, value_A); - } - if (other._hasExtensions) { - var others = other._extensions; - for (int tagNumber in others._tagNumbers) { - var extension = others._getInfoOrNull(tagNumber); - var value_A = others._getFieldOrNull(extension); - mergeField(extension, value_A); - } - } - if (other.hasUnknownFields) { - _ensureUnknownFields().mergeFromUnknownFieldSet(other._unknownFields); - } - } - void _validateField_A(FieldInfo fi, var newValue) { - var message_A = _getFieldError(fi.type, newValue); - if (message_A != null) { - throw new ArgumentError(_setFieldFailedMessage(fi, newValue, message_A)); - } - } - String _setFieldFailedMessage(FieldInfo fi, var value_A, String detail) { - return 'Illegal to set field ${fi.name} (${fi.tagNumber}) of ${_messageName}' ' to value (${value_A}): ${detail}'; - } - bool _hasRequiredValues() { - if (!_hasRequiredFields) return true; - for (var fi in _infos) { - var value_A = _values_A[fi.index]; - if (!fi._hasRequiredValues(value_A)) return false; - } - return _hasRequiredExtensionValues(); - } - bool _hasRequiredExtensionValues() { - if (!_hasExtensions) return true; - for (var fi in _extensions._infos) { - var value_A = _extensions._getFieldOrNull(fi); - if (!fi._hasRequiredValues(value_A)) return false; - } - return true; - } - void _appendInvalidFields(List problems, String prefix) { - if (!_hasRequiredFields) return; - for (var fi in _infos) { - var value_A = _values_A[fi.index]; - fi._appendInvalidFields(problems, value_A, prefix); - } - } -} -bool _isRepeated(int fieldType) => (fieldType & PbFieldType._REPEATED_BIT) != 0; -bool _isRequired(int fieldType) => (fieldType & PbFieldType._REQUIRED_BIT) != 0; -bool _isEnum(int fieldType) => PbFieldType._baseType(fieldType) == PbFieldType._ENUM_BIT; -bool _isGroupOrMessage(int fieldType) => (fieldType & (PbFieldType._GROUP_BIT | PbFieldType._MESSAGE_BIT)) != 0; -class PbFieldType { - static int _baseType(int fieldType) => fieldType & ~(_REQUIRED_BIT | _REPEATED_BIT | _PACKED_BIT); - static MakeDefaultFunc _defaultForType(int type_A) { - switch (type_A) { - case _OPTIONAL_BOOL: case _REQUIRED_BOOL: - return _BOOL_FALSE; - - case _OPTIONAL_BYTES: case _REQUIRED_BYTES: - return _BYTES_EMPTY; - - case _OPTIONAL_STRING: case _REQUIRED_STRING: - return _STRING_EMPTY; - - case _OPTIONAL_FLOAT: case _REQUIRED_FLOAT: case _OPTIONAL_DOUBLE: case _REQUIRED_DOUBLE: - return _DOUBLE_ZERO; - - case _OPTIONAL_INT32: case _REQUIRED_INT32: case _OPTIONAL_INT64: case _REQUIRED_INT64: case _OPTIONAL_SINT32: case _REQUIRED_SINT32: case _OPTIONAL_SINT64: case _REQUIRED_SINT64: case _OPTIONAL_UINT32: case _REQUIRED_UINT32: case _OPTIONAL_UINT64: case _REQUIRED_UINT64: case _OPTIONAL_FIXED32: case _REQUIRED_FIXED32: case _OPTIONAL_FIXED64: case _REQUIRED_FIXED64: case _OPTIONAL_SFIXED32: case _REQUIRED_SFIXED32: case _OPTIONAL_SFIXED64: case _REQUIRED_SFIXED64: - return _INT_ZERO; - - default: - return null; - } - } - static String _STRING_EMPTY() => ''; - static List _BYTES_EMPTY() => new PbList(check: _checkInt); - static bool _BOOL_FALSE() => false; - static int _INT_ZERO() => 0; - static double _DOUBLE_ZERO() => 0.0; - static const int _REQUIRED_BIT = 0x1; - static const int _REPEATED_BIT = 0x2; - static const int _PACKED_BIT = 0x4; - static const int _BOOL_BIT = 0x10; - static const int _BYTES_BIT = 0x20; - static const int _STRING_BIT = 0x40; - static const int _DOUBLE_BIT = 0x80; - static const int _FLOAT_BIT = 0x100; - static const int _ENUM_BIT = 0x200; - static const int _GROUP_BIT = 0x400; - static const int _INT32_BIT = 0x800; - static const int _INT64_BIT = 0x1000; - static const int _SINT32_BIT = 0x2000; - static const int _SINT64_BIT = 0x4000; - static const int _UINT32_BIT = 0x8000; - static const int _UINT64_BIT = 0x10000; - static const int _FIXED32_BIT = 0x20000; - static const int _FIXED64_BIT = 0x40000; - static const int _SFIXED32_BIT = 0x80000; - static const int _SFIXED64_BIT = 0x100000; - static const int _MESSAGE_BIT = 0x200000; - static const int _OPTIONAL_BOOL = _BOOL_BIT; - static const int _OPTIONAL_BYTES = _BYTES_BIT; - static const int _OPTIONAL_STRING = _STRING_BIT; - static const int _OPTIONAL_FLOAT = _FLOAT_BIT; - static const int _OPTIONAL_DOUBLE = _DOUBLE_BIT; - static const int _OPTIONAL_ENUM = _ENUM_BIT; - static const int _OPTIONAL_GROUP = _GROUP_BIT; - static const int _OPTIONAL_INT32 = _INT32_BIT; - static const int _OPTIONAL_INT64 = _INT64_BIT; - static const int _OPTIONAL_SINT32 = _SINT32_BIT; - static const int _OPTIONAL_SINT64 = _SINT64_BIT; - static const int _OPTIONAL_UINT32 = _UINT32_BIT; - static const int _OPTIONAL_UINT64 = _UINT64_BIT; - static const int _OPTIONAL_FIXED32 = _FIXED32_BIT; - static const int _OPTIONAL_FIXED64 = _FIXED64_BIT; - static const int _OPTIONAL_SFIXED32 = _SFIXED32_BIT; - static const int _OPTIONAL_SFIXED64 = _SFIXED64_BIT; - static const int _OPTIONAL_MESSAGE = _MESSAGE_BIT; - static const int _REQUIRED_BOOL = _REQUIRED_BIT | _BOOL_BIT; - static const int _REQUIRED_BYTES = _REQUIRED_BIT | _BYTES_BIT; - static const int _REQUIRED_STRING = _REQUIRED_BIT | _STRING_BIT; - static const int _REQUIRED_FLOAT = _REQUIRED_BIT | _FLOAT_BIT; - static const int _REQUIRED_DOUBLE = _REQUIRED_BIT | _DOUBLE_BIT; - static const int _REQUIRED_INT32 = _REQUIRED_BIT | _INT32_BIT; - static const int _REQUIRED_INT64 = _REQUIRED_BIT | _INT64_BIT; - static const int _REQUIRED_SINT32 = _REQUIRED_BIT | _SINT32_BIT; - static const int _REQUIRED_SINT64 = _REQUIRED_BIT | _SINT64_BIT; - static const int _REQUIRED_UINT32 = _REQUIRED_BIT | _UINT32_BIT; - static const int _REQUIRED_UINT64 = _REQUIRED_BIT | _UINT64_BIT; - static const int _REQUIRED_FIXED32 = _REQUIRED_BIT | _FIXED32_BIT; - static const int _REQUIRED_FIXED64 = _REQUIRED_BIT | _FIXED64_BIT; - static const int _REQUIRED_SFIXED32 = _REQUIRED_BIT | _SFIXED32_BIT; - static const int _REQUIRED_SFIXED64 = _REQUIRED_BIT | _SFIXED64_BIT; - static const int _REPEATED_BOOL = _REPEATED_BIT | _BOOL_BIT; - static const int _REPEATED_BYTES = _REPEATED_BIT | _BYTES_BIT; - static const int _REPEATED_STRING = _REPEATED_BIT | _STRING_BIT; - static const int _REPEATED_FLOAT = _REPEATED_BIT | _FLOAT_BIT; - static const int _REPEATED_DOUBLE = _REPEATED_BIT | _DOUBLE_BIT; - static const int _REPEATED_ENUM = _REPEATED_BIT | _ENUM_BIT; - static const int _REPEATED_GROUP = _REPEATED_BIT | _GROUP_BIT; - static const int _REPEATED_INT32 = _REPEATED_BIT | _INT32_BIT; - static const int _REPEATED_INT64 = _REPEATED_BIT | _INT64_BIT; - static const int _REPEATED_SINT32 = _REPEATED_BIT | _SINT32_BIT; - static const int _REPEATED_SINT64 = _REPEATED_BIT | _SINT64_BIT; - static const int _REPEATED_UINT32 = _REPEATED_BIT | _UINT32_BIT; - static const int _REPEATED_UINT64 = _REPEATED_BIT | _UINT64_BIT; - static const int _REPEATED_FIXED32 = _REPEATED_BIT | _FIXED32_BIT; - static const int _REPEATED_FIXED64 = _REPEATED_BIT | _FIXED64_BIT; - static const int _REPEATED_SFIXED32 = _REPEATED_BIT | _SFIXED32_BIT; - static const int _REPEATED_SFIXED64 = _REPEATED_BIT | _SFIXED64_BIT; - static const int _REPEATED_MESSAGE = _REPEATED_BIT | _MESSAGE_BIT; - static const int _PACKED_INT32 = _REPEATED_BIT | _PACKED_BIT | _INT32_BIT; - static const int OB = _OPTIONAL_BOOL; - static const int OY = _OPTIONAL_BYTES; - static const int OS = _OPTIONAL_STRING; - static const int OD = _OPTIONAL_DOUBLE; - static const int OE = _OPTIONAL_ENUM; - static const int O3 = _OPTIONAL_INT32; - static const int O6 = _OPTIONAL_INT64; - static const int OU6 = _OPTIONAL_UINT64; - static const int OM = _OPTIONAL_MESSAGE; - static const int QB = _REQUIRED_BOOL; - static const int QS = _REQUIRED_STRING; - static const int PS = _REPEATED_STRING; - static const int P3 = _REPEATED_INT32; - static const int PM = _REPEATED_MESSAGE; - static const int K3 = _PACKED_INT32; -} -typedef GeneratedMessage CreateBuilderFunc(); -typedef Object MakeDefaultFunc(); -typedef ProtobufEnum ValueOfFunc(int _0); -abstract class GeneratedMessage { - _FieldSet _fieldSet; - GeneratedMessage() { - _fieldSet = new _FieldSet(this, info_, eventPlugin); - if (eventPlugin != null) eventPlugin.attach(this); - } - GeneratedMessage.fromBuffer_A(List input_A, ExtensionRegistry extensionRegistry) { - _fieldSet = new _FieldSet(this, info_, eventPlugin); - if (eventPlugin != null) eventPlugin.attach(this); - mergeFromBuffer(input_A, extensionRegistry); - } - BuilderInfo get info_; - EventPlugin get eventPlugin => null; - bool get _isReadOnly => false; - bool hasRequiredFields() => info_.hasRequiredFields; - bool isInitialized() => _fieldSet._hasRequiredValues(); - void clear() => _fieldSet._clear_A(); - bool operator==(other) { - if (other is! GeneratedMessage) return false; - return _fieldSet._equals_A(other._fieldSet); - } - int get hashCode => _fieldSet._hashCode; - String toString() { - var out = new StringBuffer(); - _fieldSet.writeString(out, ''); - return out.toString(); - } - void check() { - if (!isInitialized()) { - List invalidFields = []; - _fieldSet._appendInvalidFields(invalidFields, ""); - String missingFields = (invalidFields - ..sort()).join(', '); - throw new StateError('Message missing required fields: ${missingFields}'); - } - } - Uint8List writeToBuffer() { - CodedBufferWriter out = new CodedBufferWriter(); - writeToCodedBufferWriter(out); - return out.toBuffer(); - } - void writeToCodedBufferWriter(CodedBufferWriter output) => _writeToCodedBufferWriter(_fieldSet, output); - void mergeFromCodedBufferReader(CodedBufferReader input_A, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _mergeFromCodedBufferReader(_fieldSet, input_A, extensionRegistry); - void mergeFromBuffer(List input_A, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { - CodedBufferReader codedInput = new CodedBufferReader(input_A); - _mergeFromCodedBufferReader(_fieldSet, codedInput, extensionRegistry); - codedInput.checkLastTagWas(0); - } - Map writeToJsonMap() => _writeToJsonMap(_fieldSet); - getExtension(Extension extension) { - if (_isReadOnly) return extension.readonlyDefault; - return _fieldSet._ensureExtensions()._getFieldOrDefault(extension); - } - getField(int tagNumber) => _fieldSet._getField(tagNumber); - List createRepeatedField(int tagNumber, FieldInfo fi) { - if (fi.check != null) { - return new PbList(check: fi.check); - } else { - return fi.makeDefault(); - } - } - bool hasExtension(Extension extension) => _fieldSet._hasExtensions && _fieldSet._extensions._getFieldOrNull(extension) != null; - bool hasField(int tagNumber) => _fieldSet._hasField(tagNumber); - void mergeFromMessage(GeneratedMessage other) => _fieldSet._mergeFromMessage(other._fieldSet); - void setField(int tagNumber, value_A) => _fieldSet._setField(tagNumber, value_A); -} -Int64 _MAX_JSON_INT = new Int64.fromInts(0x200000, 0); -Int64 _MIN_JSON_INT = -_MAX_JSON_INT; -Map _writeToJsonMap(_FieldSet fs) { - convertToMap(fieldValue, fieldType) { - int baseType = PbFieldType._baseType(fieldType); - if (_isRepeated(fieldType)) { - return new List.from(fieldValue.map((e) => convertToMap(e, baseType))); - } - switch (baseType) { - case PbFieldType._BOOL_BIT: case PbFieldType._STRING_BIT: case PbFieldType._FLOAT_BIT: case PbFieldType._DOUBLE_BIT: case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: - return fieldValue; - - case PbFieldType._BYTES_BIT: - return CryptoUtils.bytesToBase64_A(fieldValue); - - case PbFieldType._ENUM_BIT: - return fieldValue.value; - - case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: - if (_MIN_JSON_INT <= fieldValue && fieldValue <= _MAX_JSON_INT) { - return fieldValue.toInt(); - } - return fieldValue.toString(); - - case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: - return fieldValue.writeToJsonMap(); - - default: - throw 'Unknown type ${fieldType}'; - } - } - var result_A = {}; - for (var fi in fs._infosSortedByTag) { - var value_A = fs._values_A[fi.index]; - if (value_A == null || (value_A is List && value_A.isEmpty)) { - continue; - } - result_A['${fi.tagNumber}'] = convertToMap(value_A, fi.type); - } - if (fs._hasExtensions) { - for (int tagNumber in sorted(fs._extensions._tagNumbers)) { - var value_A = fs._extensions._values_A[tagNumber]; - if (value_A is List && value_A.isEmpty) { - continue; - } - var fi = fs._extensions._getInfoOrNull(tagNumber); - result_A['${tagNumber}'] = convertToMap(value_A, fi.type); - } - } - return result_A; -} -typedef dynamic CheckFunc(_0); -class PbList extends Object with ListMixin implements List { - final List _wrappedList; - final CheckFunc check; - PbList({this.check: _checkNotNull}) : _wrappedList = [] { - assert(check != null); - } - bool operator==(other) => (other is PbList) && _areListsEqual(other, this); - int get hashCode { - int hash = 0; - _wrappedList.forEach((E_A value_A) { - hash = (hash + value_A.hashCode) & 0x3fffffff; - hash = (hash + hash << 10) & 0x3fffffff; - hash = (hash ^ hash >> 6) & 0x3fffffff; - }); - hash = (hash + hash << 3) & 0x3fffffff; - hash = (hash ^ hash >> 11) & 0x3fffffff; - hash = (hash + hash << 15) & 0x3fffffff; - return hash; - } - Iterator get iterator => _wrappedList.iterator; - E_A operator[](int index_A) => _wrappedList[index_A]; - void operator[]=(int index_A, E_A value_A) { - _validate_A(value_A); - _wrappedList[index_A] = value_A; - } - void set length(int newLength) { - if (newLength > length) { - throw new ArgumentError('Extending protobuf lists is not supported'); - } - _wrappedList.length = newLength; - } - void add(E_A value_A) { - _validate_A(value_A); - _wrappedList.add(value_A); - } - void addAll(Iterable collection) { - collection.forEach(_validate_A); - _wrappedList.addAll(collection); - } - void setRange(int start_A, int end_A, Iterable from_A, [int skipCount = 0]) { - from_A.skip(skipCount).take(end_A - start_A).forEach(_validate_A); - _wrappedList.setRange(start_A, end_A, from_A, skipCount); - } - void insert(int index_A, E_A element_A) { - _validate_A(element_A); - _wrappedList.insert(index_A, element_A); - } - void insertAll(int index_A, Iterable iterable) { - iterable.forEach(_validate_A); - _wrappedList.insertAll(index_A, iterable); - } - void setAll(int index_A, Iterable iterable) { - iterable.forEach(_validate_A); - _wrappedList.setAll(index_A, iterable); - } - int get length => _wrappedList.length; - void _validate_A(E_A val) { - check(val); - if (val is! E_A) { - throw new ArgumentError('Value (${val}) is not of the correct type'); - } - } -} -class ProtobufEnum { - final int value; - final String name; - const ProtobufEnum(this.value, this.name); - static Map initByValue(List byIndex) { - var byValue = new Map(); - for (ProtobufEnum v in byIndex) { - byValue[v.value] = v; - } - return byValue; - } - int get hashCode => value; - String toString() => name; -} -abstract class ReadonlyMessageMixin { - BuilderInfo get info_; - get _isReadOnly => true; - void clear() => _readonly("clear"); - createRepeatedField(int tagNumber, FieldInfo fi) => _readonly("createRepeatedField"); - void mergeFromBuffer(List input_A, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly("mergeFromBuffer"); - void mergeFromCodedBufferReader(CodedBufferReader input_A, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly("mergeFromCodedBufferReader"); - void mergeFromMessage(GeneratedMessage other) => _readonly("mergeFromMessage"); - void setField(int tagNumber, var value_A, [int fieldType = null]) => _readonly("setField"); - void _readonly(String methodName) { - String messageType_A = info_.messageName; - throw new UnsupportedError("attempted to call ${methodName} on a read-only message (${messageType_A})"); - } -} -class _ReadonlyUnknownFieldSet extends UnknownFieldSet { - static final _empty_A = new _ReadonlyUnknownFieldSet(); - void clear() => _readonly("clear"); - void mergeField(int number, UnknownFieldSetField field) => _readonly("mergeField"); - bool mergeFieldFromBuffer(int tag, CodedBufferReader input_A) { - _readonly("mergeFieldFromBuffer"); - return false; - } - void mergeFromCodedBufferReader(CodedBufferReader input_A) => _readonly("mergeFromCodedBufferReader"); - void mergeFromUnknownFieldSet(UnknownFieldSet other) => _readonly("mergeFromUnknownFieldSet"); - UnknownFieldSetField _getField(int number) { - _readonly("a merge method"); - return null; - } - void _readonly(String methodName) { - throw new UnsupportedError("attempted to call ${methodName} on a read-only UnknownFieldSet"); - } -} -class UnknownFieldSet { - final Map _fields = new Map(); - UnknownFieldSet(); - UnknownFieldSet._clone_A(UnknownFieldSet unknownFieldSet) { - mergeFromUnknownFieldSet(unknownFieldSet); - } - UnknownFieldSet clone() => new UnknownFieldSet._clone_A(this); - bool get isEmpty => _fields.isEmpty; - bool get isNotEmpty => _fields.isNotEmpty; - Map asMap() => new Map.from(_fields); - void clear() { - _fields.clear(); - } - UnknownFieldSetField getField(int tagNumber) => _fields[tagNumber]; - bool hasField(int tagNumber) => _fields.containsKey(tagNumber); - void mergeField(int number, UnknownFieldSetField field) { - _getField(number) - ..varints.addAll(field.varints) - ..fixed32s.addAll(field.fixed32s) - ..fixed64s.addAll(field.fixed64s) - ..lengthDelimited.addAll(field.lengthDelimited) - ..groups.addAll(field.groups); - } - bool mergeFieldFromBuffer(int tag, CodedBufferReader input_A) { - int number = getTagFieldNumber(tag); - switch (getTagWireType(tag)) { - case WIRETYPE_VARINT: - mergeVarintField(number, input_A.readInt64()); - return true; - - case WIRETYPE_FIXED64: - mergeFixed64Field(number, input_A.readFixed64()); - return true; - - case WIRETYPE_LENGTH_DELIMITED: - mergeLengthDelimitedField(number, input_A.readBytes()); - return true; - - case WIRETYPE_START_GROUP: - UnknownFieldSet subGroup = input_A.readUnknownFieldSetGroup(number); - mergeGroupField(number, subGroup); - return true; - - case WIRETYPE_END_GROUP: - return false; - - case WIRETYPE_FIXED32: - mergeFixed32Field(number, input_A.readFixed32()); - return true; - - default: - throw new InvalidProtocolBufferException.invalidWireType(); - } - } - void mergeFromCodedBufferReader(CodedBufferReader input_A) { - while (true) { - int tag = input_A.readTag(); - if (tag == 0 || !mergeFieldFromBuffer(tag, input_A)) { - break; - } - } - } - void mergeFromUnknownFieldSet(UnknownFieldSet other) { - for (int key_A in other._fields.keys) { - mergeField(key_A, other._fields[key_A]); - } - } - _checkFieldNumber(int number) { - if (number == 0) { - throw new ArgumentError('Zero is not a valid field number.'); - } - } - void mergeFixed32Field(int number, int value_A) { - _getField(number).addFixed32(value_A); - } - void mergeFixed64Field(int number, Int64 value_A) { - _getField(number).addFixed64(value_A); - } - void mergeGroupField(int number, UnknownFieldSet value_A) { - _getField(number).addGroup(value_A); - } - void mergeLengthDelimitedField(int number, List value_A) { - _getField(number).addLengthDelimited(value_A); - } - void mergeVarintField(int number, Int64 value_A) { - _getField(number).addVarint(value_A); - } - UnknownFieldSetField _getField(int number) { - _checkFieldNumber(number); - return _fields.putIfAbsent(number, () => new UnknownFieldSetField()); - } - bool operator==(other) { - if (other is! UnknownFieldSet) return false; - UnknownFieldSet o = other; - return _areMapsEqual(o._fields, _fields); - } - int get hashCode { - int hash = 0; - _fields.forEach((int number, Object value_A) { - hash = ((37 * hash) + number) & 0x3fffffff; - hash = ((53 * hash) + value_A.hashCode) & 0x3fffffff; - }); - return hash; - } - String toString() => _toString_A(''); - String _toString_A(String indent_A) { - var stringBuffer = new StringBuffer(); - for (int tag in sorted(_fields.keys)) { - var field = _fields[tag]; - for (var value_A in field.values) { - if (value_A is UnknownFieldSet) { - stringBuffer - ..write('${indent_A}${tag}: {\n') - ..write(value_A._toString_A('${indent_A} ')) - ..write('${indent_A}}\n'); - } else { - if (value_A is ByteData) { - value_A = value_A.getUint64(0, Endianness.LITTLE_ENDIAN); - } - stringBuffer.write('${indent_A}${tag}: ${value_A}\n'); - } - } - } - return stringBuffer.toString(); - } - void writeToCodedBufferWriter(CodedBufferWriter output) { - for (int key_A in _fields.keys) { - _fields[key_A].writeTo(key_A, output); - } - } -} -class UnknownFieldSetField { - final List> lengthDelimited = >[]; - final List varints = []; - final List fixed32s = []; - final List fixed64s = []; - final List groups = []; - bool operator==(other) { - if (other is! UnknownFieldSetField) return false; - UnknownFieldSetField o = other; - if (lengthDelimited.length != o.lengthDelimited.length) return false; - for (int i = 0; i < lengthDelimited.length; i++) { - if (!_areListsEqual(o.lengthDelimited[i], lengthDelimited[i])) { - return false; - } - } - if (!_areListsEqual(o.varints, varints)) return false; - if (!_areListsEqual(o.fixed32s, fixed32s)) return false; - if (!_areListsEqual(o.fixed64s, fixed64s)) return false; - if (!_areListsEqual(o.groups, groups)) return false; - return true; - } - int get hashCode { - int hash = 0; - lengthDelimited.forEach((List value_A) { - for (int i = 0; i < value_A.length; i++) { - hash = (hash + value_A[i]) & 0x3fffffff; - hash = (hash + hash << 10) & 0x3fffffff; - hash = (hash ^ hash >> 6) & 0x3fffffff; - } - hash = (hash + hash << 3) & 0x3fffffff; - hash = (hash ^ hash >> 11) & 0x3fffffff; - hash = (hash + hash << 15) & 0x3fffffff; - }); - varints.forEach((Object value_A) => hash = (hash + 7 * value_A.hashCode) & 0x3fffffff); - fixed32s.forEach((Object value_A) => hash = (hash + 37 * value_A.hashCode) & 0x3fffffff); - fixed64s.forEach((Object value_A) => hash = (hash + 53 * value_A.hashCode) & 0x3fffffff); - groups.forEach((Object value_A) => hash = (hash + value_A.hashCode) & 0x3fffffff); - return hash; - } - List get values => [] - ..addAll(lengthDelimited) - ..addAll(varints) - ..addAll(fixed32s) - ..addAll(fixed64s) - ..addAll(groups); - void writeTo(int fieldNumber, CodedBufferWriter output) { - write_A(type_A, value_A) { - output.writeField(fieldNumber, type_A, value_A); - } - write_A(PbFieldType._REPEATED_UINT64, varints); - write_A(PbFieldType._REPEATED_FIXED32, fixed32s); - write_A(PbFieldType._REPEATED_FIXED64, fixed64s); - write_A(PbFieldType._REPEATED_BYTES, lengthDelimited); - write_A(PbFieldType._REPEATED_GROUP, groups); - } - void addGroup(UnknownFieldSet value_A) { - groups.add(value_A); - } - void addLengthDelimited(List value_A) { - lengthDelimited.add(value_A); - } - void addFixed32(int value_A) { - fixed32s.add(value_A); - } - void addFixed64(Int64 value_A) { - fixed64s.add(value_A); - } - void addVarint(Int64 value_A) { - varints.add(value_A); - } - bool hasRequiredFields() => false; - bool isInitialized() => true; - int get length => values.length; -} -bool _deepEquals(lhs, rhs) { - if ((lhs is List) && (rhs is List)) return _areListsEqual(lhs, rhs); - if ((lhs is Map) && (rhs is Map)) return _areMapsEqual(lhs, rhs); - if ((lhs is ByteData) && (rhs is ByteData)) { - return _areByteDataEqual(lhs, rhs); - } - return lhs == rhs; -} -bool _areListsEqual(List lhs, List rhs) { - range_A(i) => new Iterable.generate(i, (i) => i); - if (lhs.length != rhs.length) return false; - return range_A(lhs.length).every((i) => _deepEquals(lhs[i], rhs[i])); -} -bool _areMapsEqual(Map lhs, Map rhs) { - if (lhs.length != rhs.length) return false; - return lhs.keys.every((key_A) => _deepEquals(lhs[key_A], rhs[key_A])); -} -bool _areByteDataEqual(ByteData lhs, ByteData rhs) { - asBytes(d) => new Uint8List.view(d.buffer, d.offsetInBytes, d.lengthInBytes); - return _areListsEqual(asBytes(lhs), asBytes(rhs)); -} -List sorted(Iterable list_A) => new List.from(list_A) - ..sort(); -const int TAG_TYPE_BITS = 3; -const int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1; -const int WIRETYPE_VARINT = 0; -const int WIRETYPE_FIXED64 = 1; -const int WIRETYPE_LENGTH_DELIMITED = 2; -const int WIRETYPE_START_GROUP = 3; -const int WIRETYPE_END_GROUP = 4; -const int WIRETYPE_FIXED32 = 5; -int getTagFieldNumber(int tag) => (tag & 0x7fffffff) >> TAG_TYPE_BITS; -int getTagWireType(int tag) => tag & TAG_TYPE_MASK; -int makeTag(int fieldNumber, int tag) => (fieldNumber << TAG_TYPE_BITS) | tag; -bool _wireTypeMatches(int fieldType, int wireType) { - switch (PbFieldType._baseType(fieldType)) { - case PbFieldType._BOOL_BIT: case PbFieldType._ENUM_BIT: case PbFieldType._INT32_BIT: case PbFieldType._INT64_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._UINT64_BIT: - return wireType == WIRETYPE_VARINT || wireType == WIRETYPE_LENGTH_DELIMITED; - - case PbFieldType._FLOAT_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: - return wireType == WIRETYPE_FIXED32 || wireType == WIRETYPE_LENGTH_DELIMITED; - - case PbFieldType._DOUBLE_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: - return wireType == WIRETYPE_FIXED64 || wireType == WIRETYPE_LENGTH_DELIMITED; - - case PbFieldType._BYTES_BIT: case PbFieldType._STRING_BIT: case PbFieldType._MESSAGE_BIT: - return wireType == WIRETYPE_LENGTH_DELIMITED; - - case PbFieldType._GROUP_BIT: - return wireType == WIRETYPE_START_GROUP; - - default: - return false; - } -} -const List GeneratedMessage_reservedNames = const['hashCode', 'noSuchMethod', 'runtimeType', 'toString', 'fromBuffer', 'fromJson', 'hasRequiredFields', 'isInitialized', 'clear', 'getTagNumber', 'check', 'writeToBuffer', 'writeToCodedBufferWriter', 'mergeFromCodedBufferReader', 'mergeFromBuffer', 'writeToJson', 'mergeFromJson', 'writeToJsonMap', 'mergeFromJsonMap', 'addExtension', 'getExtension', 'setExtension', 'hasExtension', 'clearExtension', 'getField', 'getFieldOrNull', 'getDefaultForField', 'setField', 'hasField', 'clearField', 'extensionsAreInitialized', 'mergeFromMessage', 'mergeUnknownFields', '==', 'info_', 'GeneratedMessage', 'Object', 'eventPlugin', 'createRepeatedField', 'unknownFields', r'$_get', r'$_has', r'$_setBool', r'$_setBytes', r'$_setString', r'$_setFloat', r'$_setDouble', r'$_setSignedInt32', r'$_setUnsignedInt32', r'$_setInt64']; -PbMixin findMixin(String name_A) { - for (var m in _exportedMixins) { - if (m.name == name_A) { - return m; - } - } - return null; -} -class PbMixin { - final String name; - final String importFrom; - final PbMixin parent; - final List reservedNames; - const PbMixin._raw(this.name, {this.importFrom, this.parent, this.reservedNames}); - Iterable findMixinsToApply() { - var result_A = [this]; - for (var p = parent; p != null; p = p.parent) { - result_A.add(p); - } - return result_A.reversed; - } - Iterable findReservedNames() { - var names = new Set(); - for (var m = this; m != null; m = m.parent) { - names.add(m.name); - if (m.reservedNames != null) { - names.addAll(m.reservedNames); - } - } - return names; - } -} -const _exportedMixins = const[_pbMapMixin, _pbEventMixin]; -const _pbMapMixin = const PbMixin._raw("PbMapMixin", importFrom: "package:protobuf/src/protobuf/mixins/map_mixin.dart", parent: _mapMixin); -const _pbEventMixin = const PbMixin._raw("PbEventMixin", importFrom: "package:protobuf/src/protobuf/mixins/event_mixin.dart", reservedNames: const["changes", "deliverChanges"]); -const List _reservedNamesForMap = const['[]', '[]=', 'addAll', 'containsKey', 'containsValue', 'forEach', 'putIfAbsent', 'remove', 'isEmpty', 'isNotEmpty', 'keys', 'length', 'values']; -const _mapMixin = const PbMixin._raw("MapMixin", importFrom: "dart:collection", reservedNames: _reservedNamesForMap); -class BaseType { - final FieldDescriptorProto_Type descriptor; - final String unprefixed; - final String typeConstantSuffix; - final String setter; - final ProtobufContainer generator; - const BaseType._raw_A(this.descriptor, this.typeConstantSuffix, this.unprefixed, this.setter, this.generator); - bool get isGroup => descriptor == FieldDescriptorProto_Type.TYPE_GROUP; - bool get isMessage => descriptor == FieldDescriptorProto_Type.TYPE_MESSAGE; - bool get isEnum => descriptor == FieldDescriptorProto_Type.TYPE_ENUM; - String get package => generator == null ? "" : generator.package; - String get prefixed { - if (generator == null || generator.packageImportPrefix.isEmpty) { - return unprefixed; - } - return generator.packageImportPrefix + "." + unprefixed; - } - String getDartType(String package_A) => (package_A == this.package) ? unprefixed : prefixed; - String getRepeatedDartType(String package_A) => "List<${getDartType(package_A)}>"; - factory BaseType(FieldDescriptorProto field, GenerationContext ctx) { - String constSuffix; - switch (field.type) { - case FieldDescriptorProto_Type.TYPE_BOOL: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_BOOL, "B", "bool", r"$_setBool", null); - - case FieldDescriptorProto_Type.TYPE_FLOAT: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_FLOAT, "F", "double", r"$_setFloat", null); - - case FieldDescriptorProto_Type.TYPE_DOUBLE: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_DOUBLE, "D", "double", r"$_setDouble", null); - - case FieldDescriptorProto_Type.TYPE_INT32: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_INT32, "3", "int", r"$_setUnsignedInt32", null); - - case FieldDescriptorProto_Type.TYPE_UINT32: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_UINT32, "U3", "int", r"$_setUnsignedInt32", null); - - case FieldDescriptorProto_Type.TYPE_SINT32: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_SINT32, "S3", "int", r"$_setSignedInt32", null); - - case FieldDescriptorProto_Type.TYPE_FIXED32: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_FIXED32, "F3", "int", r"$_setUnsignedInt32", null); - - case FieldDescriptorProto_Type.TYPE_SFIXED32: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_SFIXED32, "SF3", "int", r"$_setSignedInt32", null); - - case FieldDescriptorProto_Type.TYPE_INT64: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_INT64, "6", "Int64", r"$_setInt64", null); - - case FieldDescriptorProto_Type.TYPE_UINT64: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_UINT64, "U6", "Int64", r"$_setInt64", null); - - case FieldDescriptorProto_Type.TYPE_SINT64: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_SINT64, "S6", "Int64", r"$_setInt64", null); - - case FieldDescriptorProto_Type.TYPE_FIXED64: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_FIXED64, "F6", "Int64", r"$_setInt64", null); - - case FieldDescriptorProto_Type.TYPE_SFIXED64: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_SFIXED64, "SF6", "Int64", r"$_setInt64", null); - - case FieldDescriptorProto_Type.TYPE_STRING: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_STRING, "S", "String", r"$_setString", null); - - case FieldDescriptorProto_Type.TYPE_BYTES: - return const BaseType._raw_A(FieldDescriptorProto_Type.TYPE_BYTES, "Y", "List", r"$_setBytes", null); - - case FieldDescriptorProto_Type.TYPE_GROUP: - constSuffix = "G"; - break; - - case FieldDescriptorProto_Type.TYPE_MESSAGE: - constSuffix = "M"; - break; - - case FieldDescriptorProto_Type.TYPE_ENUM: - constSuffix = "E"; - break; - - default: - throw new ArgumentError("unimplemented type: ${field.type.name}"); - } - ProtobufContainer generator_A = ctx.getFieldType(field.typeName); - if (generator_A == null) { - throw 'FAILURE: Unknown type reference ${field.typeName}'; - } - return new BaseType._raw_A(field.type, constSuffix, generator_A.classname, null, generator_A); - } -} -class ClientApiGenerator { - final ServiceGenerator service; - ClientApiGenerator(this.service); - String get _clientType => 'RpcClient'; - void generate_A(IndentingWriter out) { - var className = service._descriptor.name; - out.addBlock('class ${className}Api {', '}', () { - out.println('${_clientType} _client;'); - out.println('${className}Api(this._client);'); - out.println(); - for (MethodDescriptorProto m in service._descriptor.method) { - generateMethod(out, m); - } - }); - out.println(); - } - void generateMethod(IndentingWriter out, MethodDescriptorProto m) { - var methodName = service._methodName(m.name); - var inputType = service._getDartClassName(m.inputType); - var outputType = service._getDartClassName(m.outputType); - out.addBlock('Future<${outputType}> ${methodName}(' 'ClientContext ctx, ${inputType} request) {', '}', () { - out.println('var emptyResponse = new ${outputType}();'); - out.println('return _client.invoke(ctx, \'${service._descriptor.name}\', ' '\'${m.name}\', request, emptyResponse);'); - }); - } -} -abstract class ProtobufContainer { - String get package; - String get classname; - String get fqname; - String get packageImportPrefix => package.replaceAll('.', r'$'); - FileGenerator get fileGen; -} -class CodeGenerator extends ProtobufContainer { - final Stream> _streamIn; - final IOSink _streamOut; - CodeGenerator(this._streamIn, this._streamOut); - void generate_A({Map optionParsers, OutputConfiguration config}) { - if (config == null) { - config = new DefaultOutputConfiguration(); - } - var extensions_A = new ExtensionRegistry(); - Dart_options.registerAllExtensions(extensions_A); - _streamIn.fold(new BytesBuilder(), (builder_A, data_A) => builder_A - ..add(data_A)).then((builder_A) => builder_A.takeBytes()).then((List bytes) { - var request = new CodeGeneratorRequest.fromBuffer(bytes, extensions_A); - var response_A = new CodeGeneratorResponse(); - var options = parseGenerationOptions(request, response_A, optionParsers); - if (options == null) { - _streamOut.add(response_A.writeToBuffer()); - return; - } - List generators = []; - for (FileDescriptorProto file_A in request.protoFile) { - generators.add(new FileGenerator(file_A)); - } - link(options, generators); - for (var gen in generators) { - var name_A = gen._fileDescriptor.name; - if (request.fileToGenerate.contains(name_A)) { - response_A.file.add(gen.generateResponse(config)); - } - } - _streamOut.add(response_A.writeToBuffer()); - }); - } - String get package => ''; - String get classname => null; - String get fqname => ''; - get fileGen => null; -} -class EnumAlias { - final EnumValueDescriptorProto value; - final EnumValueDescriptorProto canonicalValue; - EnumAlias(this.value, this.canonicalValue); -} -class EnumGenerator extends ProtobufContainer { - final ProtobufContainer _parent_A; - final String classname; - final String fqname; - final EnumDescriptorProto _descriptor; - final List _canonicalValues = []; - final List _aliases = []; - EnumGenerator(EnumDescriptorProto descriptor, ProtobufContainer parent_A) : _parent_A = parent_A, classname = (parent_A == null || parent_A is FileGenerator) ? descriptor.name : '${parent_A.classname}_${descriptor.name}', fqname = (parent_A == null || parent_A.fqname == null) ? descriptor.name : (parent_A.fqname == '.' ? '.${descriptor.name}' : '${parent_A.fqname}.${descriptor.name}'), _descriptor = descriptor { - for (EnumValueDescriptorProto value_A in descriptor.value) { - EnumValueDescriptorProto canonicalValue = descriptor.value.firstWhere((v) => v.number == value_A.number); - if (value_A == canonicalValue) { - _canonicalValues.add(value_A); - } else { - _aliases.add(new EnumAlias(value_A, canonicalValue)); - } - } - } - String get package => _parent_A.package; - FileGenerator get fileGen => _parent_A.fileGen; - void register_A(GenerationContext ctx) { - ctx.registerFieldType(fqname, this); - } - String getJsonConstant(FileGenerator usage) { - var name_A = "${classname}\$json"; - if (usage.package == fileGen.package || packageImportPrefix.isEmpty) { - return name_A; - } - return "${packageImportPrefix}.${name_A}"; - } - void generate_A(IndentingWriter out) { - out.addBlock('class ${classname} extends ProtobufEnum {', '}\n', () { - for (EnumValueDescriptorProto val in _canonicalValues) { - out.println('static const ${classname} ${val.name} = ' "const ${classname}._(${val.number}, '${val.name}');"); - } - if (!_aliases.isEmpty) { - out.println(); - for (EnumAlias alias in _aliases) { - out.println('static const ${classname} ${alias.value.name} =' ' ${alias.canonicalValue.name};'); - } - } - out.println(); - out.println('static const List<${classname}> values =' ' const <${classname}> ['); - for (EnumValueDescriptorProto val in _canonicalValues) { - out.println(' ${val.name},'); - } - out.println('];'); - out.println(); - out.println('static final Map _byValue =' ' ProtobufEnum.initByValue(values);'); - out.println('static ${classname} valueOf(int value) =>' ' _byValue[value];'); - out.addBlock('static void ${checkItem}(${classname} v) {', '}', () { - out.println('if (v is !${classname})' " checkItemFailed(v, '${classname}');"); - }); - out.println(); - out.println('const ${classname}._(int v, String n) ' ': super(v, n);'); - }); - } - void generateConstants(IndentingWriter out) { - var name_A = getJsonConstant(fileGen); - var json = _descriptor.writeToJsonMap(); - out.print("const ${name_A} = "); - writeJsonConst(out, json); - out.println(";"); - out.println(); - } -} -class ExtensionGenerator { - final FieldDescriptorProto _descriptor; - final ProtobufContainer _parent_A; - ProtobufField _field; - String _extendedClassName = ""; - ExtensionGenerator(this._descriptor, this._parent_A); - void resolve(GenerationContext ctx) { - _field = new ProtobufField(_descriptor, null, _parent_A, ctx); - ProtobufContainer extendedType = ctx.getFieldType(_descriptor.extendee); - if (extendedType != null) { - _extendedClassName = extendedType.classname; - } - } - String get package => _parent_A.package; - FileGenerator get fileGen => _parent_A.fileGen; - String get name { - if (_field == null) throw new StateError("resolve not called"); - String name_A = _field.dartFieldName; - return _parent_A is MessageGenerator ? '${_parent_A.classname}.${name_A}' : name_A; - } - bool get needsFixnumImport { - if (_field == null) throw new StateError("resolve not called"); - return _field.needsFixnumImport; - } - void addImportsTo(Set imports) { - if (_field == null) throw new StateError("resolve not called"); - var typeGen = _field.baseType.generator; - if (typeGen != null && typeGen.fileGen != fileGen) { - imports.add(typeGen.fileGen); - } - } - void generate_A(IndentingWriter out) { - if (_field == null) throw new StateError("resolve not called"); - String name_A = _field.dartFieldName; - if (_field.isRepeated) { - out.print('static final Extension ${name_A} = ' 'new Extension.repeated(\'${_extendedClassName}\', \'${name_A}\', ' '${_field.number}, ${_field.typeConstant}'); - var type_A = _field.baseType; - if (type_A.isMessage || type_A.isGroup) { - var dartClass = type_A.getDartType(package); - out.println(', ${dartClass}.${checkItem}, ${dartClass}.create);'); - } else if (type_A.isEnum) { - var dartClass = type_A.getDartType(package); - out.println(', ${dartClass}.${checkItem}, null, ${dartClass}.valueOf);'); - } else { - out.println(", getCheckFunction(${_field.typeConstant}));"); - } - return; - } - out.print('static final Extension ${name_A} = ' 'new Extension(\'${_extendedClassName}\', \'${name_A}\', ' '${_field.number}, ${_field.typeConstant}'); - String initializer = _field.generateDefaultFunction(package); - var type_A = _field.baseType; - if (type_A.isMessage || type_A.isGroup) { - var dartClass = type_A.getDartType(package); - out.println(', ${initializer}, ${dartClass}.create);'); - } else if (type_A.isEnum) { - var dartEnum = type_A.getDartType(package); - String valueOf_D = '(var v) => ${dartEnum}.valueOf(v)'; - out.println(", ${initializer}, null, ${valueOf_D});"); - } else if (initializer != null) { - out.println(", ${initializer});"); - } else { - out.println(");"); - } - } -} -class FileGenerator extends ProtobufContainer { - static PbMixin _getDefaultMixin(FileDescriptorProto desc) { - if (!desc.hasOptions()) return null; - if (!desc.options.hasExtension(Dart_options.defaultMixin)) { - return null; - } - var name_A = desc.options.getExtension(Dart_options.defaultMixin); - PbMixin mixin_A = findMixin(name_A); - if (mixin_A == null) { - throw ("unknown mixin class: ${name_A}"); - } - return mixin_A; - } - final FileDescriptorProto _fileDescriptor; - final List enumGenerators = []; - final List messageGenerators = []; - final List extensionGenerators = []; - final List clientApiGenerators = []; - final List serviceGenerators = []; - bool _linked = false; - FileGenerator(this._fileDescriptor) { - var defaultMixin_A = _getDefaultMixin(_fileDescriptor); - for (EnumDescriptorProto enumType in _fileDescriptor.enumType) { - enumGenerators.add(new EnumGenerator(enumType, this)); - } - for (DescriptorProto messageType_A in _fileDescriptor.messageType) { - messageGenerators.add(new MessageGenerator(messageType_A, this, defaultMixin_A)); - } - for (FieldDescriptorProto extension in _fileDescriptor.extension) { - extensionGenerators.add(new ExtensionGenerator(extension, this)); - } - for (ServiceDescriptorProto service in _fileDescriptor.service) { - var serviceGen = new ServiceGenerator(service, this); - serviceGenerators.add(serviceGen); - clientApiGenerators.add(new ClientApiGenerator(serviceGen)); - } - } - void resolve(GenerationContext ctx) { - if (_linked) throw new StateError("cross references already resolved"); - for (var m in messageGenerators) { - m.resolve(ctx); - } - for (var x_A in extensionGenerators) { - x_A.resolve(ctx); - } - _linked = true; - } - String get package => _fileDescriptor.package; - String get classname => ''; - String get fqname => '.${_fileDescriptor.package}'; - FileGenerator get fileGen => this; - String _fileNameWithoutExtension(Uri filePath) { - String fileName = filePath.pathSegments.last; - int index_A = fileName.lastIndexOf("."); - return index_A == -1 ? fileName : fileName.substring(0, index_A); - } - String _generateClassName(Uri protoFilePath) { - String s = _fileNameWithoutExtension(protoFilePath).replaceAll('-', '_'); - return '${s[0].toUpperCase()}${s.substring(1)}'; - } - String _generateLibraryName(Uri protoFilePath) { - var libraryName_A = _fileNameWithoutExtension(protoFilePath).replaceAll('-', '_'); - if (_fileDescriptor.package != '') { - return _fileDescriptor.package + "_" + libraryName_A; - } - return libraryName_A; - } - CodeGeneratorResponse_File generateResponse(OutputConfiguration config) { - IndentingWriter out = new IndentingWriter(); - generate_A(out, config); - Uri filePath = new Uri.file(_fileDescriptor.name); - return new CodeGeneratorResponse_File() - ..name = config.outputPathFor(filePath).path - ..content = out.toString(); - } - void generate_A(IndentingWriter out, [OutputConfiguration config = const DefaultOutputConfiguration()]) { - if (!_linked) throw new StateError("not linked"); - Uri filePath = new Uri.file(_fileDescriptor.name); - if (filePath.isAbsolute) { - throw ("FAILURE: File with an absolute path is not supported"); - } - generateHeader(out, filePath, config); - for (EnumGenerator e in enumGenerators) { - e.generate_A(out); - } - for (MessageGenerator m in messageGenerators) { - m.generate_A(out); - } - if (!extensionGenerators.isEmpty) { - String className = _generateClassName(filePath); - out.addBlock('class ${className} {', '}\n', () { - for (ExtensionGenerator x_A in extensionGenerators) { - x_A.generate_A(out); - } - out.println('static void registerAllExtensions(ExtensionRegistry ' 'registry) {'); - for (ExtensionGenerator x_A in extensionGenerators) { - out.println(' registry.add(${x_A.name});'); - } - out.println('}'); - }); - } - for (ClientApiGenerator c in clientApiGenerators) { - c.generate_A(out); - } - for (ServiceGenerator s in serviceGenerators) { - s.generate_A(out); - } - for (var e in enumGenerators) { - e.generateConstants(out); - } - for (MessageGenerator m in messageGenerators) { - m.generateConstants(out); - } - for (ServiceGenerator s in serviceGenerators) { - s.generateConstants(out); - } - } - void generateHeader(IndentingWriter out, Uri filePath, [OutputConfiguration config = const DefaultOutputConfiguration()]) { - String libraryName_A = _generateLibraryName(filePath); - out.println('///\n' '// Generated code. Do not modify.\n' '///\n' 'library ${libraryName_A};\n'); - if (_fileDescriptor.service.isNotEmpty) { - out.println("import 'dart:async';\n"); - } - if (_needsFixnumImport) { - out.println("import 'package:fixnum/fixnum.dart';"); - } - out.println("import 'package:protobuf/protobuf.dart';"); - var mixinImports = findMixinsToImport(); - var importNames = mixinImports.keys.toList(); - importNames.sort(); - for (var imp in importNames) { - var symbols = mixinImports[imp]; - out.println("import '${imp}' show ${symbols.join(', ')};"); - } - for (var imported in _findProtosToImport()) { - String filename = imported._fileDescriptor.name; - Uri importPath = new Uri.file(filename); - if (importPath.isAbsolute) { - throw ("FAILURE: Import with absolute path is not supported"); - } - Uri resolvedImport = config.resolveImport(importPath, filePath); - out.print("import '${resolvedImport}'"); - if (package != imported.package && imported.package.isNotEmpty) { - out.print(' as ${imported.packageImportPrefix}'); - } - out.println(';'); - } - out.println(); - } - bool get _needsFixnumImport { - for (var m in messageGenerators) { - if (m.needsFixnumImport) return true; - } - for (var x_A in extensionGenerators) { - if (x_A.needsFixnumImport) return true; - } - return false; - } - Set _findProtosToImport() { - var imports = new Set.identity(); - for (var m in messageGenerators) { - m.addImportsTo(imports); - } - for (var x_A in extensionGenerators) { - x_A.addImportsTo(imports); - } - for (var x_A in serviceGenerators) { - x_A.addImportsTo(imports); - } - imports.remove(this); - return imports; - } - Map> findMixinsToImport() { - var mixins = new Set(); - for (MessageGenerator m in messageGenerators) { - m.addMixinsTo(mixins); - } - var imports = {}; - for (var m in mixins) { - var imp = m.importFrom; - List symbols = imports[imp]; - if (symbols == null) { - symbols = []; - imports[imp] = symbols; - } - symbols.add(m.name); - } - for (var imp in imports.keys) { - imports[imp].sort(); - } - return imports; - } -} -void link(GenerationOptions options, Iterable files) { - GenerationContext ctx = new GenerationContext(options); - for (var f in files) { - ctx.registerProtoFile(f); - for (var m in f.messageGenerators) { - m.register_A(ctx); - } - for (var e in f.enumGenerators) { - e.register_A(ctx); - } - } - for (var f in files) { - f.resolve(ctx); - } - for (var f in files) { - for (var s in f.serviceGenerators) { - s.resolve(ctx); - } - } -} -class GenerationContext { - final GenerationOptions options; - final Map _files = {}; - final Map _typeRegistry = {}; - GenerationContext(this.options); - void registerProtoFile(FileGenerator f) { - _files[f._fileDescriptor.name] = f; - } - void registerFieldType(String name_A, ProtobufContainer type_A) { - _typeRegistry[name_A] = type_A; - } - ProtobufContainer getFieldType(String name_A) => _typeRegistry[name_A]; -} -const checkItem = '\$checkItem'; -class MessageGenerator extends ProtobufContainer { - static final List reservedWords = ['assert', 'break', 'case', 'catch', 'class', 'const', 'continue', 'default', 'do', 'else', 'enum', 'extends', 'false', 'final', 'finally', 'for', 'if', 'in', 'is', 'new', 'null', 'rethrow', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'var', 'void', 'while', 'with']; - static final List generatedNames = ['create', 'createRepeated', 'getDefault', checkItem]; - static PbMixin _getMixin(DescriptorProto desc, PbMixin defaultValue) { - if (!desc.hasOptions()) return defaultValue; - if (!desc.options.hasExtension(Dart_options.mixin)) return defaultValue; - String name_A = desc.options.getExtension(Dart_options.mixin); - if (name_A.isEmpty) return null; - var mixin_A = findMixin(name_A); - if (mixin_A == null) { - throw ("unknown mixin class: ${name_A}"); - } - return mixin_A; - } - final String classname; - final String fqname; - final PbMixin mixin_A; - final ProtobufContainer _parent_A; - final DescriptorProto _descriptor; - final List _enumGenerators = []; - final List _messageGenerators = []; - final List _extensionGenerators = []; - List _fieldList; - final Set _methodNames = new Set(); - MessageGenerator(DescriptorProto descriptor, ProtobufContainer parent_A, PbMixin defaultMixin_A) : _descriptor = descriptor, _parent_A = parent_A, classname = (parent_A.classname == '') ? descriptor.name : '${parent_A.classname}_${descriptor.name}', fqname = (parent_A == null || parent_A.fqname == null) ? descriptor.name : (parent_A.fqname == '.' ? '.${descriptor.name}' : '${parent_A.fqname}.${descriptor.name}'), mixin_A = _getMixin(descriptor, defaultMixin_A) { - for (EnumDescriptorProto e in _descriptor.enumType) { - _enumGenerators.add(new EnumGenerator(e, this)); - } - for (DescriptorProto n in _descriptor.nestedType) { - _messageGenerators.add(new MessageGenerator(n, this, defaultMixin_A)); - } - for (FieldDescriptorProto x_A in _descriptor.extension) { - _extensionGenerators.add(new ExtensionGenerator(x_A, this)); - } - } - String get package => _parent_A.package; - FileGenerator get fileGen => _parent_A.fileGen; - void checkResolved() { - if (_fieldList == null) { - throw new StateError("message not resolved: ${fqname}"); - } - } - String getJsonConstant(FileGenerator usage) { - var name_A = "${classname}\$json"; - if (usage.package == fileGen.package || packageImportPrefix.isEmpty) { - return name_A; - } - return "${packageImportPrefix}.${name_A}"; - } - void addMixinsTo(Set output) { - if (mixin_A != null) { - output.addAll(mixin_A.findMixinsToApply()); - } - for (var m in _messageGenerators) { - m.addMixinsTo(output); - } - } - void register_A(GenerationContext ctx) { - ctx.registerFieldType(fqname, this); - for (var m in _messageGenerators) { - m.register_A(ctx); - } - for (var e in _enumGenerators) { - e.register_A(ctx); - } - } - void resolve(GenerationContext ctx) { - if (_fieldList != null) throw new StateError("message already resolved"); - var sorted_A = new List.from(_descriptor.field) - ..sort((FieldDescriptorProto a, FieldDescriptorProto b) { - if (a.number < b.number) return -1; - if (a.number > b.number) return 1; - throw "multiple fields defined for tag ${a.number} in ${fqname}"; - }); - _fieldList = []; - for (FieldDescriptorProto field in sorted_A) { - int index_A = _fieldList.length; - _fieldList.add(new ProtobufField(field, index_A, this, ctx)); - } - for (var m in _messageGenerators) { - m.resolve(ctx); - } - for (var x_A in _extensionGenerators) { - x_A.resolve(ctx); - } - } - bool get needsFixnumImport { - if (_fieldList == null) throw new StateError("message not resolved"); - for (var field in _fieldList) { - if (field.needsFixnumImport) return true; - } - for (var m in _messageGenerators) { - if (m.needsFixnumImport) return true; - } - for (var x_A in _extensionGenerators) { - if (x_A.needsFixnumImport) return true; - } - return false; - } - void addImportsTo(Set imports) { - if (_fieldList == null) throw new StateError("message not resolved"); - for (var field in _fieldList) { - var typeGen = field.baseType.generator; - if (typeGen != null && typeGen.fileGen != fileGen) { - imports.add(typeGen.fileGen); - } - } - for (var m in _messageGenerators) { - m.addImportsTo(imports); - } - for (var x_A in _extensionGenerators) { - x_A.addImportsTo(imports); - } - } - void generate_A(IndentingWriter out) { - checkResolved(); - _methodNames.clear(); - _methodNames.addAll(reservedWords); - _methodNames.addAll(GeneratedMessage_reservedNames); - _methodNames.addAll(generatedNames); - if (mixin_A != null) { - _methodNames.addAll(mixin_A.findReservedNames()); - } - for (EnumGenerator e in _enumGenerators) { - e.generate_A(out); - } - for (MessageGenerator m in _messageGenerators) { - m.generate_A(out); - } - var mixinClause = ''; - if (mixin_A != null) { - var mixinNames = mixin_A.findMixinsToApply().map((m) => m.name); - mixinClause = ' with ${mixinNames.join(", ")}'; - } - out.addBlock('class ${classname} extends GeneratedMessage${mixinClause} {', '}', () { - out.addBlock('static final BuilderInfo _i = new BuilderInfo(\'${classname}\')', ';', () { - for (ProtobufField field in _fieldList) { - out.println(field.generateBuilderInfoCall(package)); - } - if (_descriptor.extensionRange.length > 0) { - out.println('..hasExtensions = true'); - } - if (!_hasRequiredFields_A(this, new Set())) { - out.println('..hasRequiredFields = false'); - } - }); - for (ExtensionGenerator x_A in _extensionGenerators) { - x_A.generate_A(out); - } - out.println(); - out.println('${classname}() : super();'); - out.println('${classname}.fromBuffer(List i,' ' [ExtensionRegistry r = ExtensionRegistry.EMPTY])' ' : super.fromBuffer(i, r);'); - out.println('${classname}.fromJson(String i,' ' [ExtensionRegistry r = ExtensionRegistry.EMPTY])' ' : super.fromJson(i, r);'); - out.println('${classname} clone() =>' ' new ${classname}()..mergeFromMessage(this);'); - out.println('BuilderInfo get info_ => _i;'); - out.println('static ${classname} create() =>' ' new ${classname}();'); - out.println('static PbList<${classname}> createRepeated() =>' ' new PbList<${classname}>();'); - out.addBlock('static ${classname} getDefault() {', '}', () { - out.println('if (_defaultInstance == null) _defaultInstance = new _Readonly${classname}();'); - out.println('return _defaultInstance;'); - }); - out.println('static ${classname} _defaultInstance;'); - out.addBlock('static void ${checkItem}(${classname} v) {', '}', () { - out.println('if (v is !${classname})' " checkItemFailed(v, '${classname}');"); - }); - generateFieldsAccessorsMutators(out); - }); - out.println(); - out.println('class _Readonly${classname} extends ${classname} with ReadonlyMessageMixin {}'); - out.println(); - } - bool _hasRequiredFields_A(MessageGenerator type_A, Set alreadySeen) { - if (type_A._fieldList == null) throw new StateError("message not resolved"); - if (alreadySeen.contains(type_A.fqname)) { - return false; - } - alreadySeen.add(type_A.fqname); - if (type_A._descriptor.extensionRange.length > 0) { - return true; - } - for (ProtobufField field in type_A._fieldList) { - if (field.isRequired) { - return true; - } - if (field.baseType.isMessage) { - MessageGenerator child = field.baseType.generator; - if (_hasRequiredFields_A(child, alreadySeen)) { - return true; - } - } - } - return false; - } - void generateFieldsAccessorsMutators(IndentingWriter out) { - for (ProtobufField field in _fieldList) { - out.println(); - String identifier = field.dartFieldName; - String hasIdentifier = field.hasMethodName; - String clearIdentifier = field.clearMethodName; - if (!field.isRepeated) { - while (_methodNames.contains(identifier) || _methodNames.contains(hasIdentifier) || _methodNames.contains(clearIdentifier)) { - identifier += '_' + field.number.toString(); - hasIdentifier += '_' + field.number.toString(); - clearIdentifier += '_' + field.number.toString(); - } - _methodNames.add(identifier); - _methodNames.add(hasIdentifier); - _methodNames.add(clearIdentifier); - } else { - while (_methodNames.contains(identifier)) { - identifier += '_' + field.number.toString(); - } - _methodNames.add(identifier); - } - var fieldTypeString = field.getDartType(package); - var defaultExpr = field.getDefaultExpr(); - out.println('${fieldTypeString} get ${identifier}' ' => \$_get(${field.index}, ${field.number}, ${defaultExpr});'); - if (!field.isRepeated) { - var fastSetter = field.baseType.setter; - if (fastSetter != null) { - out.println('void set ${identifier}' '(${fieldTypeString} v) { ' '${fastSetter}(${field.index}, ${field.number}, v);' ' }'); - } else { - out.println('void set ${identifier}' '(${fieldTypeString} v) { ' 'setField(${field.number}, v);' ' }'); - } - out.println('bool ${hasIdentifier}() =>' ' \$_has(${field.index}, ${field.number});'); - out.println('void ${clearIdentifier}() =>' ' clearField(${field.number});'); - } - } - } - void generateConstants(IndentingWriter out) { - const nestedTypeTag = 3; - const enumTypeTag = 4; - assert(_descriptor.info_.fieldInfo[nestedTypeTag].name == "nestedType"); - assert(_descriptor.info_.fieldInfo[enumTypeTag].name == "enumType"); - var name_A = getJsonConstant(fileGen); - var json = _descriptor.writeToJsonMap(); - var nestedTypeNames = _messageGenerators.map((m) => m.getJsonConstant(fileGen)).toList(); - var nestedEnumNames = _enumGenerators.map((e) => e.getJsonConstant(fileGen)).toList(); - out.addBlock("const ${name_A} = const {", "};", () { - for (var key_A in json.keys) { - out.print("'${key_A}': "); - if (key_A == "${nestedTypeTag}") { - out.println("const [${nestedTypeNames.join(", ")}],"); - continue; - } else if (key_A == "${enumTypeTag}") { - out.println("const [${nestedEnumNames.join(", ")}],"); - continue; - } - writeJsonConst(out, json[key_A]); - out.println(","); - } - }); - out.println(); - for (var m in _messageGenerators) { - m.generateConstants(out); - } - for (var e in _enumGenerators) { - e.generateConstants(out); - } - } -} -bool genericOptionsParser(CodeGeneratorRequest request, CodeGeneratorResponse response_A, Map parsers) { - var parameter = request.parameter != null ? request.parameter : ''; - var options = parameter.trim().split(','); - var errors_A = []; - for (var option in options) { - option = option.trim(); - if (option.isEmpty) continue; - var reportError = (details) { - errors_A.add('Error found trying to parse the option: ${option}.\n${details}'); - }; - var nameValue = option.split('='); - if (nameValue.length != 1 && nameValue.length != 2) { - reportError('Options should be a single token, or a name=value pair'); - continue; - } - var name_A = nameValue[0].trim(); - var parser = parsers[name_A]; - if (parser == null) { - reportError('Unknown option (${name_A}).'); - continue; - } - var value_A = nameValue.length > 1 ? nameValue[1].trim() : null; - parser.parse_B(name_A, value_A, reportError); - } - if (errors_A.length == 0) return true; - response_A.error = errors_A.join('\n'); - return false; -} -class GenerationOptions { - final Map fieldNameOverrides; - GenerationOptions([this.fieldNameOverrides = const{}]); -} -abstract class SingleOptionParser { - void parse_B(String name_A, String value_A, onError_A(String details)); -} -GenerationOptions parseGenerationOptions(CodeGeneratorRequest request, CodeGeneratorResponse response_A, [Map parsers]) { - var fieldNameOptionParser = new FieldNameOptionParser(); - var map_A = {}; - if (parsers != null) parsers.forEach((k, v) { - map_A[k] = v; - }); - map_A['field_name'] = fieldNameOptionParser; - if (genericOptionsParser(request, response_A, map_A)) { - return new GenerationOptions(fieldNameOptionParser.mappings); - } - return null; -} -class FieldNameOptionParser implements SingleOptionParser { - final Map mappings = {}; - void parse_B(String name_A, String value_A, onError_A(String message)) { - if (value_A == null) { - onError_A('Invalid field_name option, expected a non-emtpy value.'); - return; - } - List fromTo = value_A.split('|'); - if (fromTo.length != 2) { - onError_A('Invalid field_name option, expected a single "|" separator.'); - return; - } - var fromName = fromTo[0].trim(); - var toName = fromTo[1].trim(); - if (fromName.isEmpty || toName.isEmpty) { - onError_A('Invalid field_name option, ' '"from" and "to" names should not be empty.'); - return; - } - mappings['.${fromName}'] = toName; - } -} -abstract class OutputConfiguration { - const OutputConfiguration(); - String replacePathExtension(String filePath) => '${withoutExtension(filePath)}.pb.dart'; - Uri replaceUriExtension(Uri file_A) => url.toUri(replacePathExtension(url.fromUri_A(file_A))); - Uri resolveImport(Uri target_A, Uri source_A); - Uri outputPathFor(Uri inputPath); -} -class DefaultOutputConfiguration extends OutputConfiguration { - const DefaultOutputConfiguration(); - Uri outputPathFor(Uri input_A) => replaceUriExtension(input_A); - Uri resolveImport(Uri target_A, Uri source_A) { - var builder_A = url; - var targetPath = builder_A.fromUri_A(target_A); - var sourceDir = builder_A.dirname(builder_A.fromUri_A(source_A)); - return builder_A.toUri(replacePathExtension(builder_A.relative(targetPath, from: sourceDir))); - } -} -class ProtobufField { - static final RegExp HEX_LITERAL_REGEX = new RegExp(r'^0x[0-9a-f]+$', multiLine: false, caseSensitive: false); - static final RegExp INTEGER_LITERAL_REGEX = new RegExp(r'^[+-]?[0-9]+$'); - static final RegExp DECIMAL_LITERAL_REGEX_A = new RegExp(r'^[+-]?([0-9]*)\.[0-9]+(e[+-]?[0-9]+)?$', multiLine: false, caseSensitive: false); - static final RegExp DECIMAL_LITERAL_REGEX_B = new RegExp(r'^[+-]?[0-9]+e[+-]?[0-9]+$', multiLine: false, caseSensitive: false); - final FieldDescriptorProto _field; - final int index; - final String fqname; - final BaseType baseType; - final GenerationOptions _genOptions; - ProtobufField(FieldDescriptorProto field, this.index, ProtobufContainer parent_A, GenerationContext ctx) : _field = field, fqname = '${parent_A.fqname}.${field.name}', baseType = new BaseType(field, ctx), _genOptions = ctx.options; - int get number => _field.number; - bool get isRequired => _field.label == FieldDescriptorProto_Label.LABEL_REQUIRED; - bool get isRepeated => _field.label == FieldDescriptorProto_Label.LABEL_REPEATED; - bool get isPacked => isRepeated && _field.options != null && _field.options.packed; - bool get needsFixnumImport => baseType.unprefixed == "Int64"; - String getDartType(String package) { - if (isRepeated) return baseType.getRepeatedDartType(package); - return baseType.getDartType(package); - } - String get typeConstant { - String prefix = 'O'; - if (isRequired) { - prefix = 'Q'; - } else if (isPacked) { - prefix = 'K'; - } else if (isRepeated) { - prefix = 'P'; - } - return "PbFieldType." + prefix + baseType.typeConstantSuffix; - } - String get dartFieldName { - String name_A = _fieldMethodSuffix; - return '${name_A[0].toLowerCase()}${name_A.substring(1)}'; - } - String get hasMethodName => 'has${_fieldMethodSuffix}'; - String get clearMethodName => 'clear${_fieldMethodSuffix}'; - String get _fieldMethodSuffix { - String underscoresToCamelCase(String s) { - cap(s) => s.isEmpty ? s : '${s[0].toUpperCase()}${s.substring(1)}'; - return s.split('_').map(cap).join(''); - } - if (baseType.isGroup) { - String name_A = _field.typeName; - int index_A = name_A.lastIndexOf('.'); - if (index_A != -1) { - name_A = name_A.substring(index_A + 1); - } - return underscoresToCamelCase(name_A); - } - var name_A = _genOptions.fieldNameOverrides[fqname]; - return name_A != null ? name_A : underscoresToCamelCase(_field.name); - } - String generateBuilderInfoCall(String package) { - String quotedName = "'${dartFieldName}'"; - String type_A = baseType.getDartType(package); - if (isRepeated) { - if (baseType.isMessage || baseType.isGroup) { - return '..pp(${number}, ${quotedName}, ${typeConstant},' ' ${type_A}.${checkItem}, ${type_A}.create)'; - } else if (baseType.isEnum) { - return '..pp(${number}, ${quotedName}, ${typeConstant},' ' ${type_A}.${checkItem}, null, ${type_A}.valueOf)'; - } else { - return '..p(${number}, ${quotedName}, ${typeConstant})'; - } - } - String makeDefault = generateDefaultFunction(package); - if (baseType.isEnum) { - String valueOf_D = '${type_A}.valueOf'; - return '..e(${number}, ${quotedName}, ${typeConstant}, ${makeDefault}, ${valueOf_D})'; - } - String prefix = '..a(${number}, ${quotedName}, ${typeConstant}'; - if (makeDefault == null) return prefix + ')'; - if (baseType.isMessage || baseType.isGroup) { - return prefix + ', ${makeDefault}, ${type_A}.create)'; - } - return prefix + ', ${makeDefault})'; - } - String getDefaultExpr() { - if (isRepeated) return "null"; - switch (_field.type) { - case FieldDescriptorProto_Type.TYPE_BOOL: - return _getDefaultAsBoolExpr("false"); - - case FieldDescriptorProto_Type.TYPE_INT32: case FieldDescriptorProto_Type.TYPE_UINT32: case FieldDescriptorProto_Type.TYPE_SINT32: case FieldDescriptorProto_Type.TYPE_FIXED32: case FieldDescriptorProto_Type.TYPE_SFIXED32: - return _getDefaultAsInt32Expr("0"); - - case FieldDescriptorProto_Type.TYPE_STRING: - return _getDefaultAsStringExpr("''"); - - default: - return "null"; - } - } - String generateDefaultFunction(String package) { - if (isRepeated) { - return '() => new PbList()'; - } - bool samePackage = package == baseType.package; - switch (_field.type) { - case FieldDescriptorProto_Type.TYPE_BOOL: - return _getDefaultAsBoolExpr(null); - - case FieldDescriptorProto_Type.TYPE_FLOAT: case FieldDescriptorProto_Type.TYPE_DOUBLE: - if (!_field.hasDefaultValue()) { - return null; - } else if ('0.0' == _field.defaultValue || '0' == _field.defaultValue) { - return null; - } else if (_field.defaultValue == 'inf') { - return 'double.INFINITY'; - } else if (_field.defaultValue == '-inf') { - return 'double.NEGATIVE_INFINITY'; - } else if (_field.defaultValue == 'nan') { - return 'double.NAN'; - } else if (HEX_LITERAL_REGEX.hasMatch(_field.defaultValue)) { - return '(${_field.defaultValue}).toDouble()'; - } else if (INTEGER_LITERAL_REGEX.hasMatch(_field.defaultValue)) { - return '${_field.defaultValue}.0'; - } else if (DECIMAL_LITERAL_REGEX_A.hasMatch(_field.defaultValue) || DECIMAL_LITERAL_REGEX_B.hasMatch(_field.defaultValue)) { - return '${_field.defaultValue}'; - } - throw _invalidDefaultValue; - - case FieldDescriptorProto_Type.TYPE_INT32: case FieldDescriptorProto_Type.TYPE_UINT32: case FieldDescriptorProto_Type.TYPE_SINT32: case FieldDescriptorProto_Type.TYPE_FIXED32: case FieldDescriptorProto_Type.TYPE_SFIXED32: - return _getDefaultAsInt32Expr(null); - - case FieldDescriptorProto_Type.TYPE_INT64: case FieldDescriptorProto_Type.TYPE_UINT64: case FieldDescriptorProto_Type.TYPE_SINT64: case FieldDescriptorProto_Type.TYPE_FIXED64: case FieldDescriptorProto_Type.TYPE_SFIXED64: - var value_A = '0'; - if (_field.hasDefaultValue()) value_A = _field.defaultValue; - if (value_A == '0') return 'Int64.ZERO'; - return "parseLongInt('${value_A}')"; - - case FieldDescriptorProto_Type.TYPE_STRING: - return _getDefaultAsStringExpr(null); - - case FieldDescriptorProto_Type.TYPE_BYTES: - if (!_field.hasDefaultValue() || _field.defaultValue.isEmpty) { - return null; - } - String byteList = _field.defaultValue.codeUnits.map((b) => '0x${b.toRadixString(16)}').join(','); - return '() => [${byteList}]'; - - case FieldDescriptorProto_Type.TYPE_GROUP: case FieldDescriptorProto_Type.TYPE_MESSAGE: - if (samePackage) return '${baseType.unprefixed}.getDefault'; - return "${baseType.prefixed}.getDefault"; - - case FieldDescriptorProto_Type.TYPE_ENUM: - var className = samePackage ? baseType.unprefixed : baseType.prefixed; - EnumGenerator gen = baseType.generator; - if (_field.hasDefaultValue() && !_field.defaultValue.isEmpty) { - return '${className}.${_field.defaultValue}'; - } else if (!gen._canonicalValues.isEmpty) { - return '${className}.${gen._canonicalValues[0].name}'; - } - return null; - - default: - throw _typeNotImplemented("generatedDefaultFunction"); - } - } - String _getDefaultAsBoolExpr(String noDefault) { - if (_field.hasDefaultValue() && 'false' != _field.defaultValue) { - return '${_field.defaultValue}'; - } - return noDefault; - } - String _getDefaultAsStringExpr(String noDefault) { - if (!_field.hasDefaultValue() || _field.defaultValue.isEmpty) { - return noDefault; - } - String value_A = _field.defaultValue.replaceAll(r'$', r'\$'); - return '\'${value_A}\''; - } - String _getDefaultAsInt32Expr(String noDefault) { - if (_field.hasDefaultValue() && '0' != _field.defaultValue) { - return '${_field.defaultValue}'; - } - return noDefault; - } - get _invalidDefaultValue => "dart-protoc-plugin:" " invalid default value (${_field.defaultValue})" " found in field ${fqname}"; - _typeNotImplemented(String methodName) => "dart-protoc-plugin:" " ${methodName} not implemented for type (${_field.type})" " found in field ${fqname}"; -} -class ServiceGenerator { - final ServiceDescriptorProto _descriptor; - final FileGenerator fileGen; - final _deps = {}; - final _undefinedDeps = {}; - ServiceGenerator(this._descriptor, this.fileGen); - String get classname { - if (_descriptor.name.endsWith("Service")) { - return _descriptor.name + "Base"; - } else { - return _descriptor.name + "ServiceBase"; - } - } - void resolve(GenerationContext ctx) { - for (var m in _methodDescriptors) { - _addDependency(ctx, m.inputType, "input type of ${m.name}"); - _addDependency(ctx, m.outputType, "output type of ${m.name}"); - } - _resolveMoreTypes(ctx); - } - void _resolveMoreTypes(GenerationContext ctx) {} - void _addDependency(GenerationContext ctx, String fqname, String location_A) { - if (_deps.containsKey(fqname)) return; - MessageGenerator mg = ctx.getFieldType(fqname); - if (mg == null) { - _undefinedDeps[fqname] = location_A; - return; - } - _addDepsRecursively(mg); - } - void _addDepsRecursively(MessageGenerator mg) { - if (_deps.containsKey(mg.fqname)) return; - mg.checkResolved(); - _deps[mg.fqname] = mg; - for (var field in mg._fieldList) { - if (field.baseType.isGroup || field.baseType.isMessage) { - _addDepsRecursively(field.baseType.generator); - } - } - } - void addImportsTo(Set imports) { - for (var mg in _deps.values) { - imports.add(mg.fileGen); - } - } - String _getDartClassName(String fqname) { - var mg = _deps[fqname]; - if (mg == null) { - var location_A = _undefinedDeps[fqname]; - throw 'FAILURE: Unknown type reference (${fqname}) for ${location_A}'; - } - if (fileGen.package == mg.fileGen.package || mg.fileGen.package == "") { - return mg.classname; - } - return mg.packageImportPrefix + "." + mg.classname; - } - List get _methodDescriptors => _descriptor.method; - String _methodName(String name_A) => name_A.substring(0, 1).toLowerCase() + name_A.substring(1); - String get _parentClass => 'GeneratedService'; - void _generateStub(IndentingWriter out, MethodDescriptorProto m) { - var methodName = _methodName(m.name); - var inputClass = _getDartClassName(m.inputType); - var outputClass = _getDartClassName(m.outputType); - out.println('Future<${outputClass}> ${methodName}(' 'ServerContext ctx, ${inputClass} request);'); - } - void _generateStubs(IndentingWriter out) { - for (MethodDescriptorProto m in _methodDescriptors) { - _generateStub(out, m); - } - out.println(); - } - void _generateRequestMethod(IndentingWriter out) { - out.addBlock('GeneratedMessage createRequest(String method) {', '}', () { - out.addBlock("switch (method) {", "}", () { - for (MethodDescriptorProto m in _methodDescriptors) { - var inputClass = _getDartClassName(m.inputType); - out.println("case '${m.name}': return new ${inputClass}();"); - } - out.println("default: " "throw new ArgumentError('Unknown method: \$method');"); - }); - }); - out.println(); - } - void _generateDispatchMethod(out) { - out.addBlock('Future handleCall(ServerContext ctx, ' 'String method, GeneratedMessage request) {', '}', () { - out.addBlock("switch (method) {", "}", () { - for (MethodDescriptorProto m in _methodDescriptors) { - var methodName = _methodName(m.name); - out.println("case '${m.name}': return ${methodName}(ctx, request);"); - } - out.println("default: " "throw new ArgumentError('Unknown method: \$method');"); - }); - }); - out.println(); - } - void _generateMoreClassMembers(out) {} - void generate_A(IndentingWriter out) { - out.addBlock('abstract class ${classname} extends ' '${_parentClass} {', '}', () { - _generateStubs(out); - _generateRequestMethod(out); - _generateDispatchMethod(out); - _generateMoreClassMembers(out); - out.println("Map get \$json => ${jsonConstant};"); - out.println("Map get \$messageJson =>" " ${messageJsonConstant};"); - }); - out.println(); - } - String get jsonConstant => "${_descriptor.name}\$json"; - String get messageJsonConstant => "${_descriptor.name}\$messageJson"; - void generateConstants(IndentingWriter out) { - out.print("const ${jsonConstant} = "); - writeJsonConst(out, _descriptor.writeToJsonMap()); - out.println(";"); - out.println(); - var typeConstants = {}; - for (var key_A in _deps.keys) { - typeConstants[key_A] = _deps[key_A].getJsonConstant(fileGen); - } - out.addBlock("const ${messageJsonConstant} = const {", "};", () { - for (var key_A in typeConstants.keys) { - var typeConst = typeConstants[key_A]; - out.println("'${key_A}': ${typeConst},"); - } - }); - out.println(); - if (_undefinedDeps.isNotEmpty) { - for (var name_A in _undefinedDeps.keys) { - var location_A = _undefinedDeps[name_A]; - out.println("// can't resolve (${name_A}) used by ${location_A}"); - } - out.println(); - } - } -} -void writeJsonConst(IndentingWriter out, val) { - if (val is Map) { - if (val.values.any(_nonEmptyListOrMap)) { - out.addBlock("const {", "}", () => _writeMapItems(out, val, vertical: true), endWithNewline: false); - } else { - out.print("const {"); - _writeMapItems(out, val); - out.print("}"); - } - } else if (val is List) { - if (val.any(_nonEmptyListOrMap)) { - out.addBlock("const [", "]", () => _writeListItems(out, val, vertical: true), endWithNewline: false); - } else { - out.print("const ["); - _writeListItems(out, val); - out.print("]"); - } - } else if (val is String) { - _writeString(out, val); - } else if (val is num || val is bool) { - out.print(val.toString()); - } else if (val == null) { - out.print("null"); - } else { - throw "not JSON: ${val}"; - } -} -bool _nonEmptyListOrMap(x_A) { - if (x_A is List && !x_A.isEmpty) return true; - if (x_A is Map && !x_A.isEmpty) return true; - return false; -} -void _writeString(IndentingWriter out, String val) { - if (_maybeWriteSingleLineString(out, val)) return; - var quote = "'''"; - out.addUnindentedBlock("r${quote}", "${quote}", () { - out.print(val.replaceAll(quote, '${quote} "${quote}" r${quote}')); - }, endWithNewline: false); -} -bool _maybeWriteSingleLineString(IndentingWriter out, String val) { - if (val.contains("\n")) return false; - var prefix = ''; - if (val.contains(r'$') || val.contains(r'\')) { - prefix = 'r'; - } - if (!val.contains("'")) { - out.print("${prefix}'${val}'"); - return true; - } else if (!val.contains('"')) { - out.print('${prefix}"${val}"'); - return true; - } else if (!val.contains("'''")) { - out.print("${prefix}'''${val}'''"); - return true; - } else if (!val.contains('"""')) { - out.print('${prefix}"""${val}"""'); - return true; - } else { - return false; - } -} -void _writeListItems(IndentingWriter out, List val, {bool vertical: false}) { - bool first_A = true; - for (var item in val) { - if (!first_A && !vertical) { - out.print(", "); - } - writeJsonConst(out, item); - if (vertical) { - out.println(","); - } - first_A = false; - } -} -void _writeMapItems(IndentingWriter out, Map val, {bool vertical: false}) { - bool first_A = true; - for (String key_A in val.keys) { - if (!first_A && !vertical) out.print(", "); - _writeString(out, key_A); - out.print(": "); - writeJsonConst(out, val[key_A]); - if (vertical) { - out.println(","); - } - first_A = false; - } -} -class IndentingWriter { - final StringBuffer _buffer_C = new StringBuffer(); - String _indent_A = ""; - bool _needIndent = true; - void print(String text) { - var lastNewline = text.lastIndexOf('\n'); - if (lastNewline == -1) { - _writeChunk(text); - return; - } - for (String line in text.substring(0, lastNewline).split('\n')) { - _writeChunk(line); - _newline(); - } - _writeChunk(text.substring(lastNewline + 1)); - } - void println([String text = '']) { - print(text); - _newline(); - } - void addBlock(String start_A, String end_A, void body(), {endWithNewline: true}) { - _addBlock(start_A, end_A, body, endWithNewline, _indent_A + ' '); - } - void addUnindentedBlock(String start_A, String end_A, void body(), {endWithNewline: true}) { - _addBlock(start_A, end_A, body, endWithNewline, ''); - } - void _addBlock(String start_A, String end_A, void body(), endWithNewline, newIndent) { - println(start_A); - var oldIndent = _indent_A; - _indent_A = newIndent; - body(); - _indent_A = oldIndent; - if (endWithNewline) { - println(end_A); - } else { - print(end_A); - } - } - String toString() => _buffer_C.toString(); - void _writeChunk(String chunk) { - assert(!chunk.contains('\n')); - if (chunk.isEmpty) return; - if (_needIndent) { - _buffer_C.write(_indent_A); - _needIndent = false; - } - _buffer_C.write(chunk); - } - void _newline() { - _buffer_C.writeln(); - _needIndent = true; - } -} -void main() { - new CodeGenerator(_B.stdin, _B.stdout).generate_A(); -} diff --git a/tools/build/protoc.js b/tools/build/protoc.js deleted file mode 100644 index f41c81e120..0000000000 --- a/tools/build/protoc.js +++ /dev/null @@ -1,18 +0,0 @@ -var which = require('which'); -var spawnSync = require('child_process').spawnSync; - -module.exports.detect = function() { - var PROTOC = false; - try { - var bin = 'protoc'; - which.sync(bin); - var version = spawnSync(bin, ['--version']).stdout.toString().replace(/\n/g, ''); - PROTOC = { - bin: bin, - version: version - }; - } catch (e) { - // Ignore, just return `false` instead of an object. - } - return PROTOC; -}; diff --git a/tools/build/pubbuild.js b/tools/build/pubbuild.js deleted file mode 100644 index c6c0434b56..0000000000 --- a/tools/build/pubbuild.js +++ /dev/null @@ -1,78 +0,0 @@ -var util = require('./util'); -var Q = require('q'); -var spawn = require('child_process').spawn; -var through2 = require('through2'); -var path = require('path'); -var glob = require('glob'); -var fs = require('fs'); - -function buildAllWebSubdirs(gulp, plugins, config) { - return function() { - var webFolders = [].slice.call(glob.sync(path.join(config.src, '*/web'))); - return nextFolder(); - - function nextFolder() { - if (!webFolders.length) { - return; - } - var folder = path.resolve(path.join(webFolders.shift(), '..')); - var destFolder = path.resolve(path.join(config.dest, path.basename(folder))); - - const nextConfig = { - command: config.command, - dest: destFolder, - mode: config.mode, - src: folder - }; - return single(nextConfig).then(function() { - return replaceDartWithJsScripts(gulp, destFolder); - }).then(function() { - return removeWebFolder(gulp, destFolder); - }).then(nextFolder); - } - }; -} - -function single(config) { - var pubMode = config.mode || 'release'; - var pubArgs = ['build', '--mode', pubMode]; - if (config.dest) { - pubArgs = pubArgs.concat(['-o', config.dest]); - } - - return util.processToPromise(spawn(config.command, pubArgs, { - stdio: 'inherit', - cwd: config.src - })); -} - -function replaceDartWithJsScripts(gulp, folder) { - return util.streamToPromise(gulp.src(path.join(folder, '**/*.html')) - .pipe(through2.obj(function(file, enc, done) { - var content = file.contents.toString(); - content = content.replace(/\.dart/, '.dart.js'); - content = content.replace(/application\/dart/, 'text/javascript'); - file.contents = new Buffer(content); - this.push(file); - done(); - })) - .pipe(gulp.dest(folder))); -} - -function singleWrapper(gulp, plugins, config) { - return function() { return single(config); }; -} - -function removeWebFolder(gulp, folder) { - var folders = [].slice.call(glob.sync(path.join(folder, 'web', '*'))); - folders.forEach(function(subFolder) { - fs.renameSync(subFolder, subFolder.replace('/web/', '/')); - }); - fs.rmdirSync(path.join(folder, 'web')); - return Q.resolve(); -} - -module.exports = { - single: singleWrapper, - subdirs: buildAllWebSubdirs -}; diff --git a/tools/build/pubget.js b/tools/build/pubget.js deleted file mode 100644 index e2a309bd6b..0000000000 --- a/tools/build/pubget.js +++ /dev/null @@ -1,36 +0,0 @@ -var util = require('./util'); -var spawn = require('child_process').spawn; -var path = require('path'); -var travisFoldStart = require('../travis/travis-fold'); - - -module.exports = { - dir: pubGetDir, - subDir: pubGetSubDir -}; - -function pubGetDir(gulp, plugins, config) { - return function() { - var travisFoldEnd = travisFoldStart(`pubget-${config.dir}`); - - return util.processToPromise(spawn(config.command, ['upgrade'], { - stdio: 'inherit', - cwd: config.dir - })).then(travisFoldEnd); - }; -}; - -function pubGetSubDir(gulp, plugins, config) { - return function() { - var travisFoldEnd = travisFoldStart(`pubget-${config.command}-${config.dir}`); - - // We need to execute pubspec serially as otherwise we can get into trouble - // with the pub cache... - return util.forEachSubDirSequential(config.dir, function(subDir) { - return util.processToPromise(spawn(config.command, ['upgrade'], { - stdio: 'inherit', - cwd: subDir - })); - }).then(travisFoldEnd); - }; -}; diff --git a/tools/build/pubserve.js b/tools/build/pubserve.js deleted file mode 100644 index e468b741eb..0000000000 --- a/tools/build/pubserve.js +++ /dev/null @@ -1,14 +0,0 @@ -var util = require('./util'); -var spawn = require('child_process').spawn; - -module.exports = function(gulp, plugins, config) { - return function() { - config.port = config.port || 8080; - var pubMode = config.mode || 'debug'; - var pubArgs = ['serve', '--mode', pubMode, '--port', config.port]; - return util.streamToPromise(spawn(config.command, pubArgs, { - // pub serve is very spammy, and --verbosity flag doesn't fix it - cwd: config.path, stdio: 'inherit' - })); - }; -}; diff --git a/tools/build/pubtest.js b/tools/build/pubtest.js deleted file mode 100644 index cfba45a6f6..0000000000 --- a/tools/build/pubtest.js +++ /dev/null @@ -1,51 +0,0 @@ -var util = require('./util'); -var spawn = require('child_process').spawn; -var glob = require('glob'); -var path = require('path'); -var fs = require('fs'); -var process = require('process'); -var createTestMain = require('./create_dart_test_main.js') - -function filterExclusiveTestFiles(files, dir) { - return files.filter(function(file) { - // TODO(juliemr): revisit if readFileSync becomes too slow. - // At the moment, this takes <100ms for all of angular2. - var text = fs.readFileSync(path.join(dir, file)); - var iit = text.indexOf('iit('); - var ddescribe = text.indexOf('ddescribe('); - return (iit !== -1 || ddescribe !== -1); - }); -} - -module.exports = function(config) { - var platform = config.platform || 'dartium'; - var pubArgs = ['run', 'test', '-p', platform]; - var env = process.env; - var exclusive = false; - if (config.dartiumTmpdir) { - env['PATH'] = env['PATH'] + ':' + config.dartiumTmpdir; - } - - testFiles = glob.sync(path.join(config.files), {cwd: config.dir}); - - if (config.useExclusiveTests) { - var filtered = filterExclusiveTestFiles(testFiles, config.dir); - if (filtered.length) { - exclusive = true; - pubArgs.push('--tags'); - pubArgs.push('solo'); - testFiles = filtered; - } - } - - if (config.bunchFiles && !exclusive) { - var bigFile = createTestMain(config.dir, testFiles); - testFiles = [bigFile]; - } - - pubArgs = pubArgs.concat(testFiles); - - return util.processToPromise(spawn(config.command, pubArgs, { - cwd: config.dir, stdio: 'inherit', env: env - })); -}; diff --git a/tools/build/run_server_dart_tests.js b/tools/build/run_server_dart_tests.js deleted file mode 100644 index af17bc6317..0000000000 --- a/tools/build/run_server_dart_tests.js +++ /dev/null @@ -1,51 +0,0 @@ -var Q = require('q'); -var glob = require('glob'); -var fs = require('fs'); -var path = require('path'); -var spawn = require('child_process').spawn; - -var util = require('./util'); - -module.exports = function(gulp, plugins, config) { - return function() { - if (config.dir) { - return run(config.dir); - } else { - return util.forEachSubDirSequential(config.dest, run); - } - }; - - function run(dir) { - var testFiles = [].slice.call(glob.sync('**/*.server.spec.dart', { - cwd: dir - })); - if (testFiles.length == 0) { - // No test files found - return Q.resolve(); - } - - var defer = Q.defer(); - var done = defer.makeNodeResolver(); - console.log('start tests:', dir); - var processSerial = function() { - if (testFiles.length == 0) { - done(); - return; - } - var file = testFiles.shift(); - util.processToPromise(spawn('dart', ['-c', file], { - stdio: 'inherit', - cwd: dir - })).then( - processSerial, - function(error) { - done(error); - } - ); - }; - processSerial(); - return defer.promise.then(function() { - console.log('end tests'); - }); - } -}; diff --git a/tools/build/rundartpackage.js b/tools/build/rundartpackage.js deleted file mode 100644 index 3d4b98537a..0000000000 --- a/tools/build/rundartpackage.js +++ /dev/null @@ -1,44 +0,0 @@ -var util = require('./util'); -var Q = require('q'); -var spawn = require('child_process').spawn; -var readline = require('readline'); - -module.exports = function(gulp, plugins, config) { - return function() { - return isInstalled().then(function(installed) { - if (!installed) { - return util.processToPromise(spawn(config.pub, - ['global', 'activate', config.packageName, '--no-executables'], { - stdio: 'inherit' - })); - } - }).then(function() { - return util.processToPromise(spawn(config.pub, ['global', 'run'].concat(config.args), { - stdio: 'inherit' - })); - }); - }; - - function isInstalled() { - var subProcess = spawn(config.pub, ['global', 'list'], { - // inherit stdin and stderr, but filter stdout - stdio: [process.stdin, 'pipe', process.stderr] - }); - var rl = readline.createInterface({ - input: subProcess.stdout, - output: process.stdout, - terminal: false - }); - var found = false; - rl.on('line', function(line) { - if (line.indexOf(config.packageName) !== -1) { - found = true; - } - console.log(line); - }); - return util.processToPromise(subProcess).then( function() { - return found; - }); - } - -};