code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:build_test/build_test.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'util.dart'; void main() { late Map<String, Object> assets; final platform = DartPlatform.register('ddc', ['dart:html']); final kernelOutputExtension = '.test.dill'; group('basic project', () { setUp(() async { assets = { 'b|lib/b.dart': '''final world = 'world';''', 'a|lib/a.dart': r''' import 'package:b/b.dart'; final helloWorld = 'hello $world'; ''', 'a|web/index.dart': r''' import "package:a/a.dart"; main() { print(helloWorld); } ''', }; // Set up all the other required inputs for this test. await testBuilderAndCollectAssets(const ModuleLibraryBuilder(), assets); await testBuilderAndCollectAssets(MetaModuleBuilder(platform), assets); await testBuilderAndCollectAssets( MetaModuleCleanBuilder(platform), assets); await testBuilderAndCollectAssets(ModuleBuilder(platform), assets); }); for (var trackUnusedInputs in [true, false]) { test( 'can output kernel summaries for modules under lib and web' '${trackUnusedInputs ? ' and track unused inputs' : ''}', () async { var builder = KernelBuilder( platform: platform, outputExtension: kernelOutputExtension, summaryOnly: true, sdkKernelPath: p.url.join('lib', '_internal', 'ddc_sdk.dill'), useIncrementalCompiler: trackUnusedInputs, trackUnusedInputs: trackUnusedInputs, ); // We need to compile package:b first - so its kernel file is // available. var expectedOutputs = <String, Matcher>{ 'b|lib/b$kernelOutputExtension': containsAllInOrder(utf8.encode('package:b/b.dart')), }; await testBuilderAndCollectAssets(builder, assets, outputs: expectedOutputs, generateFor: {'b|lib/b${moduleExtension(platform)}'}); // Next, compile package:a expectedOutputs = { 'a|lib/a$kernelOutputExtension': containsAllInOrder(utf8.encode('package:a/a.dart')), }; await testBuilderAndCollectAssets(builder, assets, outputs: expectedOutputs, generateFor: { 'a|lib/a${moduleExtension(platform)}', }); expectedOutputs = { 'a|web/index$kernelOutputExtension': containsAllInOrder(utf8.encode('web/index.dart')), }; // And finally compile a|web/index.dart var reportedUnused = <AssetId, Iterable<AssetId>>{}; await testBuilder(builder, assets, outputs: expectedOutputs, reportUnusedAssetsForInput: (input, unused) => reportedUnused[input] = unused, generateFor: {'a|web/index${moduleExtension(platform)}'}); expect( reportedUnused[ AssetId('a', 'web/index${moduleExtension(platform)}')], equals(trackUnusedInputs ? [AssetId('b', 'lib/b$kernelOutputExtension')] : null), reason: 'Should${trackUnusedInputs ? '' : ' not'} report unused ' 'transitive deps.'); }); } }); group('kernel outlines with missing imports', () { setUp(() async { assets = { 'a|web/index.dart': 'import "package:a/a.dart";', 'a|lib/a.dart': 'import "package:b/b.dart";', }; // Set up all the other required inputs for this test. await testBuilderAndCollectAssets(const ModuleLibraryBuilder(), assets); await testBuilderAndCollectAssets(MetaModuleBuilder(platform), assets); await testBuilderAndCollectAssets( MetaModuleCleanBuilder(platform), assets); await testBuilderAndCollectAssets(ModuleBuilder(platform), assets); await testBuilderAndCollectAssets( KernelBuilder( platform: platform, outputExtension: kernelOutputExtension, summaryOnly: true, sdkKernelPath: p.url.join('lib', '_internal', 'ddc_sdk.dill'), ), assets); }); test('print an error if there are any missing transitive modules', () async { var expectedOutputs = <String, Matcher>{}; var logs = <LogRecord>[]; await testBuilder( KernelBuilder( platform: platform, outputExtension: kernelOutputExtension, summaryOnly: true, sdkKernelPath: p.url.join('lib', '_internal', 'ddc_sdk.dill'), ), assets, outputs: expectedOutputs, onLog: logs.add); expect( logs, contains(predicate<LogRecord>((record) => record.level == Level.SEVERE && record.message .contains('Unable to find modules for some sources')))); }); }); }
build/build_modules/test/kernel_builder_test.dart/0
{'file_path': 'build/build_modules/test/kernel_builder_test.dart', 'repo_id': 'build', 'token_count': 2319}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @Tags(['integration']) import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:_test_common/common.dart'; import 'package:async/async.dart'; import 'package:io/io.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; void main() { setUpAll(() async { await d.dir('a', [ await pubspec( 'a', currentIsolateDependencies: [ 'build', 'build_config', 'build_daemon', 'build_modules', 'build_resolvers', 'build_runner', 'build_runner_core', 'build_test', 'build_web_compilers', 'code_builder', 'test', ], ), d.dir('test', [ d.file('hello_test.dart', ''' import 'package:test/test.dart'; main() { test('hello', () {}); }'''), ]), d.dir('web', [ d.file('main.dart', ''' main() { print('hello world'); }'''), ]), ]).create(); await pubGet('a', offline: false); }); tearDown(() async { expect((await runPub('a', 'run', args: ['build_runner', 'clean'])).exitCode, 0); }); void expectOutput(String path, {required bool exists}) { path = p.join(d.sandbox, 'a', '.dart_tool', 'build', 'generated', 'a', path); expect(File(path).existsSync(), exists); } Future<int> runSingleBuild(String command, List<String> args, {StreamSink<String>? stdoutSink}) async { var process = await startPub('a', 'run', args: args); var stdoutLines = process.stdout .transform(Utf8Decoder()) .transform(LineSplitter()) .asBroadcastStream() ..listen((line) { stdoutSink?.add(line); printOnFailure(line); }); var queue = StreamQueue(stdoutLines); if (command == 'serve' || command == 'watch') { while (await queue.hasNext) { var nextLine = (await queue.next).toLowerCase(); if (nextLine.contains('succeeded after')) { process.kill(); await process.exitCode; return ExitCode.success.code; } else if (nextLine.contains('failed after')) { process.kill(); await process.exitCode; return 1; } } throw StateError('Build process exited without success or failure.'); } var result = await process.exitCode; return result; } group('Building explicit output directories', () { void testBasicBuildCommand(String command) { test('is supported by the $command command', () async { var args = ['build_runner', command, 'web']; expect(await runSingleBuild(command, args), ExitCode.success.code); expectOutput('web/main.dart.js', exists: true); expectOutput('test/hello_test.dart.browser_test.dart.js', exists: false); }); } void testBuildCommandWithOutput(String command) { test('works with -o and the $command command', () async { var outputDirName = 'foo'; var args = [ 'build_runner', command, 'web', '-o', 'test:$outputDirName' ]; expect(await runSingleBuild(command, args), ExitCode.success.code); expectOutput('web/main.dart.js', exists: true); expectOutput('test/hello_test.dart.browser_test.dart.js', exists: true); var outputDir = Directory(p.join(d.sandbox, 'a', 'foo')); await outputDir.delete(recursive: true); }); } for (var command in ['build', 'serve', 'watch']) { testBasicBuildCommand(command); testBuildCommandWithOutput(command); } test('is not supported for the test command', () async { var command = 'test'; var args = ['build_runner', command, 'web']; expect(await runSingleBuild(command, args), ExitCode.usage.code); args.addAll(['--', '-p chrome']); expect(await runSingleBuild(command, args), ExitCode.usage.code); }); }); test('test builds only the test directory by default', () async { var command = 'test'; var args = ['build_runner', command]; expect(await runSingleBuild(command, args), ExitCode.success.code); expectOutput('web/main.dart.js', exists: false); expectOutput('test/hello_test.dart.browser_test.dart.js', exists: true); }); test('hoists output correctly even with --symlink', () async { var command = 'build'; var outputDirName = 'foo'; var args = [ 'build_runner', command, '-o', 'web:$outputDirName', '--symlink' ]; expect(await runSingleBuild(command, args), ExitCode.success.code); var outputDir = Directory(p.join(d.sandbox, 'a', 'foo')); expect(File(p.join(outputDir.path, 'web', 'main.dart.js')).existsSync(), isFalse); expect(File(p.join(outputDir.path, 'main.dart.js')).existsSync(), isTrue); await outputDir.delete(recursive: true); }); test('Duplicate output directories give a nice error', () async { var command = 'build'; var args = ['build_runner', command, '-o', 'web:build', '-o', 'test:build']; var stdoutController = StreamController<String>(); expect( await runSingleBuild(command, args, stdoutSink: stdoutController.sink), ExitCode.usage.code); expect( stdoutController.stream, emitsThrough(contains( 'Invalid argument (--output): Duplicate output directories are not ' 'allowed, got: "web:build test:build"'))); await stdoutController.close(); }); test('Build directories have to be top level dirs', () async { var command = 'build'; var args = ['build_runner', command, '-o', 'foo/bar:build']; var stdoutController = StreamController<String>(); expect( await runSingleBuild(command, args, stdoutSink: stdoutController.sink), ExitCode.usage.code); expect( stdoutController.stream, emitsThrough(contains( 'Invalid argument (--output): Input root can not be nested: ' '"foo/bar:build"'))); await stdoutController.close(); }); test('Handles socket errors gracefully', () async { var server = await HttpServer.bind('localhost', 8080); addTearDown(server.close); var process = await runPub('a', 'run', args: ['build_runner', 'serve', 'web:8080']); expect(process.exitCode, ExitCode.osError.code); expect( process.stdout, allOf(contains('Error starting server'), contains('8080'), contains('address is already in use'))); }); }
build/build_runner/test/entrypoint/run_test.dart/0
{'file_path': 'build/build_runner/test/entrypoint/run_test.dart', 'repo_id': 'build', 'token_count': 2787}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. @Tags(['integration']) import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:_test_common/common.dart'; import 'package:build/build.dart'; import 'package:build_runner/src/generate/watch_impl.dart' as watch_impl; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:shelf/shelf.dart'; import 'package:test/test.dart'; import 'package:watcher/watcher.dart'; void main() { late FutureOr<Response> Function(Request) handler; late InMemoryRunnerAssetReader reader; late InMemoryRunnerAssetWriter writer; late StreamSubscription subscription; late Completer<BuildResult> nextBuild; late StreamController<ProcessSignal> terminateController; final path = p.absolute('example'); setUp(() async { final graph = buildPackageGraph({rootPackage('example', path: path): []}); writer = InMemoryRunnerAssetWriter(); reader = InMemoryRunnerAssetReader.shareAssetCache(writer.assets, rootPackage: 'example') ..cacheStringAsset(AssetId('example', 'web/initial.txt'), 'initial') ..cacheStringAsset(AssetId('example', 'web/large.txt'), List.filled(10000, 'large').join('')) ..cacheStringAsset( makeAssetId('example|.dart_tool/package_config.json'), jsonEncode({ 'configVersion': 2, 'packages': [ { 'name': 'example', 'rootUri': 'file://fake/pkg/path', 'packageUri': 'lib/' }, ], })); terminateController = StreamController<ProcessSignal>(); final server = await watch_impl.watch( [applyToRoot(const UppercaseBuilder())], packageGraph: graph, reader: reader, writer: writer, logLevel: Level.ALL, onLog: (record) => printOnFailure('[${record.level}] ' '${record.loggerName}: ${record.message}'), directoryWatcherFactory: (path) => FakeWatcher(path), terminateEventStream: terminateController.stream, skipBuildScriptCheck: true, ); handler = server.handlerFor('web', logRequests: true); nextBuild = Completer<BuildResult>(); subscription = server.buildResults.listen((result) { nextBuild.complete(result); nextBuild = Completer<BuildResult>(); }); await nextBuild.future; }); tearDown(() async { await subscription.cancel(); terminateController.add(ProcessSignal.sigabrt); await terminateController.close(); }); test('should serve original files', () async { final getHello = Uri.parse('http://localhost/initial.txt'); final response = await handler(Request('GET', getHello)); expect(await response.readAsString(), 'initial'); }); test('should serve original files in parallel', () async { final getHello = Uri.parse('http://localhost/large.txt'); final futures = [ for (var i = 0; i < 512; i++) (() async => await handler(Request('GET', getHello)))(), ]; var responses = await Future.wait(futures); for (var response in responses) { expect(await response.readAsString(), startsWith('large')); } }); test('should serve built files', () async { final getHello = Uri.parse('http://localhost/initial.g.txt'); reader.cacheStringAsset(AssetId('example', 'web/initial.g.txt'), 'INITIAL'); final response = await handler(Request('GET', getHello)); expect(await response.readAsString(), 'INITIAL'); }); test('should 404 on missing files', () async { final get404 = Uri.parse('http://localhost/404.txt'); final response = await handler(Request('GET', get404)); expect(await response.readAsString(), 'Not Found'); }); test('should serve newly added files', () async { final getNew = Uri.parse('http://localhost/new.txt'); reader.cacheStringAsset(AssetId('example', 'web/new.txt'), 'New'); await Future<void>.value(); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.ADD, '$path/web/new.txt'), ); await nextBuild.future; final response = await handler(Request('GET', getNew)); expect(await response.readAsString(), 'New'); }); test('should serve built newly added files', () async { final getNew = Uri.parse('http://localhost/new.g.txt'); reader.cacheStringAsset(AssetId('example', 'web/new.txt'), 'New'); await Future<void>.value(); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.ADD, '$path/web/new.txt'), ); await nextBuild.future; final response = await handler(Request('GET', getNew)); expect(await response.readAsString(), 'NEW'); }); group(r'/$graph', () { FutureOr<Response> requestGraphPath(String path) => handler(Request('GET', Uri.parse('http://localhost/\$graph$path'))); for (var slashOrNot in ['', '/']) { test('/\$graph$slashOrNot should (try to) send the HTML page', () async { expect( requestGraphPath(slashOrNot), throwsA(isA<AssetNotFoundException>().having( (e) => e.assetId, 'assetId', AssetId.parse('build_runner|lib/src/server/graph_viz.html')))); }); } void test404(String testName, String path, String expected) { test(testName, () async { var response = await requestGraphPath(path); expect(response.statusCode, 404); expect(await response.readAsString(), expected); }); } test404('404s on an unsupported URL', '/bob', 'Bad request: "bob".'); test404('404s on an unsupported URL', '/bob/?q=bob', 'Bad request: "bob/?q=bob".'); test404('empty query causes 404', '?=', 'Bad request: "?=".'); test404('bad asset query', '?q=bob|bob', 'Could not find asset in build graph: bob|bob'); test404( 'bad path query', '?q=bob/bob', 'Could not find asset for path "bob/bob". Tried:\n' '- example|bob/bob\n' '- example|web/bob/bob'); test404( 'valid path, 2nd try', '?q=bob/initial.txt', 'Could not find asset for path "bob/initial.txt". Tried:\n' '- example|bob/initial.txt\n' '- example|web/bob/initial.txt'); void testSuccess(String testName, String path, String expectedId) { test(testName, () async { var response = await requestGraphPath(path); var output = await response.readAsString(); expect(response.statusCode, 200, reason: output); var json = jsonDecode(output) as Map<String, dynamic>; expect(json, containsPair('primary', containsPair('id', expectedId))); }); } testSuccess('valid path', '?q=web/initial.txt', 'example|web/initial.txt'); testSuccess('valid path, leading slash', '?q=/web/initial.txt', 'example|web/initial.txt'); testSuccess('valid path, assuming root', '?q=initial.txt', 'example|web/initial.txt'); testSuccess('valid path, assuming root, leading slash', '?q=/initial.txt', 'example|web/initial.txt'); testSuccess('valid AssetId', '?q=example|web/initial.txt', 'example|web/initial.txt'); }); } class UppercaseBuilder implements Builder { const UppercaseBuilder(); @override Future<void> build(BuildStep buildStep) async { final content = await buildStep.readAsString(buildStep.inputId); await buildStep.writeAsString( buildStep.inputId.changeExtension('.g.txt'), content.toUpperCase(), ); } @override final buildExtensions = const { 'txt': ['g.txt'] }; }
build/build_runner/test/server/serve_integration_test.dart/0
{'file_path': 'build/build_runner/test/server/serve_integration_test.dart', 'repo_id': 'build', 'token_count': 2966}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'package:async/async.dart'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'package:glob/glob.dart'; import '../asset_graph/graph.dart'; import '../asset_graph/node.dart'; import '../util/async.dart'; /// A [RunnerAssetReader] must implement [MultiPackageAssetReader]. abstract class RunnerAssetReader implements MultiPackageAssetReader {} /// An [AssetReader] that can provide actual paths to assets on disk. abstract class PathProvidingAssetReader implements AssetReader { String pathTo(AssetId id); } /// Describes if and how a [SingleStepReader] should read an [AssetId]. class Readability { final bool canRead; final bool inSamePhase; const Readability({required this.canRead, required this.inSamePhase}); /// Determines readability for a node written in a previous build phase, which /// means that [ownOutput] is impossible. factory Readability.fromPreviousPhase(bool readable) => readable ? Readability.readable : Readability.notReadable; static const Readability notReadable = Readability(canRead: false, inSamePhase: false); static const Readability readable = Readability(canRead: true, inSamePhase: false); static const Readability ownOutput = Readability(canRead: true, inSamePhase: true); } typedef IsReadable = FutureOr<Readability> Function( AssetNode node, int phaseNum, AssetWriterSpy? writtenAssets); /// Signature of a function throwing an [InvalidInputException] if the given /// asset [id] is an invalid input in a build. typedef CheckInvalidInput = void Function(AssetId id); /// An [AssetReader] with a lifetime equivalent to that of a single step in a /// build. /// /// A step is a single Builder and primary input (or package for package /// builders) combination. /// /// Limits reads to the assets which are sources or were generated by previous /// phases. /// /// Tracks the assets and globs read during this step for input dependency /// tracking. class SingleStepReader implements AssetReader { final AssetGraph _assetGraph; final AssetReader _delegate; final int _phaseNumber; final String _primaryPackage; final AssetWriterSpy? _writtenAssets; final IsReadable _isReadableNode; final CheckInvalidInput _checkInvalidInput; final FutureOr<GlobAssetNode> Function( Glob glob, String package, int phaseNum)? _getGlobNode; /// The assets read during this step. final assetsRead = HashSet<AssetId>(); SingleStepReader(this._delegate, this._assetGraph, this._phaseNumber, this._primaryPackage, this._isReadableNode, this._checkInvalidInput, [this._getGlobNode, this._writtenAssets]); /// Checks whether [id] can be read by this step - attempting to build the /// asset if necessary. /// /// If [catchInvalidInputs] is set to true and [_checkInvalidInput] throws an /// [InvalidInputException], this method will return `false` instead of /// throwing. FutureOr<bool> _isReadable(AssetId id, {bool catchInvalidInputs = false}) { try { _checkInvalidInput(id); } on InvalidInputException { if (catchInvalidInputs) return false; rethrow; } on PackageNotFoundException { if (catchInvalidInputs) return false; rethrow; } final node = _assetGraph.get(id); if (node == null) { assetsRead.add(id); _assetGraph.add(SyntheticSourceAssetNode(id)); return false; } return doAfter(_isReadableNode(node, _phaseNumber, _writtenAssets), (Readability readability) { if (!readability.inSamePhase) { assetsRead.add(id); } return readability.canRead; }); } @override Future<bool> canRead(AssetId id) { return toFuture( doAfter(_isReadable(id, catchInvalidInputs: true), (bool isReadable) { if (!isReadable) return false; var node = _assetGraph.get(id); FutureOr<bool> _canRead() { if (node is GeneratedAssetNode) { // Short circut, we know this file exists because its readable and it was // output. return true; } else { return _delegate.canRead(id); } } return doAfter(_canRead(), (bool canRead) { if (!canRead) return false; return doAfter(_ensureDigest(id), (_) => true); }); })); } @override Future<Digest> digest(AssetId id) { return toFuture(doAfter(_isReadable(id), (bool isReadable) { if (!isReadable) { return Future.error(AssetNotFoundException(id)); } return _ensureDigest(id); })); } @override Future<List<int>> readAsBytes(AssetId id) { return toFuture(doAfter(_isReadable(id), (bool isReadable) { if (!isReadable) { return Future.error(AssetNotFoundException(id)); } return doAfter(_ensureDigest(id), (_) => _delegate.readAsBytes(id)); })); } @override Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) { return toFuture(doAfter(_isReadable(id), (bool isReadable) { if (!isReadable) { return Future.error(AssetNotFoundException(id)); } return doAfter(_ensureDigest(id), (_) => _delegate.readAsString(id, encoding: encoding)); })); } @override Stream<AssetId> findAssets(Glob glob) { if (_getGlobNode == null) { throw StateError('this reader does not support `findAssets`'); } var streamCompleter = StreamCompleter<AssetId>(); doAfter(_getGlobNode!(glob, _primaryPackage, _phaseNumber), (GlobAssetNode globNode) { assetsRead.add(globNode.id); streamCompleter.setSourceStream(Stream.fromIterable(globNode.results!)); }); return streamCompleter.stream; } /// Returns the `lastKnownDigest` of [id], computing and caching it if /// necessary. /// /// Note that [id] must exist in the asset graph. FutureOr<Digest> _ensureDigest(AssetId id) { var node = _assetGraph.get(id)!; if (node.lastKnownDigest != null) return node.lastKnownDigest!; return _delegate.digest(id).then((digest) => node.lastKnownDigest = digest); } }
build/build_runner_core/lib/src/asset/reader.dart/0
{'file_path': 'build/build_runner_core/lib/src/asset/reader.dart', 'repo_id': 'build', 'token_count': 2211}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:watcher/watcher.dart'; import '../environment/build_environment.dart'; import '../package_graph/apply_builders.dart'; import 'build_directory.dart'; import 'build_impl.dart'; import 'build_result.dart'; import 'options.dart'; class BuildRunner { final BuildImpl _build; BuildRunner._(this._build); Future<void> beforeExit() => _build.beforeExit(); Future<BuildResult> run(Map<AssetId, ChangeType> updates, {Set<BuildDirectory> buildDirs = const <BuildDirectory>{}, Set<BuildFilter> buildFilters = const {}}) => _build.run(updates, buildDirs: buildDirs, buildFilters: buildFilters); static Future<BuildRunner> create( BuildOptions options, BuildEnvironment environment, List<BuilderApplication> builders, Map<String, Map<String, dynamic>> builderConfigOverrides, {bool isReleaseBuild = false}) async { return BuildRunner._(await BuildImpl.create( options, environment, builders, builderConfigOverrides, isReleaseBuild: isReleaseBuild)); } }
build/build_runner_core/lib/src/generate/build_runner.dart/0
{'file_path': 'build/build_runner_core/lib/src/generate/build_runner.dart', 'repo_id': 'build', 'token_count': 437}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import '../generate/performance_tracker.dart'; class PerformanceTrackingResolvers implements Resolvers { final Resolvers _delegate; final BuilderActionTracker _tracker; PerformanceTrackingResolvers(this._delegate, this._tracker); @override Future<ReleasableResolver> get(BuildStep buildStep) => _tracker.trackStage('ResolverGet', () => _delegate.get(buildStep)); @override void reset() => _delegate.reset(); }
build/build_runner_core/lib/src/performance_tracking/performance_tracking_resolvers.dart/0
{'file_path': 'build/build_runner_core/lib/src/performance_tracking/performance_tracking_resolvers.dart', 'repo_id': 'build', 'token_count': 218}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; void main() async { var env = IOEnvironment(await PackageGraph.forThisPackage(), assumeTty: true); var result = await env.prompt('Select an option!', ['a', 'b', 'c']); Logger.root.onRecord.listen(env.onLog); Logger('Simple Logger').info(result); }
build/build_runner_core/test/environment/simple_prompt.dart/0
{'file_path': 'build/build_runner_core/test/environment/simple_prompt.dart', 'repo_id': 'build', 'token_count': 179}
name: collection version: 1.9.1
build/build_runner_core/test/fixtures/flutter_pkg/pkg/collection/pubspec.yaml/0
{'file_path': 'build/build_runner_core/test/fixtures/flutter_pkg/pkg/collection/pubspec.yaml', 'repo_id': 'build', 'token_count': 12}
name: a version: 1.0.0
build/build_runner_core/test/fixtures/no_packages_file/pubspec.yaml/0
{'file_path': 'build/build_runner_core/test/fixtures/no_packages_file/pubspec.yaml', 'repo_id': 'build', 'token_count': 12}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:_test_common/common.dart'; import 'package:build_config/build_config.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:test/test.dart'; void main() { group('Resolver Reuse', () { test('Does not remove sources due to crawling for an earlier phase', () async { // If there is an asset which can't be read by an optional phase, but can // be read by a later non-optional phase, and the optional phase starts // later we need to avoid hiding that file from the later-phased reader. var optionalWithResolver = TestBuilder( buildExtensions: appendExtension('.foo'), build: (buildStep, _) async { // Use the resolver so ensure that the entry point is crawled await buildStep.inputLibrary; // If this was non-optional then the the `.imported.dart` file would // not be visible, but we don't care whether it is. return buildStep.writeAsString( buildStep.inputId.addExtension('.foo'), 'anything'); }); var nonOptionalWritesImportedFile = TestBuilder( buildExtensions: replaceExtension('.dart', '.imported.dart'), build: (buildStep, _) => buildStep.writeAsString( buildStep.inputId.changeExtension('.imported.dart'), 'class SomeClass {}')); var nonOptionalResolveImportedFile = TestBuilder( buildExtensions: appendExtension('.bar'), build: (buildStep, _) async { // Fetch the resolver so the imports get crawled. var inputLibrary = await buildStep.inputLibrary; // Force the optional builder to run await buildStep.canRead(buildStep.inputId.addExtension('.foo')); // Check that the `.imported.dart` library is still reachable // through the resolver. var importedLibrary = inputLibrary.importedLibraries.firstWhere( (l) => l.source.uri.path.endsWith('.imported.dart')); var classNames = importedLibrary.definingCompilationUnit.classes .map((c) => c.name) .toList(); return buildStep.writeAsString( buildStep.inputId.addExtension('.bar'), '$classNames'); }); await testBuilders([ applyToRoot(optionalWithResolver, isOptional: true), applyToRoot(nonOptionalWritesImportedFile, generateFor: InputSet(include: ['lib/file.dart'])), applyToRoot(nonOptionalResolveImportedFile, generateFor: InputSet(include: ['lib/file.dart'])), ], { 'a|lib/file.dart': 'import "file.imported.dart";', }, outputs: { 'a|lib/file.dart.bar': '[SomeClass]', 'a|lib/file.dart.foo': 'anything', 'a|lib/file.imported.dart': 'class SomeClass {}', }); }); test('A hidden generated file does not poison resolving', () async { final slowBuilderCompleter = Completer<void>(); final builders = [ applyToRoot( TestBuilder( buildExtensions: replaceExtension('.dart', '.g1.dart'), build: (buildStep, _) async { // Put the analysis driver into the bad state. await buildStep.inputLibrary; await buildStep.writeAsString( buildStep.inputId.changeExtension('.g1.dart'), 'class Annotation {const Annotation();}'); }), generateFor: InputSet(include: ['lib/a.dart'])), applyToRoot( TestBuilder( buildExtensions: replaceExtension('.dart', '.g2.dart'), build: (buildStep, _) async { var library = await buildStep.inputLibrary; var annotation = library .topLevelElements.single.metadata.single .computeConstantValue(); await buildStep.writeAsString( buildStep.inputId.changeExtension('.g2.dart'), '//$annotation'); slowBuilderCompleter.complete(); }), isOptional: true, generateFor: InputSet(include: ['lib/a.dart'])), applyToRoot( TestBuilder( buildExtensions: replaceExtension('.dart', '.slow.dart'), build: (buildStep, _) async { await slowBuilderCompleter.future; await buildStep.writeAsString( buildStep.inputId.changeExtension('.slow.dart'), ''); }), isOptional: true, generateFor: InputSet(include: ['lib/b.dart'])), applyToRoot( TestBuilder( buildExtensions: replaceExtension('.dart', '.root'), build: (buildStep, _) async { await buildStep.inputLibrary; }), generateFor: InputSet(include: ['lib/b.dart'])), ]; await testBuilders(builders, { 'a|lib/a.dart': ''' import 'a.g1.dart'; import 'a.g2.dart'; @Annotation() int x() => 1; ''', 'a|lib/b.dart': r''' import 'a.g1.dart'; import 'a.g2.dart'; import 'b.slow.dart'; ''' }, outputs: { 'a|lib/a.g1.dart': 'class Annotation {const Annotation();}', 'a|lib/a.g2.dart': '//Annotation ()', 'a|lib/b.slow.dart': '', }); }); }); }
build/build_runner_core/test/generate/resolver_reuse_test.dart/0
{'file_path': 'build/build_runner_core/test/generate/resolver_reuse_test.dart', 'repo_id': 'build', 'token_count': 2630}
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:build/build.dart'; import 'package:glob/glob.dart'; /// An [AssetReader] that records which assets have been read to [assetsRead]. abstract class RecordingAssetReader implements AssetReader { Iterable<AssetId> get assetsRead; } /// An implementation of [AssetReader] with primed in-memory assets. class InMemoryAssetReader extends AssetReader implements MultiPackageAssetReader, RecordingAssetReader { final Map<AssetId, List<int>> assets; final String? rootPackage; @override final Set<AssetId> assetsRead = <AssetId>{}; /// Create a new asset reader that contains [sourceAssets]. /// /// Any items in [sourceAssets] which are [String]s will be converted into /// a [List<int>] of bytes. /// /// May optionally define a [rootPackage], which is required for some APIs. InMemoryAssetReader({Map<AssetId, dynamic>? sourceAssets, this.rootPackage}) : assets = _assetsAsBytes(sourceAssets); /// Create a new asset reader backed by [assets]. InMemoryAssetReader.shareAssetCache(this.assets, {this.rootPackage}); static Map<AssetId, List<int>> _assetsAsBytes(Map<AssetId, dynamic>? assets) { if (assets == null || assets.isEmpty) { return {}; } final output = <AssetId, List<int>>{}; assets.forEach((id, stringOrBytes) { if (stringOrBytes is List<int>) { output[id] = stringOrBytes; } else if (stringOrBytes is String) { output[id] = utf8.encode(stringOrBytes); } else { throw UnsupportedError('Invalid asset contents: $stringOrBytes.'); } }); return output; } @override Future<bool> canRead(AssetId id) async { assetsRead.add(id); return assets.containsKey(id); } @override Future<List<int>> readAsBytes(AssetId id) async { if (!await canRead(id)) throw AssetNotFoundException(id); assetsRead.add(id); return assets[id]!; } @override Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) async { if (!await canRead(id)) throw AssetNotFoundException(id); assetsRead.add(id); return encoding.decode(assets[id]!); } @override Stream<AssetId> findAssets(Glob glob, {String? package}) { package ??= rootPackage; if (package == null) { throw UnsupportedError( 'Root package is required to use findAssets without providing an ' 'explicit package.'); } return Stream.fromIterable(assets.keys .where((id) => id.package == package && glob.matches(id.path))); } void cacheBytesAsset(AssetId id, List<int> bytes) { assets[id] = bytes; } void cacheStringAsset(AssetId id, String contents, {Encoding? encoding}) { encoding ??= utf8; assets[id] = encoding.encode(contents); } }
build/build_test/lib/src/in_memory_reader.dart/0
{'file_path': 'build/build_test/lib/src/in_memory_reader.dart', 'repo_id': 'build', 'token_count': 1021}
builders: modules: import: "package:build_vm_compilers/builders.dart" builder_factories: - metaModuleBuilder - metaModuleCleanBuilder - moduleBuilder build_extensions: $lib$: - .vm.meta_module.raw - .vm.meta_module.clean .dart: - .vm.module is_optional: True auto_apply: none required_inputs: [".dart", ".module.library"] applies_builders: ["build_modules:module_cleanup"] vm: import: "package:build_vm_compilers/builders.dart" builder_factories: - vmKernelModuleBuilder build_extensions: .vm.module: - .vm.dill is_optional: True auto_apply: all_packages required_inputs: - .dart - .vm.module applies_builders: - build_vm_compilers:modules entrypoint: import: "package:build_vm_compilers/builders.dart" builder_factories: - vmKernelEntrypointBuilder build_extensions: .dart: - .vm.app.dill required_inputs: - .dart - .vm.dill - .vm.module build_to: cache auto_apply: root_package defaults: generate_for: include: - bin/** - tool/** - test/**.dart.vm_test.dart - example/** - benchmark/**
build/build_vm_compilers/build.yaml/0
{'file_path': 'build/build_vm_compilers/build.yaml', 'repo_id': 'build', 'token_count': 597}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:build/build.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; final defaultAnalysisOptionsId = AssetId('build_modules', 'lib/src/analysis_options.default.yaml'); final sdkDir = p.dirname(p.dirname(Platform.resolvedExecutable)); String defaultAnalysisOptionsArg(ScratchSpace scratchSpace) => '--options=${scratchSpace.fileFor(defaultAnalysisOptionsId).path}'; String sdkDdcKernelPath(bool soundNullSafety) => p.url.join('lib', '_internal', soundNullSafety ? 'ddc_outline_sound.dill' : 'ddc_sdk.dill'); String soundnessExt(bool soundNullSafety) => soundNullSafety ? '.sound' : '.unsound'; /// Validates that [config] only has the top level keys [supportedOptions]. /// /// Throws an [ArgumentError] if not. void validateOptions(Map<String, dynamic> config, List<String> supportedOptions, String builderKey, {List<String> deprecatedOptions = const []}) { var unsupported = config.keys.where( (o) => !supportedOptions.contains(o) && !deprecatedOptions.contains(o)); if (unsupported.isNotEmpty) { throw ArgumentError.value(unsupported.join(', '), builderKey, 'only $supportedOptions are supported options, but got'); } var deprecated = config.keys.where(deprecatedOptions.contains); if (deprecated.isNotEmpty) { log.warning('Found deprecated options ${deprecated.join(', ')}. These no ' 'longer have any effect and should be removed.'); } } /// Fixes up the [uris] from a source map so they make sense in a browser /// context. /// /// - Strips the scheme from the uri /// - Strips the top level directory if its not `packages` /// /// Copied to `web/stack_trace_mapper.dart`, these need to be kept in sync. List<String> fixSourceMapSources(List<String> uris) { return uris.map((source) { var uri = Uri.parse(source); // We only want to rewrite multi-root scheme uris. if (uri.scheme.isEmpty) return source; var newSegments = uri.pathSegments.first == 'packages' ? uri.pathSegments : uri.pathSegments.skip(1); return Uri(path: p.url.joinAll(['/', ...newSegments])).toString(); }).toList(); }
build/build_web_compilers/lib/src/common.dart/0
{'file_path': 'build/build_web_compilers/lib/src/common.dart', 'repo_id': 'build', 'token_count': 800}
// Generated, do not edit const String running = 'Script running!';
build/example/lib/generated/texts/web.dart/0
{'file_path': 'build/example/lib/generated/texts/web.dart', 'repo_id': 'build', 'token_count': 18}
name: scratch_space version: 1.0.2-dev description: A tool to manage running external executables within package:build repository: https://github.com/dart-lang/build/tree/master/scratch_space environment: sdk: ">=2.17.0 <3.0.0" dependencies: build: ^2.0.0 crypto: ^3.0.0 path: ^1.8.0 pool: ^1.5.0 dev_dependencies: build_runner: ^2.0.0 build_test: ^2.0.0 lints: '>=1.0.0 <3.0.0' test: ^1.16.0
build/scratch_space/pubspec.yaml/0
{'file_path': 'build/scratch_space/pubspec.yaml', 'repo_id': 'build', 'token_count': 187}
import 'package:bunq/src/Bunq.dart'; import 'package:bunq/src/models/Session.dart'; import 'package:bunq/src/utils/api.dart'; import 'package:bunq/src/utils/endpoints.dart'; import 'package:bunq/src/utils/log.dart'; import 'package:bunq/src/utils/response.dart'; class Sessions extends Api { Future<Response<Session>> start(String token, int deviceId) async { final payload = <String, dynamic>{"secret": Bunq().apiKey}; Log().debug("$runtimeType.start()", payload); final _response = Response<Session>( await http.post(Endpoints.sessions, payload, shouldSign: true, token: token), onTransform: Session.fromJson, ); Log().debug("$runtimeType.start() -> Response", _response); return _response; } }
bunq.dart/lib/src/api/Sessions.dart/0
{'file_path': 'bunq.dart/lib/src/api/Sessions.dart', 'repo_id': 'bunq.dart', 'token_count': 267}
/// A simple way to cache values that result from rather expensive operations. library cached_value; export 'src/cached_value.dart'; export 'src/dependent_cached_value.dart'; export 'src/simple_cached_value.dart'; export 'src/single_child_cached_value.dart'; export 'src/time_to_live_cached_value.dart';
cached_value/lib/cached_value.dart/0
{'file_path': 'cached_value/lib/cached_value.dart', 'repo_id': 'cached_value', 'token_count': 101}
name: canvas_test_examples description: An example of how to use the canvas_test package version: 0.1.0 homepage: https://github.com/bluefireteam/canvas_test publish_to: none environment: sdk: ">=2.12.0 <3.0.0" flutter: ">=1.24.0" dependencies: flutter: sdk: flutter dev_dependencies: flame_lint: ^0.0.1 flutter_test: sdk: flutter test: ^1.17.10 canvas_test: path: ../
canvas_test/example/pubspec.yaml/0
{'file_path': 'canvas_test/example/pubspec.yaml', 'repo_id': 'canvas_test', 'token_count': 173}
// Copyright (c) 2022, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. /// chance_dart_cli, A Very Good Project created by Very Good CLI. /// /// ```sh /// # activate chance_dart_cli /// dart pub global activate chance_dart_cli /// /// # see usage /// chance_dart_cli --help /// ``` library chance_dart_cli;
chance-dart-cli/lib/chance_dart_cli.dart/0
{'file_path': 'chance-dart-cli/lib/chance_dart_cli.dart', 'repo_id': 'chance-dart-cli', 'token_count': 142}
import 'package:chance_dart/chance_dart.dart' as chance; void main() { /// Usage /// ```chance.[random value to generate]``` /// try { // Generate random address print(chance.address().toJson()); // Generate random age print('AGE'); print(chance.age( max: 100, )); // Generate random amPm print(chance.amPm()); // Generate random age print(chance.animal()); // Generate random areaCode print(chance.areaCode()); // Generate random age print(chance.birthday()); // Generate random boolean print(chance.boolean()); print(chance.birthday()); print(chance.cc( ccType: chance.CCType.mastercard, // visaLength: 20, )); } catch (e) { if (e is chance.ChanceException) { print(e.message); } } // Generate random boolean // print(chance.ccType()); // print(UserWrapper().generatedModel()); // print(ChanceModelWrapper().generatedModels()); // Generate random address print(chance.address().toJson()); // Generate random age print(chance.age()); // Generate random amPm print(chance.amPm()); // Generate random age print(chance.animal()); // Generate random areaCode print(chance.areaCode()); // Generate random age print(chance.birthday()); // Generate random boolean print(chance.boolean()); /// for more random values checkout the docs https://docs.page/Yczar/chance-dart }
chance-dart/packages/chance_dart/example/chance_dart_example.dart/0
{'file_path': 'chance-dart/packages/chance_dart/example/chance_dart_example.dart', 'repo_id': 'chance-dart', 'token_count': 503}
import 'dart:math'; import 'character.dart'; const String _lowerCaseChars = 'abcdefghijklmnopqrstuvwxyz'; const String _upperCaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const String _symbols = '!@#\$%^&*()'; const String _numbers = '0123456789'; const String _chars = '$_lowerCaseChars$_upperCaseChars$_numbers$_symbols'; /// It generates a random string of characters from a given string of characters /// /// Args: /// length (int): The length of the string to be generated. Defaults to 5 /// max (int): The maximum length of the string to be generated. /// pool (String): The characters to use for the random string. /// alpha (bool): If true, the string will only contain alphabetic characters. /// casing (Casing): The casing of the string to be generated. /// symbols (bool): If true, the string will contain symbols. /// /// Returns: /// A string of random characters. String string({ int length = 5, int? max, String? pool, bool? alpha, Casing? casing, bool? symbols, }) { assert(casing != null && symbols == true); if (alpha == null && pool == null && casing == null && symbols == null) { return _getRandomString(null, length: max ?? 5); } else if (alpha == true) { return _getRandomString( _upperCaseChars, length: max ?? 5, ); } else if (pool != null) { return _getRandomString(pool, length: max ?? 5); } else if (casing != null) { if (casing == Casing.lower) { return _getRandomString(_lowerCaseChars, length: max ?? 5); } return _getRandomString(_upperCaseChars, length: max ?? 5); } else if (symbols != null) { return _getRandomString(_symbols); } return _getRandomString(null, length: max ?? 5); } /// It generates a random string of characters from a given string of characters /// /// Args: /// chars (String): The characters to use for the random string. /// length (int): The length of the string to be generated. String _getRandomString(String? chars, {int? length}) => String.fromCharCodes( Iterable.generate( length ?? 1, (_) => chars?.codeUnitAt( Random().nextInt(chars.length), ) ?? _chars.codeUnitAt( Random().nextInt(_chars.length), ), ), );
chance-dart/packages/chance_dart/lib/core/basics/src/string.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/basics/src/string.dart', 'repo_id': 'chance-dart', 'token_count': 825}
import 'package:chance_dart/chance_dart.dart'; /// Generate a random integer between the current year and the current year /// plus 10. /// /// Returns: /// A random integer between the current year and 10 years from now. String expYear() { final now = DateTime.now().year; return '${floating(max: now + 10, min: now).ceil()}'; }
chance-dart/packages/chance_dart/lib/core/finance/src/exp_year.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/finance/src/exp_year.dart', 'repo_id': 'chance-dart', 'token_count': 105}
import 'package:dart_geohash/dart_geohash.dart'; import '../../core.dart'; /// It takes a random address, gets the coordinates, and then uses the /// GeoHasher library to encode those /// coordinates into a geohash /// /// Returns: /// A string String geohash() { final mainAddress = address(); if (mainAddress.coordinates?.latitude == null || mainAddress.coordinates?.longitude == null) { return geohash(); } return GeoHasher().encode( mainAddress.coordinates!.longitude!, mainAddress.coordinates!.longitude!, ); }
chance-dart/packages/chance_dart/lib/core/location/src/geohash.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/location/src/geohash.dart', 'repo_id': 'chance-dart', 'token_count': 182}
import 'package:chance_dart/chance_dart.dart'; /// `age` returns a random integer between 0 and 123 /// /// Args: /// max (int): The maximum value of the integer. /// /// Returns: /// A random integer between 0 and 123 int age({int? max}) { return integer(max: max ?? 123); }
chance-dart/packages/chance_dart/lib/core/person/src/age.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/person/src/age.dart', 'repo_id': 'chance-dart', 'token_count': 93}
export 'src/paragraph.dart'; export 'src/sentence.dart'; export 'src/syllable.dart'; export 'src/word.dart';
chance-dart/packages/chance_dart/lib/core/text/text.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/text/text.dart', 'repo_id': 'chance-dart', 'token_count': 43}
export 'src/am_pm.dart'; export 'src/date.dart'; export 'src/hour.dart'; export 'src/millisecond.dart'; export 'src/minute.dart'; export 'src/month.dart'; export 'src/second.dart'; export 'src/timestamp.dart'; export 'src/weekday.dart'; export 'src/year.dart';
chance-dart/packages/chance_dart/lib/core/time/time.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/time/time.dart', 'repo_id': 'chance-dart', 'token_count': 106}
import 'package:chance_dart/chance_dart.dart'; import 'package:chance_dart/core/text/constants/sentences.dart'; import 'package:test/test.dart'; void main() { test( 'verify that sentence returned is from a list of sentences', () => expect( sentence(), isIn(sentences), ), ); }
chance-dart/packages/chance_dart/test/core/text/sentences_test.dart/0
{'file_path': 'chance-dart/packages/chance_dart/test/core/text/sentences_test.dart', 'repo_id': 'chance-dart', 'token_count': 118}
import 'package:test/test.dart'; void main() { test('example', () {}); }
ci/packages/a/test/example_test.dart/0
{'file_path': 'ci/packages/a/test/example_test.dart', 'repo_id': 'ci', 'token_count': 29}
import 'package:args/command_runner.dart'; import 'package:mason_logger/mason_logger.dart'; /// A command that only has a sub command class SomeOtherCommand extends Command<int> { SomeOtherCommand(this._logger) { addSubcommand(_SomeSubCommand(_logger)); } final Logger _logger; @override String get description => 'This is help for some_other_command'; @override String get name => 'some_other_command'; } /// A command under [SomeOtherCommand] that does not receive options and read /// the "rest" field from arg results class _SomeSubCommand extends Command<int> { _SomeSubCommand(this._logger) { argParser.addFlag( 'flag', help: 'a flag just to show we are in the subcommand', ); } final Logger _logger; @override String get description => 'A sub command of some_other_command'; @override String get name => 'subcommand'; @override List<String> get aliases => ['subcommand_alias']; @override Future<int> run() async { _logger.info(description); for (final rest in argResults!.rest) { _logger.info(' - $rest'); } return ExitCode.success.code; } }
cli_completion/example/lib/src/commands/some_other_commmand.dart/0
{'file_path': 'cli_completion/example/lib/src/commands/some_other_commmand.dart', 'repo_id': 'cli_completion', 'token_count': 386}
import 'dart:io'; import 'package:cli_completion/installer.dart'; import 'package:mason_logger/mason_logger.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; /// {@template shell_completion_installation} /// Manages the installation of completion scripts for the current shell. /// /// Creation should be done via [CompletionInstallation.fromSystemShell]. /// {@endtemplate} class CompletionInstallation { /// {@macro shell_completion_installation} @visibleForTesting CompletionInstallation({ required this.configuration, required this.logger, required this.isWindows, required this.environment, }); /// Creates a [CompletionInstallation] given the current [systemShell]. /// /// If [systemShell] is null, it will assume that the current shell is /// unknown and [configuration] will be null. /// /// Pass [isWindowsOverride] to override the default value of /// [Platform.isWindows]. /// /// Pass [environmentOverride] to override the default value of /// [Platform.environment]. factory CompletionInstallation.fromSystemShell({ required SystemShell? systemShell, required Logger logger, bool? isWindowsOverride, Map<String, String>? environmentOverride, }) { final isWindows = isWindowsOverride ?? Platform.isWindows; final environment = environmentOverride ?? Platform.environment; final configuration = systemShell == null ? null : ShellCompletionConfiguration.fromSystemShell(systemShell); return CompletionInstallation( configuration: configuration, logger: logger, isWindows: isWindows, environment: environment, ); } /// The injected [Logger]; final Logger logger; /// Defines whether the installation is running on windows or not. final bool isWindows; /// Describes the environment variables. Usually /// equals to [Platform.environment]. final Map<String, String> environment; /// The associated [ShellCompletionConfiguration] inferred from the current /// shell. It is null if the current shell is unknown. final ShellCompletionConfiguration? configuration; /// Define the [Directory] in which the /// completion configuration files will be stored. /// /// If [isWindows] is true, it will return the directory defined by /// %LOCALAPPDATA%/DartCLICompletion /// /// If [isWindows] is false, it will return the directory defined by /// $XDG_CONFIG_HOME/.dart_cli_completion or $HOME/.dart_cli_completion @visibleForTesting Directory get completionConfigDir { if (isWindows) { // Use localappdata on windows final localAppData = environment['LOCALAPPDATA']!; return Directory(path.join(localAppData, 'DartCLICompletion')); } else { // Try using XDG config folder var dirPath = environment['XDG_CONFIG_HOME']; // Fallback to $HOME if not following XDG specification if (dirPath == null || dirPath.isEmpty) { dirPath = environment['HOME']; } return Directory(path.join(dirPath!, '.dart-cli-completion')); } } /// Define the [File] in which the completion configuration is stored. @visibleForTesting File get completionConfigurationFile { return File(path.join(completionConfigDir.path, 'config.json')); } /// Install completion configuration files for a [rootCommand] in the /// current shell. /// /// It will create: /// - A completion script file in [completionConfigDir] that is named after /// the [rootCommand] and the current shell (e.g. `very_good.bash`). /// - A config file in [completionConfigDir] that is named after the current /// shell (e.g. `bash-config.bash`) that sources the aforementioned /// completion script file. /// - A line in the shell config file (e.g. `.bash_profile`) that sources /// the aforementioned config file. /// /// If [force] is true, it will overwrite the command's completion files even /// if they already exist. If false, it will check if is already installed, or /// if it has been explicitly uninstalled before installing it. void install(String rootCommand, {bool force = false}) { final configuration = this.configuration; if (configuration == null) { throw CompletionInstallationException( message: 'Unknown shell.', rootCommand: rootCommand, ); } if (!force && !_shouldInstall(rootCommand)) { return; } logger.detail( 'Installing completion for the command $rootCommand ' 'on ${configuration.shell.name}', ); createCompletionConfigDir(); final completionFileCreated = writeCompletionScriptForCommand(rootCommand); writeCompletionConfigForShell(rootCommand); writeToShellConfigFile(rootCommand); if (completionFileCreated) { _logSourceInstructions(rootCommand); } final completionConfiguration = CompletionConfiguration.fromFile(completionConfigurationFile); completionConfiguration .copyWith( uninstalls: completionConfiguration.uninstalls.exclude( command: rootCommand, systemShell: configuration.shell, ), installs: completionConfiguration.installs.include( command: rootCommand, systemShell: configuration.shell, ), ) .writeTo(completionConfigurationFile); } /// Wether the completion configuration files for a [rootCommand] should be /// installed or not. /// /// It will return false if the root command is already installed or it /// has been explicitly uninstalled. bool _shouldInstall(String rootCommand) { final completionConfiguration = CompletionConfiguration.fromFile( completionConfigurationFile, ); final systemShell = configuration!.shell; final isInstalled = completionConfiguration.installs.contains( command: rootCommand, systemShell: systemShell, ); final isUninstalled = completionConfiguration.uninstalls.contains( command: rootCommand, systemShell: systemShell, ); return !isInstalled && !isUninstalled; } /// Create a directory in which the completion config files shall be saved. /// If the directory already exists, it will do nothing. /// /// The directory is defined by [completionConfigDir]. @visibleForTesting void createCompletionConfigDir() { final completionConfigDirPath = completionConfigDir.path; logger.info( 'Creating completion configuration directory ' 'at $completionConfigDirPath', ); if (completionConfigDir.existsSync()) { logger.warn( 'A ${completionConfigDir.path} directory was already found.', ); return; } completionConfigDir.createSync(); } /// Creates a configuration file exclusively to [rootCommand] and the /// identified shell. /// /// The file will be named after the [rootCommand] and the current shell /// (e.g. `very_good.bash`). /// /// The file will be created in [completionConfigDir]. /// /// If the file already exists, it will do nothing. /// /// Returns true if the file was created, false otherwise. @visibleForTesting bool writeCompletionScriptForCommand(String rootCommand) { final configuration = this.configuration!; final completionConfigDirPath = completionConfigDir.path; final commandScriptName = '$rootCommand.${configuration.shell.name}'; final commandScriptPath = path.join( completionConfigDirPath, commandScriptName, ); logger.info( 'Writing completion script for $rootCommand on $commandScriptPath', ); final scriptFile = File(commandScriptPath); if (scriptFile.existsSync()) { logger.warn( 'A script file for $rootCommand was already found on ' '$commandScriptPath.', ); return false; } scriptFile.writeAsStringSync(configuration.scriptTemplate(rootCommand)); return true; } /// Adds a reference for the command-specific config file created on /// [writeCompletionScriptForCommand] the the global completion config file. @visibleForTesting void writeCompletionConfigForShell(String rootCommand) { final configuration = this.configuration!; final completionConfigDirPath = completionConfigDir.path; final configPath = path.join( completionConfigDirPath, configuration.completionConfigForShellFileName, ); logger.info('Adding config for $rootCommand config entry to $configPath'); final configFile = File(configPath); if (!configFile.existsSync()) { logger.info('No file found at $configPath, creating one now'); configFile.createSync(); } if (ScriptConfigurationEntry(rootCommand).existsIn(configFile)) { logger.warn( 'A config entry for $rootCommand was already found on $configPath.', ); return; } final commandScriptName = '$rootCommand.${configuration.shell.name}'; _sourceScriptOnFile( configFile: configFile, scriptName: rootCommand, scriptPath: path.join(completionConfigDirPath, commandScriptName), ); } String get _shellRCFilePath => _resolveHome(configuration!.shellRCFile, environment); /// Write a source to the completion global script in the shell configuration /// file, which its location is described by the [configuration]. @visibleForTesting void writeToShellConfigFile(String rootCommand) { final configuration = this.configuration!; logger.info( 'Adding dart cli completion config entry ' 'to $_shellRCFilePath', ); final shellRCFile = File(_shellRCFilePath); if (!shellRCFile.existsSync()) { throw CompletionInstallationException( rootCommand: rootCommand, message: 'No configuration file found at ${shellRCFile.path}', ); } if (const ScriptConfigurationEntry('Completion').existsIn(shellRCFile)) { logger.warn( '''A completion config entry was already found on $_shellRCFilePath.''', ); return; } _sourceScriptOnFile( configFile: shellRCFile, scriptName: 'Completion', description: 'Completion scripts setup. ' 'Remove the following line to uninstall', scriptPath: path.join( completionConfigDir.path, configuration.completionConfigForShellFileName, ), ); } /// Tells the user to source the shell configuration file. void _logSourceInstructions(String rootCommand) { final level = logger.level; logger ..level = Level.info ..info( '\n' 'Completion files installed. To enable completion, run the following ' 'command in your shell:\n' '${lightCyan.wrap('source $_shellRCFilePath')}' '\n', ) ..level = level; } void _sourceScriptOnFile({ required File configFile, required String scriptName, required String scriptPath, String? description, }) { assert( configFile.existsSync(), 'Sourcing a script line into an nonexistent config file.', ); final configFilePath = configFile.path; description ??= 'Completion config for "$scriptName"'; final content = ''' ## $description ${configuration!.sourceLineTemplate(scriptPath)}'''; ScriptConfigurationEntry(scriptName).appendTo( configFile, content: content, ); logger.info('Added config to $configFilePath'); } /// Uninstalls the completion for the command [rootCommand] on the current /// shell. /// /// Before uninstalling, it checks if the completion is installed: /// - The shell has an existing RCFile with a completion /// [ScriptConfigurationEntry]. /// - The shell has an existing completion configuration file with a /// [ScriptConfigurationEntry] for the [rootCommand]. /// /// If any of the above is not true, it throws a /// [CompletionUninstallationException]. /// /// Upon a successful uninstallation the executable [ScriptConfigurationEntry] /// is removed from the shell configuration file. If after this removal the /// latter is empty, it is deleted together with the the executable completion /// script and the completion [ScriptConfigurationEntry] from the shell RC /// file. In the case that there are no other completion scripts installed on /// other shells the completion config directory is deleted, leaving the /// user's system as it was before the installation. void uninstall(String rootCommand) { final configuration = this.configuration!; logger.detail( '''Uninstalling completion for the command $rootCommand on ${configuration.shell.name}''', ); final shellRCFile = File(_shellRCFilePath); if (!shellRCFile.existsSync()) { throw CompletionUninstallationException( rootCommand: rootCommand, message: 'No shell RC file found at ${shellRCFile.path}', ); } const completionEntry = ScriptConfigurationEntry('Completion'); if (!completionEntry.existsIn(shellRCFile)) { throw CompletionUninstallationException( rootCommand: rootCommand, message: 'Completion is not installed at ${shellRCFile.path}', ); } final shellCompletionConfigurationFile = File( path.join( completionConfigDir.path, configuration.completionConfigForShellFileName, ), ); final executableEntry = ScriptConfigurationEntry(rootCommand); if (!executableEntry.existsIn(shellCompletionConfigurationFile)) { throw CompletionUninstallationException( rootCommand: rootCommand, message: '''No shell script file found at ${shellCompletionConfigurationFile.path}''', ); } final executableShellCompletionScriptFile = File( path.join( completionConfigDir.path, '$rootCommand.${configuration.shell.name}', ), ); if (executableShellCompletionScriptFile.existsSync()) { executableShellCompletionScriptFile.deleteSync(); } executableEntry.removeFrom( shellCompletionConfigurationFile, shouldDelete: true, ); if (!shellCompletionConfigurationFile.existsSync()) { completionEntry.removeFrom(shellRCFile); } final completionConfigDirContent = completionConfigDir.listSync(); final onlyHasConfigurationFile = completionConfigDirContent.length == 1 && path.absolute(completionConfigDirContent.first.path) == path.absolute(completionConfigurationFile.path); if (completionConfigDirContent.isEmpty || onlyHasConfigurationFile) { completionConfigDir.deleteSync(recursive: true); } else { final completionConfiguration = CompletionConfiguration.fromFile(completionConfigurationFile); completionConfiguration .copyWith( uninstalls: completionConfiguration.uninstalls.include( command: rootCommand, systemShell: configuration.shell, ), installs: completionConfiguration.installs.exclude( command: rootCommand, systemShell: configuration.shell, ), ) .writeTo(completionConfigurationFile); } } } /// Resolve the home from a path string String _resolveHome( String originalPath, Map<String, String> environment, ) { final after = originalPath.split('~/').last; final home = path.absolute(environment['HOME']!); return path.join(home, after); }
cli_completion/lib/src/installer/completion_installation.dart/0
{'file_path': 'cli_completion/lib/src/installer/completion_installation.dart', 'repo_id': 'cli_completion', 'token_count': 4991}
name: ci concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: branches: - main jobs: semantic_pull_request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_channel: stable flutter_version: 3.3.7
cloud9/.github/workflows/main.yaml/0
{'file_path': 'cloud9/.github/workflows/main.yaml', 'repo_id': 'cloud9', 'token_count': 178}
name: no-response-test # Declare default permissions as read only. permissions: read-all on: pull_request: paths: - 'gh_actions/third_party/no-response/**' - '.github/workflows/no-response_test.yaml' - '.github/workflows/no-response_publish.yaml' jobs: unitTest: runs-on: ubuntu-latest if: ${{ github.repository == 'flutter/cocoon' }} steps: - name: Checkout uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 with: ref: ${{ github.event.release.tag_name }} sparse-checkout: 'gh_actions/third_party/no-response' sparse-checkout-cone-mode: false - name: move_package_to_root run: | mv -f gh_actions/third_party/no-response/{.[!.],}* ./ rm -rf gh_actions - name: ls run: ls -la - name: npm_ci run: npm ci - name: npm_run_ci run: npm run ci - name: npm_run_build run: npm run build
cocoon/.github/workflows/no-response_test.yaml/0
{'file_path': 'cocoon/.github/workflows/no-response_test.yaml', 'repo_id': 'cocoon', 'token_count': 465}
// Copyright 2021 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:github/github.dart'; import 'package:process/process.dart'; import 'package:test/test.dart'; import 'common.dart'; /// List of supported repositories with TESTOWNERS. final List<SupportedConfig> configs = <SupportedConfig>[ SupportedConfig(RepositorySlug('flutter', 'flutter')), ]; Future<void> main() async { for (final SupportedConfig config in configs) { test('validate test ownership for $config', () async { const String dart = 'dart'; const String taskExecutable = 'bin/validate_task_ownership.dart'; final List<String> taskArgs = <String>[config.slug.name, config.branch]; const ProcessManager processManager = LocalProcessManager(); final Process process = await processManager.start( <String>[dart, taskExecutable, ...taskArgs], workingDirectory: Directory.current.path, ); final List<String> output = <String>[]; final List<String> error = <String>[]; process.stdout .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) { stdout.writeln('[STDOUT] $line'); output.add(line); }); process.stderr .transform<String>(const Utf8Decoder()) .transform<String>(const LineSplitter()) .listen((String line) { stderr.writeln('[STDERR] $line'); error.add(line); }); final int exitCode = await process.exitCode; if (exitCode != 0) { for (String line in error) { print(line); } fail('An error has occurred.'); } }); } }
cocoon/app_dart/integration_test/validate_test_ownership_test.dart/0
{'file_path': 'cocoon/app_dart/integration_test/validate_test_ownership_test.dart', 'repo_id': 'cocoon', 'token_count': 709}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:gcloud/db.dart'; import 'package:json_annotation/json_annotation.dart'; import 'key_helper.dart'; /// A converter for [Key]s encoded as strings. class StringKeyConverter implements JsonConverter<Key<String>?, String> { const StringKeyConverter(); @override Key<String>? fromJson(String? json) => (json == null || json.isEmpty) ? null : KeyHelper().decode(json) as Key<String>; @override String toJson(Key<String>? key) => key == null ? '' : KeyHelper().encode(key); } /// A converter for [Key]s encoded as strings. class IntKeyConverter implements JsonConverter<Key<int>, String> { const IntKeyConverter(); @override Key<int> fromJson(String json) => KeyHelper().decode(json) as Key<int>; @override String toJson(Key<int?> key) => KeyHelper().encode(key); }
cocoon/app_dart/lib/src/model/appengine/key_converter.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/appengine/key_converter.dart', 'repo_id': 'cocoon', 'token_count': 327}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' hide json; import 'dart:convert' as convert show json; import 'package:json_annotation/json_annotation.dart'; /// A converter for tags. /// /// The JSON format is: /// /// ```json /// [ /// { /// "key": "tag_key", /// "value": "tag_value" /// } /// ] /// ``` /// /// Which is flattened out as a `Map<String, List<String>>`. class TagsConverter implements JsonConverter<Map<String?, List<String?>>?, List<dynamic>?> { const TagsConverter(); @override Map<String?, List<String?>>? fromJson(List<dynamic>? json) { if (json == null) { return null; } final Map<String?, List<String?>> result = <String?, List<String?>>{}; for (Map<String, dynamic> tag in json.cast<Map<String, dynamic>>()) { final String? key = tag['key'] as String?; result[key] ??= <String?>[]; result[key]!.add(tag['value'] as String?); } return result; } @override List<Map<String, dynamic>>? toJson(Map<String?, List<String?>>? object) { if (object == null) { return null; } if (object.isEmpty) { return const <Map<String, List<String>>>[]; } final List<Map<String, String>> result = <Map<String, String>>[]; for (String? key in object.keys) { if (key == null) { continue; } final List<String?>? values = object[key]; if (values == null) { continue; } for (String? value in values) { if (value == null) { continue; } result.add(<String, String>{ 'key': key, 'value': value, }); } } return result; } } /// A converter for a "binary" JSON field. /// /// Encodes and decodes a String to and from base64. class Base64Converter implements JsonConverter<String, String> { const Base64Converter(); @override String fromJson(String json) { return utf8.decode(base64.decode(json)); } @override String toJson(String object) { return base64.encode(utf8.encode(object)); } } /// A converter for "timestamp" fields encoded as microseconds since epoch. class MicrosecondsSinceEpochConverter implements JsonConverter<DateTime?, String?> { const MicrosecondsSinceEpochConverter(); @override DateTime? fromJson(String? json) { if (json == null) { return null; } return DateTime.fromMicrosecondsSinceEpoch(int.parse(json)); } @override String? toJson(DateTime? object) { if (object == null) { return null; } return object.microsecondsSinceEpoch.toString(); } } /// A converter for "timestamp" fields encoded as seconds since epoch. class SecondsSinceEpochConverter implements JsonConverter<DateTime?, String?> { const SecondsSinceEpochConverter(); @override DateTime? fromJson(String? json) { if (json == null) { return null; } return DateTime.fromMillisecondsSinceEpoch(int.parse(json) * 1000); } @override String? toJson(DateTime? dateTime) { if (dateTime == null) { return null; } final int secondsSinceEpoch = dateTime.millisecondsSinceEpoch ~/ 1000; return secondsSinceEpoch.toString(); } } /// A converter for boolean fields encoded as strings. class BoolConverter implements JsonConverter<bool?, String?> { const BoolConverter(); @override bool? fromJson(String? json) { if (json == null) { return null; } return json.toLowerCase() == 'true'; } @override String? toJson(bool? value) { if (value == null) { return null; } return '$value'; } } /// A converter for fields with nested JSON objects in String format. class NestedJsonConverter implements JsonConverter<Map<String, dynamic>?, String?> { const NestedJsonConverter(); @override Map<String, dynamic>? fromJson(String? json) { if (json == null) { return null; } return convert.json.decode(json) as Map<String, dynamic>?; } @override String? toJson(Map<String, dynamic>? object) { if (object == null) { return null; } return convert.json.encode(object); } } const Map<String, int> _months = <String, int>{ 'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12, }; /// Convert a DateTime format from Gerrit to [DateTime]. /// /// Example format is "Wed Jun 07 22:54:06 2023 +0000" class GerritDateTimeConverter implements JsonConverter<DateTime?, String?> { const GerritDateTimeConverter(); @override DateTime? fromJson(String? json) { if (json == null) { return null; } final DateTime? date = DateTime.tryParse(json); if (date != null) { return date; } json = json.substring(4); // Trim day of the week final List<String> parts = json.split(' '); final int month = _months[parts[0]]!; final int year = int.parse(parts[3]); final int day = int.parse(parts[1]); final List<String> time = parts[2].split(':'); final int hours = int.parse(time[0]); final int minutes = int.parse(time[1]); final int seconds = int.parse(time[2]); return DateTime(year, month, day, hours, minutes, seconds); } @override String? toJson(DateTime? object) { return object?.toIso8601String(); } }
cocoon/app_dart/lib/src/model/common/json_converters.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/common/json_converters.dart', 'repo_id': 'cocoon', 'token_count': 2106}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'package:crypto/crypto.dart'; import '../model/proto/protos.dart' as pb; import '../request_handling/body.dart'; import '../request_handling/exceptions.dart'; import '../request_handling/pubsub.dart'; import '../request_handling/request_handler.dart'; import '../service/logging.dart'; /// The [RequestHandler] for processing GitHub webhooks and publishing valid events to PubSub. /// /// Requests are only published as a [GithubWebhookMessage] iff they contain: /// 1. Event type from the header `X-GitHub-Event` /// 2. Event payload that was HMAC authenticated class GithubWebhook extends RequestHandler<Body> { GithubWebhook({ required super.config, required this.pubsub, required this.secret, required this.topic, }); final PubSub pubsub; /// PubSub topic to publish authenticated requests to. final String topic; /// Future that resolves to the GitHub apps webhook secret. final Future<String> secret; @override Future<Body> post() async { final String? event = request!.headers.value('X-GitHub-Event'); if (event == null || request!.headers.value('X-Hub-Signature') == null) { throw const BadRequestException('Missing required headers.'); } final List<int> requestBytes = await request!.expand((_) => _).toList(); final String? hmacSignature = request!.headers.value('X-Hub-Signature'); await _validateRequest(hmacSignature, requestBytes); final String requestString = utf8.decode(requestBytes); final pb.GithubWebhookMessage message = pb.GithubWebhookMessage.create() ..event = event ..payload = requestString; log.fine(message); await pubsub.publish(topic, message.writeToJsonMap()); return Body.empty; } /// Ensures the signature provided for the given payload matches what is expected. /// /// The expected key is the sha1 hash of the payload using the private key of the GitHub app. Future<void> _validateRequest( String? signature, List<int> requestBody, ) async { final String rawKey = await secret; final List<int> key = utf8.encode(rawKey); final Hmac hmac = Hmac(sha1, key); final Digest digest = hmac.convert(requestBody); final String bodySignature = 'sha1=$digest'; if (bodySignature != signature) { throw const Forbidden('X-Hub-Signature does not match expected value'); } } }
cocoon/app_dart/lib/src/request_handlers/github_webhook.dart/0
{'file_path': 'cocoon/app_dart/lib/src/request_handlers/github_webhook.dart', 'repo_id': 'cocoon', 'token_count': 826}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:appengine/appengine.dart'; import 'package:auto_submit/helpers.dart'; import 'package:auto_submit/request_handling/authentication.dart'; import 'package:auto_submit/requests/check_pull_request.dart'; import 'package:auto_submit/requests/check_revert_request.dart'; import 'package:auto_submit/requests/github_webhook.dart'; import 'package:auto_submit/requests/readiness_check.dart'; import 'package:auto_submit/service/config.dart'; import 'package:auto_submit/service/secrets.dart'; import 'package:neat_cache/neat_cache.dart'; import 'package:shelf_router/shelf_router.dart'; /// Number of entries allowed in [Cache]. const int kCacheSize = 1024; Future<void> main() async { await withAppEngineServices(() async { useLoggingPackageAdaptor(); final cache = Cache.inMemoryCacheProvider(kCacheSize); final Config config = Config( cacheProvider: cache, secretManager: CloudSecretManager(), ); const CronAuthProvider authProvider = CronAuthProvider(); final Router router = Router() ..post( '/webhook', GithubWebhook( config: config, ).post, ) ..get( '/check-pull-request', CheckPullRequest( config: config, cronAuthProvider: authProvider, ).run, ) ..get( '/check-revert-requests', CheckRevertRequest( config: config, cronAuthProvider: authProvider, ).run, ) ..get( '/readiness_check', ReadinessCheck( config: config, ).run, ); await serveHandler(router.call); }); }
cocoon/auto_submit/bin/server.dart/0
{'file_path': 'cocoon/auto_submit/bin/server.dart', 'repo_id': 'cocoon', 'token_count': 715}
// Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// There are two ways to clone the repository which will be configurable in the /// repository configuration in .github. enum GitAccessMethod { SSH, HTTP, } /// Wrapper class to create a revert branch that is comprised of the prefix /// revert_ and the commit sha so the branch is easily identifiable. class GitRevertBranchName { final String _commitSha; const GitRevertBranchName(this._commitSha); static const String _branchPrefix = 'revert'; String get branch => '${_branchPrefix}_$_commitSha'; }
cocoon/auto_submit/lib/git/utilities.dart/0
{'file_path': 'cocoon/auto_submit/lib/git/utilities.dart', 'repo_id': 'cocoon', 'token_count': 191}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:auto_submit/model/pull_request_data_types.dart'; import 'package:test/test.dart'; void main() { final List<String> expectedNames = ['change', 'revert']; test('Expected string value for enum is returned.', () { for (PullRequestChangeType prChangeType in PullRequestChangeType.values) { assert(expectedNames.contains(prChangeType.name)); } expect(PullRequestChangeType.values.length, 2); }); }
cocoon/auto_submit/test/model/pull_request_change_type.dart/0
{'file_path': 'cocoon/auto_submit/test/model/pull_request_change_type.dart', 'repo_id': 'cocoon', 'token_count': 185}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:math'; import 'package:auto_submit/request_handling/pubsub.dart'; import 'package:googleapis/pubsub/v1.dart'; class FakePubSub extends PubSub { List<dynamic> messagesQueue = <dynamic>[]; // The iteration of `pull` API calls. int iteration = -1; // Number of messages in each Pub/Sub pull call. This mocks the API // returning random number of messages each time. int messageSize = 2; @override Future<void> publish(String topicName, dynamic json) async { final String messageData = jsonEncode(json); final List<int> messageBytes = utf8.encode(messageData); final String messageBase64 = base64Encode(messageBytes); messagesQueue.add(messageBase64); } @override Future<PullResponse> pull(String subscription, int maxMessages) async { // The list will be empty if there are no more messages available in the backlog. final List<ReceivedMessage> receivedMessages = <ReceivedMessage>[]; iteration++; if (messagesQueue.isNotEmpty) { int i = iteration * messageSize; // Returns only allowed max number of messages. The number should not be greater than // `maxMessages`, the available messages, and the number allowed in each call. The // last number is to mock real `pull` API call. while (i < min(min(maxMessages, messagesQueue.length), (iteration + 1) * messageSize)) { receivedMessages.add( ReceivedMessage( message: PubsubMessage(data: messagesQueue[i] as String, messageId: '$i'), ackId: 'ackId_$i', ), ); i++; } return PullResponse(receivedMessages: receivedMessages); } return PullResponse(receivedMessages: receivedMessages); } @override Future<void> acknowledge(String subscription, String ackId) async { if (messagesQueue.isNotEmpty) { messagesQueue.removeAt(messagesQueue.length - 1); } } }
cocoon/auto_submit/test/src/request_handling/fake_pubsub.dart/0
{'file_path': 'cocoon/auto_submit/test/src/request_handling/fake_pubsub.dart', 'repo_id': 'cocoon', 'token_count': 707}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const String noStatusInCommitJson = ''' { "repository": { "pullRequest": { "author": { "login": "author1" }, "authorAssociation": "MEMBER", "id": "PR_kwDOA8VHis43rs4_", "title": "[dependabot] Remove human reviewers", "commits": { "nodes":[ { "commit": { "abbreviatedOid": "4009ecc", "oid": "4009ecc0b6dbf5cb19cb97472147063e7368ec10", "committedDate": "2022-05-11T22:35:02Z", "pushedDate": "2022-05-11T22:35:03Z", "status": { "contexts":[ ] } } } ] }, "reviews": { "nodes": [ { "author": { "login": "keyonghan" }, "authorAssociation": "MEMBER", "state": "APPROVED" } ] } } } } '''; const String nullStatusCommitRepositoryJson = ''' { "repository": { "pullRequest": { "author": { "login": "author1" }, "authorAssociation": "MEMBER", "id": "PR_kwDOA8VHis43rs4_", "title": "[dependabot] Remove human reviewers", "commits": { "nodes":[ { "commit": { "abbreviatedOid": "4009ecc", "oid": "4009ecc0b6dbf5cb19cb97472147063e7368ec10", "committedDate": "2022-05-11T22:35:02Z", "pushedDate": "2022-05-11T22:35:03Z", "status": null } } ] }, "reviews": { "nodes": [ { "author": { "login": "keyonghan" }, "authorAssociation": "MEMBER", "state": "APPROVED" } ] } } } } '''; const String nonNullStatusSUCCESSCommitRepositoryJson = ''' { "repository": { "pullRequest": { "author": { "login": "author1" }, "authorAssociation": "MEMBER", "id": "PR_kwDOA8VHis43rs4_", "title": "[dependabot] Remove human reviewers", "commits": { "nodes":[ { "commit": { "abbreviatedOid": "4009ecc", "oid": "4009ecc0b6dbf5cb19cb97472147063e7368ec10", "committedDate": "2022-05-11T22:35:02Z", "pushedDate": "2022-05-11T22:35:03Z", "status": { "contexts":[ { "context":"tree-status", "state":"SUCCESS", "targetUrl":"https://ci.example.com/1000/output" } ] } } } ] }, "reviews": { "nodes": [ { "author": { "login": "keyonghan" }, "authorAssociation": "MEMBER", "state": "APPROVED" } ] } } } } '''; const String nonNullStatusFAILURECommitRepositoryJson = ''' { "repository": { "pullRequest": { "author": { "login": "author1" }, "authorAssociation": "MEMBER", "id": "PR_kwDOA8VHis43rs4_", "title": "[dependabot] Remove human reviewers", "commits": { "nodes":[ { "commit": { "abbreviatedOid": "4009ecc", "oid": "4009ecc0b6dbf5cb19cb97472147063e7368ec10", "committedDate": "2022-05-11T22:35:02Z", "pushedDate": "2022-05-11T22:35:03Z", "status": { "contexts":[ { "context":"tree-status", "state":"FAILURE", "targetUrl":"https://ci.example.com/1000/output" } ] } } } ] }, "reviews": { "nodes": [ { "author": { "login": "keyonghan" }, "authorAssociation": "MEMBER", "state": "APPROVED" } ] } } } } ''';
cocoon/auto_submit/test/validations/ci_successful_test_data.dart/0
{'file_path': 'cocoon/auto_submit/test/validations/ci_successful_test_data.dart', 'repo_id': 'cocoon', 'token_count': 2921}
name: license_checks description: Script to check licenses. environment: sdk: ">=2.18.0 <4.0.0" dependencies: path: 1.9.0 platform: 3.1.4 dev_dependencies: mockito: 5.4.4 test_api: 0.7.0
cocoon/licenses/pubspec.yaml/0
{'file_path': 'cocoon/licenses/pubspec.yaml', 'repo_id': 'cocoon', 'token_count': 89}
// // Generated code. Do not modify. // source: go.chromium.org/luci/common/proto/structmask/structmask.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides, camel_case_types // ignore_for_file: constant_identifier_names, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_final_fields // ignore_for_file: unnecessary_import, unnecessary_this, unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use structMaskDescriptor instead') const StructMask$json = { '1': 'StructMask', '2': [ {'1': 'path', '3': 1, '4': 3, '5': 9, '10': 'path'}, ], }; /// Descriptor for `StructMask`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List structMaskDescriptor = $convert.base64Decode('CgpTdHJ1Y3RNYXNrEhIKBHBhdGgYASADKAlSBHBhdGg=');
cocoon/packages/buildbucket-dart/lib/src/generated/go.chromium.org/luci/common/proto/structmask/structmask.pbjson.dart/0
{'file_path': 'cocoon/packages/buildbucket-dart/lib/src/generated/go.chromium.org/luci/common/proto/structmask/structmask.pbjson.dart', 'repo_id': 'cocoon', 'token_count': 349}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'visitors.dart'; abstract class Spec { R accept<R>(SpecVisitor<R> visitor, [R context]); } /// Returns a generic [Spec] that is lazily generated when visited. Spec lazySpec(Spec Function() generate) => _LazySpec(generate); class _LazySpec implements Spec { final Spec Function() generate; const _LazySpec(this.generate); @override R accept<R>(SpecVisitor<R> visitor, [R context]) { return generate().accept(visitor, context); } }
code_builder/lib/src/base.dart/0
{'file_path': 'code_builder/lib/src/base.dart', 'repo_id': 'code_builder', 'token_count': 204}
name: code_builder version: 3.1.3 description: A fluent API for generating Dart code author: Dart Team <misc@dartlang.org> homepage: https://github.com/dart-lang/code_builder environment: sdk: '>=2.0.0 <3.0.0' dependencies: built_collection: '>=3.0.0 <5.0.0' built_value: ^6.0.0 matcher: ^0.12.0 meta: ^1.0.5 dev_dependencies: build: ^0.12.0 build_runner: ^0.10.0 built_value_generator: ^6.0.0 dart_style: ^1.0.0 source_gen: ^0.9.0 test: ^1.3.0
code_builder/pubspec.yaml/0
{'file_path': 'code_builder/pubspec.yaml', 'repo_id': 'code_builder', 'token_count': 218}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:googleapis/youtube/v3.dart'; import 'package:provider/provider.dart'; import 'app_state.dart'; class Playlists extends StatelessWidget { const Playlists({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('FlutterDev Playlists'), ), body: Consumer<FlutterDevPlaylists>( builder: (context, flutterDev, child) { final playlists = flutterDev.playlists; if (playlists.isEmpty) { return const Center( child: CircularProgressIndicator(), ); } return _PlaylistsListView(items: playlists); }, ), ); } } class _PlaylistsListView extends StatelessWidget { const _PlaylistsListView({required this.items}); final List<Playlist> items; @override Widget build(BuildContext context) { return ListView.builder( itemCount: items.length, itemBuilder: (context, index) { var playlist = items[index]; return Padding( padding: const EdgeInsets.all(8.0), child: ListTile( leading: Image.network( playlist.snippet!.thumbnails!.default_!.url!, ), title: Text(playlist.snippet!.title!), subtitle: Text( playlist.snippet!.description!, ), onTap: () { context.go( Uri( path: '/playlist/${playlist.id}', queryParameters: <String, String>{ 'title': playlist.snippet!.title! }, ).toString(), ); }, ), ); }, ); } }
codelabs/adaptive_app/step_04/lib/src/playlists.dart/0
{'file_path': 'codelabs/adaptive_app/step_04/lib/src/playlists.dart', 'repo_id': 'codelabs', 'token_count': 920}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flex_color_scheme/flex_color_scheme.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:googleapis_auth/googleapis_auth.dart'; import 'package:provider/provider.dart'; import 'src/adaptive_login.dart'; import 'src/adaptive_playlists.dart'; import 'src/app_state.dart'; import 'src/playlist_details.dart'; // From https://developers.google.com/youtube/v3/guides/auth/installed-apps#identify-access-scopes final scopes = [ 'https://www.googleapis.com/auth/youtube.readonly', ]; // TODO: Replace with your Client ID and Client Secret for Desktop configuration final clientId = ClientId( 'TODO-Client-ID.apps.googleusercontent.com', 'TODO-Client-secret', ); final _router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (context, state) { return const AdaptivePlaylists(); }, redirect: (context, state) { if (!context.read<AuthedUserPlaylists>().isLoggedIn) { return '/login'; } else { return null; } }, routes: <RouteBase>[ GoRoute( path: 'login', builder: (context, state) { return AdaptiveLogin( clientId: clientId, scopes: scopes, loginButtonChild: const Text('Login to YouTube'), ); }, ), GoRoute( path: 'playlist/:id', builder: (context, state) { final title = state.uri.queryParameters['title']!; final id = state.pathParameters['id']!; return Scaffold( appBar: AppBar(title: Text(title)), body: PlaylistDetails( playlistId: id, playlistName: title, ), ); }, ), ], ), ], ); void main() { runApp(ChangeNotifierProvider<AuthedUserPlaylists>( create: (context) => AuthedUserPlaylists(), child: const PlaylistsApp(), )); } class PlaylistsApp extends StatelessWidget { const PlaylistsApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Your Playlists', theme: FlexColorScheme.light( scheme: FlexScheme.red, useMaterial3: true, ).toTheme, darkTheme: FlexColorScheme.dark( scheme: FlexScheme.red, useMaterial3: true, ).toTheme, themeMode: ThemeMode.dark, // Or ThemeMode.System if you'd prefer debugShowCheckedModeBanner: false, routerConfig: _router, ); } }
codelabs/adaptive_app/step_07/lib/main.dart/0
{'file_path': 'codelabs/adaptive_app/step_07/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 1196}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. class Attachment { const Attachment({ required this.url, }); final String url; } class Email { const Email({ required this.sender, required this.recipients, required this.subject, required this.content, this.replies = 0, this.attachments = const [], }); final User sender; final List<User> recipients; final String subject; final String content; final List<Attachment> attachments; final double replies; } class Name { const Name({ required this.first, required this.last, }); final String first; final String last; String get fullName => '$first $last'; } class User { const User({ required this.name, required this.avatarUrl, required this.lastActive, }); final Name name; final String avatarUrl; final DateTime lastActive; }
codelabs/animated-responsive-layout/step_06/lib/models/models.dart/0
{'file_path': 'codelabs/animated-responsive-layout/step_06/lib/models/models.dart', 'repo_id': 'codelabs', 'token_count': 317}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../../shared/classes/classes.dart'; import '../../../shared/views/views.dart'; class ArtistNews extends StatelessWidget { const ArtistNews({super.key, required this.artist}); final Artist artist; @override Widget build(BuildContext context) { return Column( children: [ for (final article in artist.news) Clickable( child: Padding( padding: const EdgeInsets.all(8.0), child: ImageCard( clickable: true, title: article.title, subtitle: article.author, details: article.blurb, image: article.image.image.toString(), ), ), onTap: () { launchUrl(Uri.parse('https://docs.flutter.dev')); }, ), ], ); } }
codelabs/boring_to_beautiful/final/lib/src/features/artists/view/artist_news.dart/0
{'file_path': 'codelabs/boring_to_beautiful/final/lib/src/features/artists/view/artist_news.dart', 'repo_id': 'codelabs', 'token_count': 493}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../classes/classes.dart'; import '../playback/bloc/bloc.dart'; import '../views/views.dart'; /// Renders the child widget when not hovered and a Play button when hovered. class HoverableSongPlayButton extends StatelessWidget { const HoverableSongPlayButton({ super.key, required this.song, required this.child, this.size = const Size(50, 50), this.hoverMode = HoverMode.replace, }); final Widget child; final Size size; final Song song; final HoverMode hoverMode; @override Widget build(BuildContext context) { return HoverToggle( hoverChild: Center( child: GestureDetector( child: const Icon(Icons.play_arrow), onTap: () => BlocProvider.of<PlaybackBloc>(context).add( PlaybackEvent.changeSong(song), ), ), ), mode: hoverMode, size: size, child: child, ); } }
codelabs/boring_to_beautiful/final/lib/src/shared/views/hoverable_song_play_button.dart/0
{'file_path': 'codelabs/boring_to_beautiful/final/lib/src/shared/views/hoverable_song_play_button.dart', 'repo_id': 'codelabs', 'token_count': 431}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../../shared/views/views.dart'; class HomeHighlight extends StatelessWidget { const HomeHighlight({super.key}); @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.all(2), // Modify this line child: Clickable( child: SizedBox( height: 275, child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( 'assets/images/news/concert.jpeg', fit: BoxFit.cover, ), ), ), onTap: () => launchUrl(Uri.parse('https://docs.flutter.dev')), ), ), ), ], ); } }
codelabs/boring_to_beautiful/step_01/lib/src/features/home/view/home_highlight.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/features/home/view/home_highlight.dart', 'repo_id': 'codelabs', 'token_count': 529}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import './classes.dart'; class RankedSong extends Song { final int ranking; const RankedSong(this.ranking, String title, Artist artist, Duration length, MyArtistImage image) : super(title, artist, length, image); }
codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/ranked_song.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/ranked_song.dart', 'repo_id': 'codelabs', 'token_count': 114}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class AdaptiveTable<T> extends StatelessWidget { const AdaptiveTable({ super.key, required this.items, required this.itemBuilder, required this.rowBuilder, required this.columns, this.breakpoint = 600, }); final List<T> items; final Widget Function(T item, int index) itemBuilder; final DataRow Function(T item, int index) rowBuilder; final List<DataColumn> columns; final double breakpoint; @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, dimens) { if (dimens.maxWidth >= breakpoint) { return DataTable( columns: columns, rows: [ for (var i = 0; i < items.length; i++) rowBuilder(items[i], i), ], ); } return ListView.builder( shrinkWrap: true, itemCount: items.length, itemBuilder: (context, index) { final item = items[index]; return itemBuilder(item, index); }, ); }, ); } }
codelabs/boring_to_beautiful/step_01/lib/src/shared/views/adaptive_table.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/views/adaptive_table.dart', 'repo_id': 'codelabs', 'token_count': 512}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export 'adaptive_table.dart'; export 'article_content.dart'; export 'bottom_bar.dart'; export 'brightness_toggle.dart'; export 'center_row.dart'; export 'clickable.dart'; export 'events.dart'; export 'hover_toggle.dart'; export 'hoverable_song_play_button.dart'; export 'image_card.dart'; export 'image_tile.dart'; export 'play_pause_listener.dart'; export 'root_layout.dart'; export 'sidebar.dart';
codelabs/boring_to_beautiful/step_01/lib/src/shared/views/views.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/views/views.dart', 'repo_id': 'codelabs', 'token_count': 188}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../../shared/views/views.dart'; class HomeHighlight extends StatelessWidget { const HomeHighlight({super.key}); @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.all(15), child: Clickable( child: SizedBox( height: 275, child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.asset( 'assets/images/news/concert.jpeg', fit: BoxFit.cover, ), ), ), onTap: () => launchUrl(Uri.parse('https://docs.flutter.dev')), ), ), ), ], ); } }
codelabs/boring_to_beautiful/step_07/lib/src/features/home/view/home_highlight.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_07/lib/src/features/home/view/home_highlight.dart', 'repo_id': 'codelabs', 'token_count': 524}
# Align with DartPad's analysis rules: # https://github.com/dart-lang/dart-services/blob/master/lib/src/project_creator.dart#L119 include: package:flutter_lints/flutter.yaml linter: rules: avoid_print: false prefer_const_constructors: false use_build_context_synchronously: false use_key_in_widget_constructors: false use_super_parameters: true
codelabs/dartpad_codelabs/analysis_options.yaml/0
{'file_path': 'codelabs/dartpad_codelabs/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 137}
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors import 'package:flutter/material.dart'; // Runs an app that displays the `CustomButton` void main() { runApp( MaterialApp( home: Scaffold( body: Center( child: CustomButton(), // Display the CustomButton ), ), ), ); } class CustomButton extends StatelessWidget { @override Widget build(BuildContext context) { return GestureDetector( onTap: () { print('Handle Tap/Click'); }, onLongPress: () { print('Handle LongPress'); }, child: Container( padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(10), ), child: Text("Press me!"), ), ); } }
codelabs/dartpad_codelabs/src/custom_button/step_02/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/custom_button/step_02/solution.dart', 'repo_id': 'codelabs', 'token_count': 363}
void main() { int? a; a = null; print('a is $a.'); }
codelabs/dartpad_codelabs/src/null_safety_workshop/step_02/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_02/solution.dart', 'repo_id': 'codelabs', 'token_count': 29}
int _computeValue() { print('In _computeValue...'); return 3; } class CachedValueProvider { final _cache = _computeValue(); int get value => _cache; } void main() { print('Calling constructor...'); var provider = CachedValueProvider(); print('Getting value...'); print('The value is ${provider.value}!'); }
codelabs/dartpad_codelabs/src/null_safety_workshop/step_13/snippet.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_13/snippet.dart', 'repo_id': 'codelabs', 'token_count': 105}
# Run with `flutter pub run ffigen --config ffigen.yaml`. name: FfigenAppBindings description: | Bindings for `src/ffigen_app.h`. Regenerate bindings with `flutter pub run ffigen --config ffigen.yaml`. output: 'lib/ffigen_app_bindings_generated.dart' headers: entry-points: - 'src/ffigen_app.h' include-directives: - 'src/ffigen_app.h' preamble: | // ignore_for_file: always_specify_types // ignore_for_file: camel_case_types // ignore_for_file: non_constant_identifier_names comments: style: any length: full
codelabs/ffigen_codelab/step_03/ffigen.yaml/0
{'file_path': 'codelabs/ffigen_codelab/step_03/ffigen.yaml', 'repo_id': 'codelabs', 'token_count': 203}
// ignore_for_file: always_specify_types // ignore_for_file: camel_case_types // ignore_for_file: non_constant_identifier_names // AUTO GENERATED FILE, DO NOT EDIT. // // Generated by `package:ffigen`. // ignore_for_file: type=lint import 'dart:ffi' as ffi; /// Bindings for `src/duktape.h`. /// /// Regenerate bindings with `flutter pub run ffigen --config ffigen.yaml`. /// class DuktapeBindings { /// Holds the symbol lookup function. final ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName) _lookup; /// The symbols are looked up in [dynamicLibrary]. DuktapeBindings(ffi.DynamicLibrary dynamicLibrary) : _lookup = dynamicLibrary.lookup; /// The symbols are looked up with [lookup]. DuktapeBindings.fromLookup( ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName) lookup) : _lookup = lookup; /// Context management ffi.Pointer<duk_context> duk_create_heap( duk_alloc_function alloc_func, duk_realloc_function realloc_func, duk_free_function free_func, ffi.Pointer<ffi.Void> heap_udata, duk_fatal_function fatal_handler, ) { return _duk_create_heap( alloc_func, realloc_func, free_func, heap_udata, fatal_handler, ); } late final _duk_create_heapPtr = _lookup< ffi.NativeFunction< ffi.Pointer<duk_context> Function( duk_alloc_function, duk_realloc_function, duk_free_function, ffi.Pointer<ffi.Void>, duk_fatal_function)>>('duk_create_heap'); late final _duk_create_heap = _duk_create_heapPtr.asFunction< ffi.Pointer<duk_context> Function( duk_alloc_function, duk_realloc_function, duk_free_function, ffi.Pointer<ffi.Void>, duk_fatal_function)>(); void duk_destroy_heap( ffi.Pointer<duk_context> ctx, ) { return _duk_destroy_heap( ctx, ); } late final _duk_destroy_heapPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_destroy_heap'); late final _duk_destroy_heap = _duk_destroy_heapPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_suspend( ffi.Pointer<duk_context> ctx, ffi.Pointer<duk_thread_state> state, ) { return _duk_suspend( ctx, state, ); } late final _duk_suspendPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_thread_state>)>>('duk_suspend'); late final _duk_suspend = _duk_suspendPtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_thread_state>)>(); void duk_resume( ffi.Pointer<duk_context> ctx, ffi.Pointer<duk_thread_state> state, ) { return _duk_resume( ctx, state, ); } late final _duk_resumePtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_thread_state>)>>('duk_resume'); late final _duk_resume = _duk_resumePtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_thread_state>)>(); /// Memory management /// /// Raw functions have no side effects (cannot trigger GC). ffi.Pointer<ffi.Void> duk_alloc_raw( ffi.Pointer<duk_context> ctx, int size, ) { return _duk_alloc_raw( ctx, size, ); } late final _duk_alloc_rawPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_size_t)>>('duk_alloc_raw'); late final _duk_alloc_raw = _duk_alloc_rawPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); void duk_free_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_free_raw( ctx, ptr, ); } late final _duk_free_rawPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_free_raw'); late final _duk_free_raw = _duk_free_rawPtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); ffi.Pointer<ffi.Void> duk_realloc_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, int size, ) { return _duk_realloc_raw( ctx, ptr, size, ); } late final _duk_realloc_rawPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_realloc_raw'); late final _duk_realloc_raw = _duk_realloc_rawPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>, int)>(); ffi.Pointer<ffi.Void> duk_alloc( ffi.Pointer<duk_context> ctx, int size, ) { return _duk_alloc( ctx, size, ); } late final _duk_allocPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_size_t)>>('duk_alloc'); late final _duk_alloc = _duk_allocPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); void duk_free( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_free( ctx, ptr, ); } late final _duk_freePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_free'); late final _duk_free = _duk_freePtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); ffi.Pointer<ffi.Void> duk_realloc( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, int size, ) { return _duk_realloc( ctx, ptr, size, ); } late final _duk_reallocPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_realloc'); late final _duk_realloc = _duk_reallocPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>, int)>(); void duk_get_memory_functions( ffi.Pointer<duk_context> ctx, ffi.Pointer<duk_memory_functions> out_funcs, ) { return _duk_get_memory_functions( ctx, out_funcs, ); } late final _duk_get_memory_functionsPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_memory_functions>)>>('duk_get_memory_functions'); late final _duk_get_memory_functions = _duk_get_memory_functionsPtr.asFunction< void Function( ffi.Pointer<duk_context>, ffi.Pointer<duk_memory_functions>)>(); void duk_gc( ffi.Pointer<duk_context> ctx, int flags, ) { return _duk_gc( ctx, flags, ); } late final _duk_gcPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_uint_t)>>('duk_gc'); late final _duk_gc = _duk_gcPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_throw_raw( ffi.Pointer<duk_context> ctx, ) { return _duk_throw_raw( ctx, ); } late final _duk_throw_rawPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_throw_raw'); late final _duk_throw_raw = _duk_throw_rawPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_fatal_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> err_msg, ) { return _duk_fatal_raw( ctx, err_msg, ); } late final _duk_fatal_rawPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>>('duk_fatal_raw'); late final _duk_fatal_raw = _duk_fatal_rawPtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>(); void duk_error_raw( ffi.Pointer<duk_context> ctx, int err_code, ffi.Pointer<ffi.Char> filename, int line, ffi.Pointer<ffi.Char> fmt, ) { return _duk_error_raw( ctx, err_code, filename, line, fmt, ); } late final _duk_error_rawPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_errcode_t, ffi.Pointer<ffi.Char>, duk_int_t, ffi.Pointer<ffi.Char>)>>('duk_error_raw'); late final _duk_error_raw = _duk_error_rawPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int, ffi.Pointer<ffi.Char>)>(); void duk_error_va_raw( ffi.Pointer<duk_context> ctx, int err_code, ffi.Pointer<ffi.Char> filename, int line, ffi.Pointer<ffi.Char> fmt, va_list ap, ) { return _duk_error_va_raw( ctx, err_code, filename, line, fmt, ap, ); } late final _duk_error_va_rawPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_errcode_t, ffi.Pointer<ffi.Char>, duk_int_t, ffi.Pointer<ffi.Char>, va_list)>>('duk_error_va_raw'); late final _duk_error_va_raw = _duk_error_va_rawPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int, ffi.Pointer<ffi.Char>, va_list)>(); /// Other state related functions int duk_is_strict_call( ffi.Pointer<duk_context> ctx, ) { return _duk_is_strict_call( ctx, ); } late final _duk_is_strict_callPtr = _lookup< ffi.NativeFunction<duk_bool_t Function(ffi.Pointer<duk_context>)>>( 'duk_is_strict_call'); late final _duk_is_strict_call = _duk_is_strict_callPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_is_constructor_call( ffi.Pointer<duk_context> ctx, ) { return _duk_is_constructor_call( ctx, ); } late final _duk_is_constructor_callPtr = _lookup< ffi.NativeFunction<duk_bool_t Function(ffi.Pointer<duk_context>)>>( 'duk_is_constructor_call'); late final _duk_is_constructor_call = _duk_is_constructor_callPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); /// Stack management int duk_normalize_index( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_normalize_index( ctx, idx, ); } late final _duk_normalize_indexPtr = _lookup< ffi.NativeFunction< duk_idx_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_normalize_index'); late final _duk_normalize_index = _duk_normalize_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_require_normalize_index( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_normalize_index( ctx, idx, ); } late final _duk_require_normalize_indexPtr = _lookup< ffi.NativeFunction< duk_idx_t Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_normalize_index'); late final _duk_require_normalize_index = _duk_require_normalize_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_valid_index( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_valid_index( ctx, idx, ); } late final _duk_is_valid_indexPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_valid_index'); late final _duk_is_valid_index = _duk_is_valid_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_require_valid_index( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_valid_index( ctx, idx, ); } late final _duk_require_valid_indexPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_valid_index'); late final _duk_require_valid_index = _duk_require_valid_indexPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_get_top( ffi.Pointer<duk_context> ctx, ) { return _duk_get_top( ctx, ); } late final _duk_get_topPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_get_top'); late final _duk_get_top = _duk_get_topPtr.asFunction<int Function(ffi.Pointer<duk_context>)>(); void duk_set_top( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_set_top( ctx, idx, ); } late final _duk_set_topPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_set_top'); late final _duk_set_top = _duk_set_topPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_get_top_index( ffi.Pointer<duk_context> ctx, ) { return _duk_get_top_index( ctx, ); } late final _duk_get_top_indexPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_get_top_index'); late final _duk_get_top_index = _duk_get_top_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_require_top_index( ffi.Pointer<duk_context> ctx, ) { return _duk_require_top_index( ctx, ); } late final _duk_require_top_indexPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_require_top_index'); late final _duk_require_top_index = _duk_require_top_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); /// Although extra/top could be an unsigned type here, using a signed type /// makes the API more robust to calling code calculation errors or corner /// cases (where caller might occasionally come up with negative values). /// Negative values are treated as zero, which is better than casting them /// to a large unsigned number. (This principle is used elsewhere in the /// API too.) int duk_check_stack( ffi.Pointer<duk_context> ctx, int extra, ) { return _duk_check_stack( ctx, extra, ); } late final _duk_check_stackPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_check_stack'); late final _duk_check_stack = _duk_check_stackPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_require_stack( ffi.Pointer<duk_context> ctx, int extra, ) { return _duk_require_stack( ctx, extra, ); } late final _duk_require_stackPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_stack'); late final _duk_require_stack = _duk_require_stackPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_check_stack_top( ffi.Pointer<duk_context> ctx, int top, ) { return _duk_check_stack_top( ctx, top, ); } late final _duk_check_stack_topPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_check_stack_top'); late final _duk_check_stack_top = _duk_check_stack_topPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_require_stack_top( ffi.Pointer<duk_context> ctx, int top, ) { return _duk_require_stack_top( ctx, top, ); } late final _duk_require_stack_topPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_stack_top'); late final _duk_require_stack_top = _duk_require_stack_topPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); /// Stack manipulation (other than push/pop) void duk_swap( ffi.Pointer<duk_context> ctx, int idx1, int idx2, ) { return _duk_swap( ctx, idx1, idx2, ); } late final _duk_swapPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_swap'); late final _duk_swap = _duk_swapPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); void duk_swap_top( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_swap_top( ctx, idx, ); } late final _duk_swap_topPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_swap_top'); late final _duk_swap_top = _duk_swap_topPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_dup( ffi.Pointer<duk_context> ctx, int from_idx, ) { return _duk_dup( ctx, from_idx, ); } late final _duk_dupPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_dup'); late final _duk_dup = _duk_dupPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_dup_top( ffi.Pointer<duk_context> ctx, ) { return _duk_dup_top( ctx, ); } late final _duk_dup_topPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_dup_top'); late final _duk_dup_top = _duk_dup_topPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_insert( ffi.Pointer<duk_context> ctx, int to_idx, ) { return _duk_insert( ctx, to_idx, ); } late final _duk_insertPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_insert'); late final _duk_insert = _duk_insertPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_pull( ffi.Pointer<duk_context> ctx, int from_idx, ) { return _duk_pull( ctx, from_idx, ); } late final _duk_pullPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_pull'); late final _duk_pull = _duk_pullPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_replace( ffi.Pointer<duk_context> ctx, int to_idx, ) { return _duk_replace( ctx, to_idx, ); } late final _duk_replacePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_replace'); late final _duk_replace = _duk_replacePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_copy( ffi.Pointer<duk_context> ctx, int from_idx, int to_idx, ) { return _duk_copy( ctx, from_idx, to_idx, ); } late final _duk_copyPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_copy'); late final _duk_copy = _duk_copyPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); void duk_remove( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_remove( ctx, idx, ); } late final _duk_removePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_remove'); late final _duk_remove = _duk_removePtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_xcopymove_raw( ffi.Pointer<duk_context> to_ctx, ffi.Pointer<duk_context> from_ctx, int count, int is_copy, ) { return _duk_xcopymove_raw( to_ctx, from_ctx, count, is_copy, ); } late final _duk_xcopymove_rawPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_context>, duk_idx_t, duk_bool_t)>>('duk_xcopymove_raw'); late final _duk_xcopymove_raw = _duk_xcopymove_rawPtr.asFunction< void Function( ffi.Pointer<duk_context>, ffi.Pointer<duk_context>, int, int)>(); /// Push operations /// /// Push functions return the absolute (relative to bottom of frame) /// position of the pushed value for convenience. /// /// Note: duk_dup() is technically a push. void duk_push_undefined( ffi.Pointer<duk_context> ctx, ) { return _duk_push_undefined( ctx, ); } late final _duk_push_undefinedPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_undefined'); late final _duk_push_undefined = _duk_push_undefinedPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_null( ffi.Pointer<duk_context> ctx, ) { return _duk_push_null( ctx, ); } late final _duk_push_nullPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_null'); late final _duk_push_null = _duk_push_nullPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_boolean( ffi.Pointer<duk_context> ctx, int val, ) { return _duk_push_boolean( ctx, val, ); } late final _duk_push_booleanPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_bool_t)>>('duk_push_boolean'); late final _duk_push_boolean = _duk_push_booleanPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_push_true( ffi.Pointer<duk_context> ctx, ) { return _duk_push_true( ctx, ); } late final _duk_push_truePtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_true'); late final _duk_push_true = _duk_push_truePtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_false( ffi.Pointer<duk_context> ctx, ) { return _duk_push_false( ctx, ); } late final _duk_push_falsePtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_false'); late final _duk_push_false = _duk_push_falsePtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_number( ffi.Pointer<duk_context> ctx, double val, ) { return _duk_push_number( ctx, val, ); } late final _duk_push_numberPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_double_t)>>('duk_push_number'); late final _duk_push_number = _duk_push_numberPtr .asFunction<void Function(ffi.Pointer<duk_context>, double)>(); void duk_push_nan( ffi.Pointer<duk_context> ctx, ) { return _duk_push_nan( ctx, ); } late final _duk_push_nanPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_nan'); late final _duk_push_nan = _duk_push_nanPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_int( ffi.Pointer<duk_context> ctx, int val, ) { return _duk_push_int( ctx, val, ); } late final _duk_push_intPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_int_t)>>('duk_push_int'); late final _duk_push_int = _duk_push_intPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_push_uint( ffi.Pointer<duk_context> ctx, int val, ) { return _duk_push_uint( ctx, val, ); } late final _duk_push_uintPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_uint_t)>>('duk_push_uint'); late final _duk_push_uint = _duk_push_uintPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_push_string( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> str, ) { return _duk_push_string( ctx, str, ); } late final _duk_push_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>>('duk_push_string'); late final _duk_push_string = _duk_push_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>(); ffi.Pointer<ffi.Char> duk_push_lstring( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> str, int len, ) { return _duk_push_lstring( ctx, str, len, ); } late final _duk_push_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_push_lstring'); late final _duk_push_lstring = _duk_push_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); void duk_push_pointer( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> p, ) { return _duk_push_pointer( ctx, p, ); } late final _duk_push_pointerPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_push_pointer'); late final _duk_push_pointer = _duk_push_pointerPtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); ffi.Pointer<ffi.Char> duk_push_sprintf( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> fmt, ) { return _duk_push_sprintf( ctx, fmt, ); } late final _duk_push_sprintfPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>>('duk_push_sprintf'); late final _duk_push_sprintf = _duk_push_sprintfPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>(); ffi.Pointer<ffi.Char> duk_push_vsprintf( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> fmt, va_list ap, ) { return _duk_push_vsprintf( ctx, fmt, ap, ); } late final _duk_push_vsprintfPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, va_list)>>('duk_push_vsprintf'); late final _duk_push_vsprintf = _duk_push_vsprintfPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, va_list)>(); ffi.Pointer<ffi.Char> duk_push_literal_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> str, int len, ) { return _duk_push_literal_raw( ctx, str, len, ); } late final _duk_push_literal_rawPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_push_literal_raw'); late final _duk_push_literal_raw = _duk_push_literal_rawPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); void duk_push_this( ffi.Pointer<duk_context> ctx, ) { return _duk_push_this( ctx, ); } late final _duk_push_thisPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_this'); late final _duk_push_this = _duk_push_thisPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_new_target( ffi.Pointer<duk_context> ctx, ) { return _duk_push_new_target( ctx, ); } late final _duk_push_new_targetPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_new_target'); late final _duk_push_new_target = _duk_push_new_targetPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_current_function( ffi.Pointer<duk_context> ctx, ) { return _duk_push_current_function( ctx, ); } late final _duk_push_current_functionPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_current_function'); late final _duk_push_current_function = _duk_push_current_functionPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_current_thread( ffi.Pointer<duk_context> ctx, ) { return _duk_push_current_thread( ctx, ); } late final _duk_push_current_threadPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_current_thread'); late final _duk_push_current_thread = _duk_push_current_threadPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_global_object( ffi.Pointer<duk_context> ctx, ) { return _duk_push_global_object( ctx, ); } late final _duk_push_global_objectPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_global_object'); late final _duk_push_global_object = _duk_push_global_objectPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_heap_stash( ffi.Pointer<duk_context> ctx, ) { return _duk_push_heap_stash( ctx, ); } late final _duk_push_heap_stashPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_heap_stash'); late final _duk_push_heap_stash = _duk_push_heap_stashPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_global_stash( ffi.Pointer<duk_context> ctx, ) { return _duk_push_global_stash( ctx, ); } late final _duk_push_global_stashPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_global_stash'); late final _duk_push_global_stash = _duk_push_global_stashPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_push_thread_stash( ffi.Pointer<duk_context> ctx, ffi.Pointer<duk_context> target_ctx, ) { return _duk_push_thread_stash( ctx, target_ctx, ); } late final _duk_push_thread_stashPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_context>)>>('duk_push_thread_stash'); late final _duk_push_thread_stash = _duk_push_thread_stashPtr.asFunction< void Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_context>)>(); int duk_push_object( ffi.Pointer<duk_context> ctx, ) { return _duk_push_object( ctx, ); } late final _duk_push_objectPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_push_object'); late final _duk_push_object = _duk_push_objectPtr.asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_push_bare_object( ffi.Pointer<duk_context> ctx, ) { return _duk_push_bare_object( ctx, ); } late final _duk_push_bare_objectPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_push_bare_object'); late final _duk_push_bare_object = _duk_push_bare_objectPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_push_array( ffi.Pointer<duk_context> ctx, ) { return _duk_push_array( ctx, ); } late final _duk_push_arrayPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_push_array'); late final _duk_push_array = _duk_push_arrayPtr.asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_push_bare_array( ffi.Pointer<duk_context> ctx, ) { return _duk_push_bare_array( ctx, ); } late final _duk_push_bare_arrayPtr = _lookup<ffi.NativeFunction<duk_idx_t Function(ffi.Pointer<duk_context>)>>( 'duk_push_bare_array'); late final _duk_push_bare_array = _duk_push_bare_arrayPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); int duk_push_c_function( ffi.Pointer<duk_context> ctx, duk_c_function func, int nargs, ) { return _duk_push_c_function( ctx, func, nargs, ); } late final _duk_push_c_functionPtr = _lookup< ffi.NativeFunction< duk_idx_t Function(ffi.Pointer<duk_context>, duk_c_function, duk_idx_t)>>('duk_push_c_function'); late final _duk_push_c_function = _duk_push_c_functionPtr.asFunction< int Function(ffi.Pointer<duk_context>, duk_c_function, int)>(); int duk_push_c_lightfunc( ffi.Pointer<duk_context> ctx, duk_c_function func, int nargs, int length, int magic, ) { return _duk_push_c_lightfunc( ctx, func, nargs, length, magic, ); } late final _duk_push_c_lightfuncPtr = _lookup< ffi.NativeFunction< duk_idx_t Function(ffi.Pointer<duk_context>, duk_c_function, duk_idx_t, duk_idx_t, duk_int_t)>>('duk_push_c_lightfunc'); late final _duk_push_c_lightfunc = _duk_push_c_lightfuncPtr.asFunction< int Function(ffi.Pointer<duk_context>, duk_c_function, int, int, int)>(); int duk_push_thread_raw( ffi.Pointer<duk_context> ctx, int flags, ) { return _duk_push_thread_raw( ctx, flags, ); } late final _duk_push_thread_rawPtr = _lookup< ffi.NativeFunction< duk_idx_t Function( ffi.Pointer<duk_context>, duk_uint_t)>>('duk_push_thread_raw'); late final _duk_push_thread_raw = _duk_push_thread_rawPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_push_proxy( ffi.Pointer<duk_context> ctx, int proxy_flags, ) { return _duk_push_proxy( ctx, proxy_flags, ); } late final _duk_push_proxyPtr = _lookup< ffi.NativeFunction< duk_idx_t Function( ffi.Pointer<duk_context>, duk_uint_t)>>('duk_push_proxy'); late final _duk_push_proxy = _duk_push_proxyPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_push_error_object_raw( ffi.Pointer<duk_context> ctx, int err_code, ffi.Pointer<ffi.Char> filename, int line, ffi.Pointer<ffi.Char> fmt, ) { return _duk_push_error_object_raw( ctx, err_code, filename, line, fmt, ); } late final _duk_push_error_object_rawPtr = _lookup< ffi.NativeFunction< duk_idx_t Function( ffi.Pointer<duk_context>, duk_errcode_t, ffi.Pointer<ffi.Char>, duk_int_t, ffi.Pointer<ffi.Char>)>>('duk_push_error_object_raw'); late final _duk_push_error_object_raw = _duk_push_error_object_rawPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int, ffi.Pointer<ffi.Char>)>(); int duk_push_error_object_va_raw( ffi.Pointer<duk_context> ctx, int err_code, ffi.Pointer<ffi.Char> filename, int line, ffi.Pointer<ffi.Char> fmt, va_list ap, ) { return _duk_push_error_object_va_raw( ctx, err_code, filename, line, fmt, ap, ); } late final _duk_push_error_object_va_rawPtr = _lookup< ffi.NativeFunction< duk_idx_t Function( ffi.Pointer<duk_context>, duk_errcode_t, ffi.Pointer<ffi.Char>, duk_int_t, ffi.Pointer<ffi.Char>, va_list)>>('duk_push_error_object_va_raw'); late final _duk_push_error_object_va_raw = _duk_push_error_object_va_rawPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int, ffi.Pointer<ffi.Char>, va_list)>(); ffi.Pointer<ffi.Void> duk_push_buffer_raw( ffi.Pointer<duk_context> ctx, int size, int flags, ) { return _duk_push_buffer_raw( ctx, size, flags, ); } late final _duk_push_buffer_rawPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_size_t, duk_small_uint_t)>>('duk_push_buffer_raw'); late final _duk_push_buffer_raw = _duk_push_buffer_rawPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, int)>(); void duk_push_buffer_object( ffi.Pointer<duk_context> ctx, int idx_buffer, int byte_offset, int byte_length, int flags, ) { return _duk_push_buffer_object( ctx, idx_buffer, byte_offset, byte_length, flags, ); } late final _duk_push_buffer_objectPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_size_t, duk_size_t, duk_uint_t)>>('duk_push_buffer_object'); late final _duk_push_buffer_object = _duk_push_buffer_objectPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, int, int, int)>(); int duk_push_heapptr( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_push_heapptr( ctx, ptr, ); } late final _duk_push_heapptrPtr = _lookup< ffi.NativeFunction< duk_idx_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_push_heapptr'); late final _duk_push_heapptr = _duk_push_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); /// Pop operations void duk_pop( ffi.Pointer<duk_context> ctx, ) { return _duk_pop( ctx, ); } late final _duk_popPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_pop'); late final _duk_pop = _duk_popPtr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_pop_n( ffi.Pointer<duk_context> ctx, int count, ) { return _duk_pop_n( ctx, count, ); } late final _duk_pop_nPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_pop_n'); late final _duk_pop_n = _duk_pop_nPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_pop_2( ffi.Pointer<duk_context> ctx, ) { return _duk_pop_2( ctx, ); } late final _duk_pop_2Ptr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_pop_2'); late final _duk_pop_2 = _duk_pop_2Ptr.asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_pop_3( ffi.Pointer<duk_context> ctx, ) { return _duk_pop_3( ctx, ); } late final _duk_pop_3Ptr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_pop_3'); late final _duk_pop_3 = _duk_pop_3Ptr.asFunction<void Function(ffi.Pointer<duk_context>)>(); /// Type checks /// /// duk_is_none(), which would indicate whether index it outside of stack, /// is not needed; duk_is_valid_index() gives the same information. int duk_get_type( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_type( ctx, idx, ); } late final _duk_get_typePtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_type'); late final _duk_get_type = _duk_get_typePtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_check_type( ffi.Pointer<duk_context> ctx, int idx, int type, ) { return _duk_check_type( ctx, idx, type, ); } late final _duk_check_typePtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_int_t)>>('duk_check_type'); late final _duk_check_type = _duk_check_typePtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_get_type_mask( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_type_mask( ctx, idx, ); } late final _duk_get_type_maskPtr = _lookup< ffi.NativeFunction< duk_uint_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_type_mask'); late final _duk_get_type_mask = _duk_get_type_maskPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_check_type_mask( ffi.Pointer<duk_context> ctx, int idx, int mask, ) { return _duk_check_type_mask( ctx, idx, mask, ); } late final _duk_check_type_maskPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_check_type_mask'); late final _duk_check_type_mask = _duk_check_type_maskPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_is_undefined( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_undefined( ctx, idx, ); } late final _duk_is_undefinedPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_undefined'); late final _duk_is_undefined = _duk_is_undefinedPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_null( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_null( ctx, idx, ); } late final _duk_is_nullPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_null'); late final _duk_is_null = _duk_is_nullPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_boolean( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_boolean( ctx, idx, ); } late final _duk_is_booleanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_boolean'); late final _duk_is_boolean = _duk_is_booleanPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_number( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_number( ctx, idx, ); } late final _duk_is_numberPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_number'); late final _duk_is_number = _duk_is_numberPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_nan( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_nan( ctx, idx, ); } late final _duk_is_nanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_nan'); late final _duk_is_nan = _duk_is_nanPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_string( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_string( ctx, idx, ); } late final _duk_is_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_string'); late final _duk_is_string = _duk_is_stringPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_object( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_object( ctx, idx, ); } late final _duk_is_objectPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_object'); late final _duk_is_object = _duk_is_objectPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_buffer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_buffer( ctx, idx, ); } late final _duk_is_bufferPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_buffer'); late final _duk_is_buffer = _duk_is_bufferPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_buffer_data( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_buffer_data( ctx, idx, ); } late final _duk_is_buffer_dataPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_buffer_data'); late final _duk_is_buffer_data = _duk_is_buffer_dataPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_pointer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_pointer( ctx, idx, ); } late final _duk_is_pointerPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_pointer'); late final _duk_is_pointer = _duk_is_pointerPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_lightfunc( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_lightfunc( ctx, idx, ); } late final _duk_is_lightfuncPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_lightfunc'); late final _duk_is_lightfunc = _duk_is_lightfuncPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_symbol( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_symbol( ctx, idx, ); } late final _duk_is_symbolPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_symbol'); late final _duk_is_symbol = _duk_is_symbolPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_array( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_array( ctx, idx, ); } late final _duk_is_arrayPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_array'); late final _duk_is_array = _duk_is_arrayPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_function( ctx, idx, ); } late final _duk_is_functionPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_function'); late final _duk_is_function = _duk_is_functionPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_c_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_c_function( ctx, idx, ); } late final _duk_is_c_functionPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_c_function'); late final _duk_is_c_function = _duk_is_c_functionPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_ecmascript_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_ecmascript_function( ctx, idx, ); } late final _duk_is_ecmascript_functionPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_ecmascript_function'); late final _duk_is_ecmascript_function = _duk_is_ecmascript_functionPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_bound_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_bound_function( ctx, idx, ); } late final _duk_is_bound_functionPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_bound_function'); late final _duk_is_bound_function = _duk_is_bound_functionPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_thread( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_thread( ctx, idx, ); } late final _duk_is_threadPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_thread'); late final _duk_is_thread = _duk_is_threadPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_constructable( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_constructable( ctx, idx, ); } late final _duk_is_constructablePtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_constructable'); late final _duk_is_constructable = _duk_is_constructablePtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_dynamic_buffer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_dynamic_buffer( ctx, idx, ); } late final _duk_is_dynamic_bufferPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_dynamic_buffer'); late final _duk_is_dynamic_buffer = _duk_is_dynamic_bufferPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_fixed_buffer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_fixed_buffer( ctx, idx, ); } late final _duk_is_fixed_bufferPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_fixed_buffer'); late final _duk_is_fixed_buffer = _duk_is_fixed_bufferPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_is_external_buffer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_is_external_buffer( ctx, idx, ); } late final _duk_is_external_bufferPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_is_external_buffer'); late final _duk_is_external_buffer = _duk_is_external_bufferPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_get_error_code( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_error_code( ctx, idx, ); } late final _duk_get_error_codePtr = _lookup< ffi.NativeFunction< duk_errcode_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_error_code'); late final _duk_get_error_code = _duk_get_error_codePtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); /// Get operations: no coercion, returns default value for invalid /// indices and invalid value types. /// /// duk_get_undefined() and duk_get_null() would be pointless and /// are not included. int duk_get_boolean( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_boolean( ctx, idx, ); } late final _duk_get_booleanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_boolean'); late final _duk_get_boolean = _duk_get_booleanPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); double duk_get_number( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_number( ctx, idx, ); } late final _duk_get_numberPtr = _lookup< ffi.NativeFunction< duk_double_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_number'); late final _duk_get_number = _duk_get_numberPtr .asFunction<double Function(ffi.Pointer<duk_context>, int)>(); int duk_get_int( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_int( ctx, idx, ); } late final _duk_get_intPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_int'); late final _duk_get_int = _duk_get_intPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_get_uint( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_uint( ctx, idx, ); } late final _duk_get_uintPtr = _lookup< ffi.NativeFunction< duk_uint_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_uint'); late final _duk_get_uint = _duk_get_uintPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_get_string( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_string( ctx, idx, ); } late final _duk_get_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_string'); late final _duk_get_string = _duk_get_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_get_lstring( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ) { return _duk_get_lstring( ctx, idx, out_len, ); } late final _duk_get_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_get_lstring'); late final _duk_get_lstring = _duk_get_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_get_buffer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ) { return _duk_get_buffer( ctx, idx, out_size, ); } late final _duk_get_bufferPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_get_buffer'); late final _duk_get_buffer = _duk_get_bufferPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_get_buffer_data( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ) { return _duk_get_buffer_data( ctx, idx, out_size, ); } late final _duk_get_buffer_dataPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_get_buffer_data'); late final _duk_get_buffer_data = _duk_get_buffer_dataPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_get_pointer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_pointer( ctx, idx, ); } late final _duk_get_pointerPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_pointer'); late final _duk_get_pointer = _duk_get_pointerPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); duk_c_function duk_get_c_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_c_function( ctx, idx, ); } late final _duk_get_c_functionPtr = _lookup< ffi.NativeFunction< duk_c_function Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_c_function'); late final _duk_get_c_function = _duk_get_c_functionPtr .asFunction<duk_c_function Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<duk_context> duk_get_context( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_context( ctx, idx, ); } late final _duk_get_contextPtr = _lookup< ffi.NativeFunction< ffi.Pointer<duk_context> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_context'); late final _duk_get_context = _duk_get_contextPtr.asFunction< ffi.Pointer<duk_context> Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Void> duk_get_heapptr( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_heapptr( ctx, idx, ); } late final _duk_get_heapptrPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_heapptr'); late final _duk_get_heapptr = _duk_get_heapptrPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); /// Get-with-explicit default operations: like get operations but with an /// explicit default value. int duk_get_boolean_default( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_get_boolean_default( ctx, idx, def_value, ); } late final _duk_get_boolean_defaultPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_bool_t)>>('duk_get_boolean_default'); late final _duk_get_boolean_default = _duk_get_boolean_defaultPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); double duk_get_number_default( ffi.Pointer<duk_context> ctx, int idx, double def_value, ) { return _duk_get_number_default( ctx, idx, def_value, ); } late final _duk_get_number_defaultPtr = _lookup< ffi.NativeFunction< duk_double_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_double_t)>>('duk_get_number_default'); late final _duk_get_number_default = _duk_get_number_defaultPtr .asFunction<double Function(ffi.Pointer<duk_context>, int, double)>(); int duk_get_int_default( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_get_int_default( ctx, idx, def_value, ); } late final _duk_get_int_defaultPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_int_t)>>('duk_get_int_default'); late final _duk_get_int_default = _duk_get_int_defaultPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_get_uint_default( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_get_uint_default( ctx, idx, def_value, ); } late final _duk_get_uint_defaultPtr = _lookup< ffi.NativeFunction< duk_uint_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_get_uint_default'); late final _duk_get_uint_default = _duk_get_uint_defaultPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); ffi.Pointer<ffi.Char> duk_get_string_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Char> def_value, ) { return _duk_get_string_default( ctx, idx, def_value, ); } late final _duk_get_string_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_get_string_default'); late final _duk_get_string_default = _duk_get_string_defaultPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); ffi.Pointer<ffi.Char> duk_get_lstring_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ffi.Pointer<ffi.Char> def_ptr, int def_len, ) { return _duk_get_lstring_default( ctx, idx, out_len, def_ptr, def_len, ); } late final _duk_get_lstring_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_get_lstring_default'); late final _duk_get_lstring_default = _duk_get_lstring_defaultPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Char>, int)>(); ffi.Pointer<ffi.Void> duk_get_buffer_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ffi.Pointer<ffi.Void> def_ptr, int def_len, ) { return _duk_get_buffer_default( ctx, idx, out_size, def_ptr, def_len, ); } late final _duk_get_buffer_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_get_buffer_default'); late final _duk_get_buffer_default = _duk_get_buffer_defaultPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, int)>(); ffi.Pointer<ffi.Void> duk_get_buffer_data_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ffi.Pointer<ffi.Void> def_ptr, int def_len, ) { return _duk_get_buffer_data_default( ctx, idx, out_size, def_ptr, def_len, ); } late final _duk_get_buffer_data_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_get_buffer_data_default'); late final _duk_get_buffer_data_default = _duk_get_buffer_data_defaultPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, int)>(); ffi.Pointer<ffi.Void> duk_get_pointer_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Void> def_value, ) { return _duk_get_pointer_default( ctx, idx, def_value, ); } late final _duk_get_pointer_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_get_pointer_default'); late final _duk_get_pointer_default = _duk_get_pointer_defaultPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); duk_c_function duk_get_c_function_default( ffi.Pointer<duk_context> ctx, int idx, duk_c_function def_value, ) { return _duk_get_c_function_default( ctx, idx, def_value, ); } late final _duk_get_c_function_defaultPtr = _lookup< ffi.NativeFunction< duk_c_function Function(ffi.Pointer<duk_context>, duk_idx_t, duk_c_function)>>('duk_get_c_function_default'); late final _duk_get_c_function_default = _duk_get_c_function_defaultPtr.asFunction< duk_c_function Function( ffi.Pointer<duk_context>, int, duk_c_function)>(); ffi.Pointer<duk_context> duk_get_context_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_context> def_value, ) { return _duk_get_context_default( ctx, idx, def_value, ); } late final _duk_get_context_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<duk_context> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_context>)>>('duk_get_context_default'); late final _duk_get_context_default = _duk_get_context_defaultPtr.asFunction< ffi.Pointer<duk_context> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_context>)>(); ffi.Pointer<ffi.Void> duk_get_heapptr_default( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Void> def_value, ) { return _duk_get_heapptr_default( ctx, idx, def_value, ); } late final _duk_get_heapptr_defaultPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_get_heapptr_default'); late final _duk_get_heapptr_default = _duk_get_heapptr_defaultPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); /// Opt operations: like require operations but with an explicit default value /// when value is undefined or index is invalid, null and non-matching types /// cause a TypeError. int duk_opt_boolean( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_opt_boolean( ctx, idx, def_value, ); } late final _duk_opt_booleanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_bool_t)>>('duk_opt_boolean'); late final _duk_opt_boolean = _duk_opt_booleanPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); double duk_opt_number( ffi.Pointer<duk_context> ctx, int idx, double def_value, ) { return _duk_opt_number( ctx, idx, def_value, ); } late final _duk_opt_numberPtr = _lookup< ffi.NativeFunction< duk_double_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_double_t)>>('duk_opt_number'); late final _duk_opt_number = _duk_opt_numberPtr .asFunction<double Function(ffi.Pointer<duk_context>, int, double)>(); int duk_opt_int( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_opt_int( ctx, idx, def_value, ); } late final _duk_opt_intPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t, duk_int_t)>>('duk_opt_int'); late final _duk_opt_int = _duk_opt_intPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_opt_uint( ffi.Pointer<duk_context> ctx, int idx, int def_value, ) { return _duk_opt_uint( ctx, idx, def_value, ); } late final _duk_opt_uintPtr = _lookup< ffi.NativeFunction< duk_uint_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_opt_uint'); late final _duk_opt_uint = _duk_opt_uintPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); ffi.Pointer<ffi.Char> duk_opt_string( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Char> def_ptr, ) { return _duk_opt_string( ctx, idx, def_ptr, ); } late final _duk_opt_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_opt_string'); late final _duk_opt_string = _duk_opt_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); ffi.Pointer<ffi.Char> duk_opt_lstring( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ffi.Pointer<ffi.Char> def_ptr, int def_len, ) { return _duk_opt_lstring( ctx, idx, out_len, def_ptr, def_len, ); } late final _duk_opt_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_opt_lstring'); late final _duk_opt_lstring = _duk_opt_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Char>, int)>(); ffi.Pointer<ffi.Void> duk_opt_buffer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ffi.Pointer<ffi.Void> def_ptr, int def_size, ) { return _duk_opt_buffer( ctx, idx, out_size, def_ptr, def_size, ); } late final _duk_opt_bufferPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_opt_buffer'); late final _duk_opt_buffer = _duk_opt_bufferPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, int)>(); ffi.Pointer<ffi.Void> duk_opt_buffer_data( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ffi.Pointer<ffi.Void> def_ptr, int def_size, ) { return _duk_opt_buffer_data( ctx, idx, out_size, def_ptr, def_size, ); } late final _duk_opt_buffer_dataPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_opt_buffer_data'); late final _duk_opt_buffer_data = _duk_opt_buffer_dataPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, ffi.Pointer<ffi.Void>, int)>(); ffi.Pointer<ffi.Void> duk_opt_pointer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Void> def_value, ) { return _duk_opt_pointer( ctx, idx, def_value, ); } late final _duk_opt_pointerPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_opt_pointer'); late final _duk_opt_pointer = _duk_opt_pointerPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); duk_c_function duk_opt_c_function( ffi.Pointer<duk_context> ctx, int idx, duk_c_function def_value, ) { return _duk_opt_c_function( ctx, idx, def_value, ); } late final _duk_opt_c_functionPtr = _lookup< ffi.NativeFunction< duk_c_function Function(ffi.Pointer<duk_context>, duk_idx_t, duk_c_function)>>('duk_opt_c_function'); late final _duk_opt_c_function = _duk_opt_c_functionPtr.asFunction< duk_c_function Function(ffi.Pointer<duk_context>, int, duk_c_function)>(); ffi.Pointer<duk_context> duk_opt_context( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_context> def_value, ) { return _duk_opt_context( ctx, idx, def_value, ); } late final _duk_opt_contextPtr = _lookup< ffi.NativeFunction< ffi.Pointer<duk_context> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_context>)>>('duk_opt_context'); late final _duk_opt_context = _duk_opt_contextPtr.asFunction< ffi.Pointer<duk_context> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_context>)>(); ffi.Pointer<ffi.Void> duk_opt_heapptr( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Void> def_value, ) { return _duk_opt_heapptr( ctx, idx, def_value, ); } late final _duk_opt_heapptrPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_opt_heapptr'); late final _duk_opt_heapptr = _duk_opt_heapptrPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); void duk_require_undefined( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_undefined( ctx, idx, ); } late final _duk_require_undefinedPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_undefined'); late final _duk_require_undefined = _duk_require_undefinedPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_require_null( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_null( ctx, idx, ); } late final _duk_require_nullPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_null'); late final _duk_require_null = _duk_require_nullPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_require_boolean( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_boolean( ctx, idx, ); } late final _duk_require_booleanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_boolean'); late final _duk_require_boolean = _duk_require_booleanPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); double duk_require_number( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_number( ctx, idx, ); } late final _duk_require_numberPtr = _lookup< ffi.NativeFunction< duk_double_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_number'); late final _duk_require_number = _duk_require_numberPtr .asFunction<double Function(ffi.Pointer<duk_context>, int)>(); int duk_require_int( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_int( ctx, idx, ); } late final _duk_require_intPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_int'); late final _duk_require_int = _duk_require_intPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_require_uint( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_uint( ctx, idx, ); } late final _duk_require_uintPtr = _lookup< ffi.NativeFunction< duk_uint_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_uint'); late final _duk_require_uint = _duk_require_uintPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_require_string( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_string( ctx, idx, ); } late final _duk_require_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_string'); late final _duk_require_string = _duk_require_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_require_lstring( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ) { return _duk_require_lstring( ctx, idx, out_len, ); } late final _duk_require_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_require_lstring'); late final _duk_require_lstring = _duk_require_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); void duk_require_object( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_object( ctx, idx, ); } late final _duk_require_objectPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_object'); late final _duk_require_object = _duk_require_objectPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Void> duk_require_buffer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ) { return _duk_require_buffer( ctx, idx, out_size, ); } late final _duk_require_bufferPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_require_buffer'); late final _duk_require_buffer = _duk_require_bufferPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_require_buffer_data( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ) { return _duk_require_buffer_data( ctx, idx, out_size, ); } late final _duk_require_buffer_dataPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_require_buffer_data'); late final _duk_require_buffer_data = _duk_require_buffer_dataPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_require_pointer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_pointer( ctx, idx, ); } late final _duk_require_pointerPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_pointer'); late final _duk_require_pointer = _duk_require_pointerPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); duk_c_function duk_require_c_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_c_function( ctx, idx, ); } late final _duk_require_c_functionPtr = _lookup< ffi.NativeFunction< duk_c_function Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_c_function'); late final _duk_require_c_function = _duk_require_c_functionPtr .asFunction<duk_c_function Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<duk_context> duk_require_context( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_context( ctx, idx, ); } late final _duk_require_contextPtr = _lookup< ffi.NativeFunction< ffi.Pointer<duk_context> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_context'); late final _duk_require_context = _duk_require_contextPtr.asFunction< ffi.Pointer<duk_context> Function(ffi.Pointer<duk_context>, int)>(); void duk_require_function( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_function( ctx, idx, ); } late final _duk_require_functionPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_function'); late final _duk_require_function = _duk_require_functionPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_require_constructor_call( ffi.Pointer<duk_context> ctx, ) { return _duk_require_constructor_call( ctx, ); } late final _duk_require_constructor_callPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_require_constructor_call'); late final _duk_require_constructor_call = _duk_require_constructor_callPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_require_constructable( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_constructable( ctx, idx, ); } late final _duk_require_constructablePtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_constructable'); late final _duk_require_constructable = _duk_require_constructablePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Void> duk_require_heapptr( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_require_heapptr( ctx, idx, ); } late final _duk_require_heapptrPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_require_heapptr'); late final _duk_require_heapptr = _duk_require_heapptrPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); /// Coercion operations: in-place coercion, return coerced value where /// applicable. If index is invalid, throw error. Some coercions may /// throw an expected error (e.g. from a toString() or valueOf() call) /// or an internal error (e.g. from out of memory). void duk_to_undefined( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_undefined( ctx, idx, ); } late final _duk_to_undefinedPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_undefined'); late final _duk_to_undefined = _duk_to_undefinedPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_to_null( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_null( ctx, idx, ); } late final _duk_to_nullPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_null'); late final _duk_to_null = _duk_to_nullPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_to_boolean( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_boolean( ctx, idx, ); } late final _duk_to_booleanPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_boolean'); late final _duk_to_boolean = _duk_to_booleanPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); double duk_to_number( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_number( ctx, idx, ); } late final _duk_to_numberPtr = _lookup< ffi.NativeFunction< duk_double_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_number'); late final _duk_to_number = _duk_to_numberPtr .asFunction<double Function(ffi.Pointer<duk_context>, int)>(); int duk_to_int( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_int( ctx, idx, ); } late final _duk_to_intPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_int'); late final _duk_to_int = _duk_to_intPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_to_uint( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_uint( ctx, idx, ); } late final _duk_to_uintPtr = _lookup< ffi.NativeFunction< duk_uint_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_uint'); late final _duk_to_uint = _duk_to_uintPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_to_int32( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_int32( ctx, idx, ); } late final _duk_to_int32Ptr = _lookup< ffi.NativeFunction< duk_int32_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_int32'); late final _duk_to_int32 = _duk_to_int32Ptr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_to_uint32( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_uint32( ctx, idx, ); } late final _duk_to_uint32Ptr = _lookup< ffi.NativeFunction< duk_uint32_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_uint32'); late final _duk_to_uint32 = _duk_to_uint32Ptr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_to_uint16( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_uint16( ctx, idx, ); } late final _duk_to_uint16Ptr = _lookup< ffi.NativeFunction< duk_uint16_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_uint16'); late final _duk_to_uint16 = _duk_to_uint16Ptr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_to_string( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_string( ctx, idx, ); } late final _duk_to_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_string'); late final _duk_to_string = _duk_to_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_to_lstring( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ) { return _duk_to_lstring( ctx, idx, out_len, ); } late final _duk_to_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_to_lstring'); late final _duk_to_lstring = _duk_to_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Void> duk_to_buffer_raw( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, int flags, ) { return _duk_to_buffer_raw( ctx, idx, out_size, flags, ); } late final _duk_to_buffer_rawPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>, duk_uint_t)>>('duk_to_buffer_raw'); late final _duk_to_buffer_raw = _duk_to_buffer_rawPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>, int)>(); ffi.Pointer<ffi.Void> duk_to_pointer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_pointer( ctx, idx, ); } late final _duk_to_pointerPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_pointer'); late final _duk_to_pointer = _duk_to_pointerPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int)>(); void duk_to_object( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_object( ctx, idx, ); } late final _duk_to_objectPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_object'); late final _duk_to_object = _duk_to_objectPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_to_primitive( ffi.Pointer<duk_context> ctx, int idx, int hint, ) { return _duk_to_primitive( ctx, idx, hint, ); } late final _duk_to_primitivePtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_int_t)>>('duk_to_primitive'); late final _duk_to_primitive = _duk_to_primitivePtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); /// safe variants of a few coercion operations ffi.Pointer<ffi.Char> duk_safe_to_lstring( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_len, ) { return _duk_safe_to_lstring( ctx, idx, out_len, ); } late final _duk_safe_to_lstringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_safe_to_lstring'); late final _duk_safe_to_lstring = _duk_safe_to_lstringPtr.asFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); ffi.Pointer<ffi.Char> duk_to_stacktrace( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_to_stacktrace( ctx, idx, ); } late final _duk_to_stacktracePtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_to_stacktrace'); late final _duk_to_stacktrace = _duk_to_stacktracePtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_safe_to_stacktrace( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_safe_to_stacktrace( ctx, idx, ); } late final _duk_safe_to_stacktracePtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_safe_to_stacktrace'); late final _duk_safe_to_stacktrace = _duk_safe_to_stacktracePtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); /// Value length int duk_get_length( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_length( ctx, idx, ); } late final _duk_get_lengthPtr = _lookup< ffi.NativeFunction< duk_size_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_length'); late final _duk_get_length = _duk_get_lengthPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_set_length( ffi.Pointer<duk_context> ctx, int idx, int len, ) { return _duk_set_length( ctx, idx, len, ); } late final _duk_set_lengthPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_size_t)>>('duk_set_length'); late final _duk_set_length = _duk_set_lengthPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); /// Misc conversion ffi.Pointer<ffi.Char> duk_base64_encode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_base64_encode( ctx, idx, ); } late final _duk_base64_encodePtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_base64_encode'); late final _duk_base64_encode = _duk_base64_encodePtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); void duk_base64_decode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_base64_decode( ctx, idx, ); } late final _duk_base64_decodePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_base64_decode'); late final _duk_base64_decode = _duk_base64_decodePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_hex_encode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_hex_encode( ctx, idx, ); } late final _duk_hex_encodePtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_hex_encode'); late final _duk_hex_encode = _duk_hex_encodePtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); void duk_hex_decode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_hex_decode( ctx, idx, ); } late final _duk_hex_decodePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_hex_decode'); late final _duk_hex_decode = _duk_hex_decodePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); ffi.Pointer<ffi.Char> duk_json_encode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_json_encode( ctx, idx, ); } late final _duk_json_encodePtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_json_encode'); late final _duk_json_encode = _duk_json_encodePtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); void duk_json_decode( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_json_decode( ctx, idx, ); } late final _duk_json_decodePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_json_decode'); late final _duk_json_decode = _duk_json_decodePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_cbor_encode( ffi.Pointer<duk_context> ctx, int idx, int encode_flags, ) { return _duk_cbor_encode( ctx, idx, encode_flags, ); } late final _duk_cbor_encodePtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_cbor_encode'); late final _duk_cbor_encode = _duk_cbor_encodePtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); void duk_cbor_decode( ffi.Pointer<duk_context> ctx, int idx, int decode_flags, ) { return _duk_cbor_decode( ctx, idx, decode_flags, ); } late final _duk_cbor_decodePtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_cbor_decode'); late final _duk_cbor_decode = _duk_cbor_decodePtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); ffi.Pointer<ffi.Char> duk_buffer_to_string( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_buffer_to_string( ctx, idx, ); } late final _duk_buffer_to_stringPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Char> Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_buffer_to_string'); late final _duk_buffer_to_string = _duk_buffer_to_stringPtr.asFunction< ffi.Pointer<ffi.Char> Function(ffi.Pointer<duk_context>, int)>(); /// Buffer ffi.Pointer<ffi.Void> duk_resize_buffer( ffi.Pointer<duk_context> ctx, int idx, int new_size, ) { return _duk_resize_buffer( ctx, idx, new_size, ); } late final _duk_resize_bufferPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, duk_size_t)>>('duk_resize_buffer'); late final _duk_resize_buffer = _duk_resize_bufferPtr.asFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, int, int)>(); ffi.Pointer<ffi.Void> duk_steal_buffer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<duk_size_t> out_size, ) { return _duk_steal_buffer( ctx, idx, out_size, ); } late final _duk_steal_bufferPtr = _lookup< ffi.NativeFunction< ffi.Pointer<ffi.Void> Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_size_t>)>>('duk_steal_buffer'); late final _duk_steal_buffer = _duk_steal_bufferPtr.asFunction< ffi.Pointer<ffi.Void> Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_size_t>)>(); void duk_config_buffer( ffi.Pointer<duk_context> ctx, int idx, ffi.Pointer<ffi.Void> ptr, int len, ) { return _duk_config_buffer( ctx, idx, ptr, len, ); } late final _duk_config_bufferPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>, duk_size_t)>>('duk_config_buffer'); late final _duk_config_buffer = _duk_config_bufferPtr.asFunction< void Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>, int)>(); /// Property access /// /// The basic function assumes key is on stack. The _(l)string variant takes /// a C string as a property name; the _literal variant takes a C literal. /// The _index variant takes an array index as a property name (e.g. 123 is /// equivalent to the key "123"). The _heapptr variant takes a raw, borrowed /// heap pointer. int duk_get_prop( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_get_prop( ctx, obj_idx, ); } late final _duk_get_propPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_prop'); late final _duk_get_prop = _duk_get_propPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_get_prop_string( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, ) { return _duk_get_prop_string( ctx, obj_idx, key, ); } late final _duk_get_prop_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_get_prop_string'); late final _duk_get_prop_string = _duk_get_prop_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); int duk_get_prop_lstring( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_get_prop_lstring( ctx, obj_idx, key, key_len, ); } late final _duk_get_prop_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_get_prop_lstring'); late final _duk_get_prop_lstring = _duk_get_prop_lstringPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_get_prop_literal_raw( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_get_prop_literal_raw( ctx, obj_idx, key, key_len, ); } late final _duk_get_prop_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_get_prop_literal_raw'); late final _duk_get_prop_literal_raw = _duk_get_prop_literal_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_get_prop_index( ffi.Pointer<duk_context> ctx, int obj_idx, int arr_idx, ) { return _duk_get_prop_index( ctx, obj_idx, arr_idx, ); } late final _duk_get_prop_indexPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uarridx_t)>>('duk_get_prop_index'); late final _duk_get_prop_index = _duk_get_prop_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_get_prop_heapptr( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_get_prop_heapptr( ctx, obj_idx, ptr, ); } late final _duk_get_prop_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_get_prop_heapptr'); late final _duk_get_prop_heapptr = _duk_get_prop_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); int duk_put_prop( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_put_prop( ctx, obj_idx, ); } late final _duk_put_propPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_put_prop'); late final _duk_put_prop = _duk_put_propPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_put_prop_string( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, ) { return _duk_put_prop_string( ctx, obj_idx, key, ); } late final _duk_put_prop_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_put_prop_string'); late final _duk_put_prop_string = _duk_put_prop_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); int duk_put_prop_lstring( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_put_prop_lstring( ctx, obj_idx, key, key_len, ); } late final _duk_put_prop_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_put_prop_lstring'); late final _duk_put_prop_lstring = _duk_put_prop_lstringPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_put_prop_literal_raw( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_put_prop_literal_raw( ctx, obj_idx, key, key_len, ); } late final _duk_put_prop_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_put_prop_literal_raw'); late final _duk_put_prop_literal_raw = _duk_put_prop_literal_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_put_prop_index( ffi.Pointer<duk_context> ctx, int obj_idx, int arr_idx, ) { return _duk_put_prop_index( ctx, obj_idx, arr_idx, ); } late final _duk_put_prop_indexPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uarridx_t)>>('duk_put_prop_index'); late final _duk_put_prop_index = _duk_put_prop_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_put_prop_heapptr( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_put_prop_heapptr( ctx, obj_idx, ptr, ); } late final _duk_put_prop_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_put_prop_heapptr'); late final _duk_put_prop_heapptr = _duk_put_prop_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); int duk_del_prop( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_del_prop( ctx, obj_idx, ); } late final _duk_del_propPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_del_prop'); late final _duk_del_prop = _duk_del_propPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_del_prop_string( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, ) { return _duk_del_prop_string( ctx, obj_idx, key, ); } late final _duk_del_prop_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_del_prop_string'); late final _duk_del_prop_string = _duk_del_prop_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); int duk_del_prop_lstring( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_del_prop_lstring( ctx, obj_idx, key, key_len, ); } late final _duk_del_prop_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_del_prop_lstring'); late final _duk_del_prop_lstring = _duk_del_prop_lstringPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_del_prop_literal_raw( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_del_prop_literal_raw( ctx, obj_idx, key, key_len, ); } late final _duk_del_prop_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_del_prop_literal_raw'); late final _duk_del_prop_literal_raw = _duk_del_prop_literal_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_del_prop_index( ffi.Pointer<duk_context> ctx, int obj_idx, int arr_idx, ) { return _duk_del_prop_index( ctx, obj_idx, arr_idx, ); } late final _duk_del_prop_indexPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uarridx_t)>>('duk_del_prop_index'); late final _duk_del_prop_index = _duk_del_prop_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_del_prop_heapptr( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_del_prop_heapptr( ctx, obj_idx, ptr, ); } late final _duk_del_prop_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_del_prop_heapptr'); late final _duk_del_prop_heapptr = _duk_del_prop_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); int duk_has_prop( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_has_prop( ctx, obj_idx, ); } late final _duk_has_propPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_has_prop'); late final _duk_has_prop = _duk_has_propPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_has_prop_string( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, ) { return _duk_has_prop_string( ctx, obj_idx, key, ); } late final _duk_has_prop_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>)>>('duk_has_prop_string'); late final _duk_has_prop_string = _duk_has_prop_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>)>(); int duk_has_prop_lstring( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_has_prop_lstring( ctx, obj_idx, key, key_len, ); } late final _duk_has_prop_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_has_prop_lstring'); late final _duk_has_prop_lstring = _duk_has_prop_lstringPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_has_prop_literal_raw( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_has_prop_literal_raw( ctx, obj_idx, key, key_len, ); } late final _duk_has_prop_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_has_prop_literal_raw'); late final _duk_has_prop_literal_raw = _duk_has_prop_literal_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Char>, int)>(); int duk_has_prop_index( ffi.Pointer<duk_context> ctx, int obj_idx, int arr_idx, ) { return _duk_has_prop_index( ctx, obj_idx, arr_idx, ); } late final _duk_has_prop_indexPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uarridx_t)>>('duk_has_prop_index'); late final _duk_has_prop_index = _duk_has_prop_indexPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_has_prop_heapptr( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_has_prop_heapptr( ctx, obj_idx, ptr, ); } late final _duk_has_prop_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<ffi.Void>)>>('duk_has_prop_heapptr'); late final _duk_has_prop_heapptr = _duk_has_prop_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, int, ffi.Pointer<ffi.Void>)>(); void duk_get_prop_desc( ffi.Pointer<duk_context> ctx, int obj_idx, int flags, ) { return _duk_get_prop_desc( ctx, obj_idx, flags, ); } late final _duk_get_prop_descPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_get_prop_desc'); late final _duk_get_prop_desc = _duk_get_prop_descPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); void duk_def_prop( ffi.Pointer<duk_context> ctx, int obj_idx, int flags, ) { return _duk_def_prop( ctx, obj_idx, flags, ); } late final _duk_def_propPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_def_prop'); late final _duk_def_prop = _duk_def_propPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); int duk_get_global_string( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, ) { return _duk_get_global_string( ctx, key, ); } late final _duk_get_global_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>>('duk_get_global_string'); late final _duk_get_global_string = _duk_get_global_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>(); int duk_get_global_lstring( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_get_global_lstring( ctx, key, key_len, ); } late final _duk_get_global_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_get_global_lstring'); late final _duk_get_global_lstring = _duk_get_global_lstringPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); int duk_get_global_literal_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_get_global_literal_raw( ctx, key, key_len, ); } late final _duk_get_global_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_get_global_literal_raw'); late final _duk_get_global_literal_raw = _duk_get_global_literal_rawPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); int duk_get_global_heapptr( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_get_global_heapptr( ctx, ptr, ); } late final _duk_get_global_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_get_global_heapptr'); late final _duk_get_global_heapptr = _duk_get_global_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); int duk_put_global_string( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, ) { return _duk_put_global_string( ctx, key, ); } late final _duk_put_global_stringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>>('duk_put_global_string'); late final _duk_put_global_string = _duk_put_global_stringPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>)>(); int duk_put_global_lstring( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_put_global_lstring( ctx, key, key_len, ); } late final _duk_put_global_lstringPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_put_global_lstring'); late final _duk_put_global_lstring = _duk_put_global_lstringPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); int duk_put_global_literal_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> key, int key_len, ) { return _duk_put_global_literal_raw( ctx, key, key_len, ); } late final _duk_put_global_literal_rawPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t)>>('duk_put_global_literal_raw'); late final _duk_put_global_literal_raw = _duk_put_global_literal_rawPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int)>(); int duk_put_global_heapptr( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> ptr, ) { return _duk_put_global_heapptr( ctx, ptr, ); } late final _duk_put_global_heapptrPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>>('duk_put_global_heapptr'); late final _duk_put_global_heapptr = _duk_put_global_heapptrPtr.asFunction< int Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Void>)>(); /// Inspection void duk_inspect_value( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_inspect_value( ctx, idx, ); } late final _duk_inspect_valuePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_inspect_value'); late final _duk_inspect_value = _duk_inspect_valuePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_inspect_callstack_entry( ffi.Pointer<duk_context> ctx, int level, ) { return _duk_inspect_callstack_entry( ctx, level, ); } late final _duk_inspect_callstack_entryPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_int_t)>>('duk_inspect_callstack_entry'); late final _duk_inspect_callstack_entry = _duk_inspect_callstack_entryPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); /// Object prototype void duk_get_prototype( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_prototype( ctx, idx, ); } late final _duk_get_prototypePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_prototype'); late final _duk_get_prototype = _duk_get_prototypePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_set_prototype( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_set_prototype( ctx, idx, ); } late final _duk_set_prototypePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_set_prototype'); late final _duk_set_prototype = _duk_set_prototypePtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); /// Object finalizer void duk_get_finalizer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_finalizer( ctx, idx, ); } late final _duk_get_finalizerPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_finalizer'); late final _duk_get_finalizer = _duk_get_finalizerPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_set_finalizer( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_set_finalizer( ctx, idx, ); } late final _duk_set_finalizerPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_set_finalizer'); late final _duk_set_finalizer = _duk_set_finalizerPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); /// Global object void duk_set_global_object( ffi.Pointer<duk_context> ctx, ) { return _duk_set_global_object( ctx, ); } late final _duk_set_global_objectPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_set_global_object'); late final _duk_set_global_object = _duk_set_global_objectPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); /// Duktape/C function magic value int duk_get_magic( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_get_magic( ctx, idx, ); } late final _duk_get_magicPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_get_magic'); late final _duk_get_magic = _duk_get_magicPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_set_magic( ffi.Pointer<duk_context> ctx, int idx, int magic, ) { return _duk_set_magic( ctx, idx, magic, ); } late final _duk_set_magicPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_int_t)>>('duk_set_magic'); late final _duk_set_magic = _duk_set_magicPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); int duk_get_current_magic( ffi.Pointer<duk_context> ctx, ) { return _duk_get_current_magic( ctx, ); } late final _duk_get_current_magicPtr = _lookup<ffi.NativeFunction<duk_int_t Function(ffi.Pointer<duk_context>)>>( 'duk_get_current_magic'); late final _duk_get_current_magic = _duk_get_current_magicPtr .asFunction<int Function(ffi.Pointer<duk_context>)>(); /// Module helpers: put multiple function or constant properties void duk_put_function_list( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<duk_function_list_entry> funcs, ) { return _duk_put_function_list( ctx, obj_idx, funcs, ); } late final _duk_put_function_listPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_function_list_entry>)>>('duk_put_function_list'); late final _duk_put_function_list = _duk_put_function_listPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, ffi.Pointer<duk_function_list_entry>)>(); void duk_put_number_list( ffi.Pointer<duk_context> ctx, int obj_idx, ffi.Pointer<duk_number_list_entry> numbers, ) { return _duk_put_number_list( ctx, obj_idx, numbers, ); } late final _duk_put_number_listPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, ffi.Pointer<duk_number_list_entry>)>>('duk_put_number_list'); late final _duk_put_number_list = _duk_put_number_listPtr.asFunction< void Function( ffi.Pointer<duk_context>, int, ffi.Pointer<duk_number_list_entry>)>(); /// Object operations void duk_compact( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_compact( ctx, obj_idx, ); } late final _duk_compactPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_compact'); late final _duk_compact = _duk_compactPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_enum( ffi.Pointer<duk_context> ctx, int obj_idx, int enum_flags, ) { return _duk_enum( ctx, obj_idx, enum_flags, ); } late final _duk_enumPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t, duk_uint_t)>>('duk_enum'); late final _duk_enum = _duk_enumPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); int duk_next( ffi.Pointer<duk_context> ctx, int enum_idx, int get_value, ) { return _duk_next( ctx, enum_idx, get_value, ); } late final _duk_nextPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t, duk_bool_t)>>('duk_next'); late final _duk_next = _duk_nextPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); void duk_seal( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_seal( ctx, obj_idx, ); } late final _duk_sealPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_seal'); late final _duk_seal = _duk_sealPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_freeze( ffi.Pointer<duk_context> ctx, int obj_idx, ) { return _duk_freeze( ctx, obj_idx, ); } late final _duk_freezePtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_freeze'); late final _duk_freeze = _duk_freezePtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); /// String manipulation void duk_concat( ffi.Pointer<duk_context> ctx, int count, ) { return _duk_concat( ctx, count, ); } late final _duk_concatPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_concat'); late final _duk_concat = _duk_concatPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_join( ffi.Pointer<duk_context> ctx, int count, ) { return _duk_join( ctx, count, ); } late final _duk_joinPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_join'); late final _duk_join = _duk_joinPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_decode_string( ffi.Pointer<duk_context> ctx, int idx, duk_decode_char_function callback, ffi.Pointer<ffi.Void> udata, ) { return _duk_decode_string( ctx, idx, callback, udata, ); } late final _duk_decode_stringPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t, duk_decode_char_function, ffi.Pointer<ffi.Void>)>>('duk_decode_string'); late final _duk_decode_string = _duk_decode_stringPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, duk_decode_char_function, ffi.Pointer<ffi.Void>)>(); void duk_map_string( ffi.Pointer<duk_context> ctx, int idx, duk_map_char_function callback, ffi.Pointer<ffi.Void> udata, ) { return _duk_map_string( ctx, idx, callback, udata, ); } late final _duk_map_stringPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_map_char_function, ffi.Pointer<ffi.Void>)>>('duk_map_string'); late final _duk_map_string = _duk_map_stringPtr.asFunction< void Function(ffi.Pointer<duk_context>, int, duk_map_char_function, ffi.Pointer<ffi.Void>)>(); void duk_substring( ffi.Pointer<duk_context> ctx, int idx, int start_char_offset, int end_char_offset, ) { return _duk_substring( ctx, idx, start_char_offset, end_char_offset, ); } late final _duk_substringPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_size_t, duk_size_t)>>('duk_substring'); late final _duk_substring = _duk_substringPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int, int)>(); void duk_trim( ffi.Pointer<duk_context> ctx, int idx, ) { return _duk_trim( ctx, idx, ); } late final _duk_trimPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_trim'); late final _duk_trim = _duk_trimPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_char_code_at( ffi.Pointer<duk_context> ctx, int idx, int char_offset, ) { return _duk_char_code_at( ctx, idx, char_offset, ); } late final _duk_char_code_atPtr = _lookup< ffi.NativeFunction< duk_codepoint_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_size_t)>>('duk_char_code_at'); late final _duk_char_code_at = _duk_char_code_atPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); /// ECMAScript operators int duk_equals( ffi.Pointer<duk_context> ctx, int idx1, int idx2, ) { return _duk_equals( ctx, idx1, idx2, ); } late final _duk_equalsPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_equals'); late final _duk_equals = _duk_equalsPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_strict_equals( ffi.Pointer<duk_context> ctx, int idx1, int idx2, ) { return _duk_strict_equals( ctx, idx1, idx2, ); } late final _duk_strict_equalsPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_strict_equals'); late final _duk_strict_equals = _duk_strict_equalsPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_samevalue( ffi.Pointer<duk_context> ctx, int idx1, int idx2, ) { return _duk_samevalue( ctx, idx1, idx2, ); } late final _duk_samevaluePtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_samevalue'); late final _duk_samevalue = _duk_samevaluePtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); int duk_instanceof( ffi.Pointer<duk_context> ctx, int idx1, int idx2, ) { return _duk_instanceof( ctx, idx1, idx2, ); } late final _duk_instanceofPtr = _lookup< ffi.NativeFunction< duk_bool_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_instanceof'); late final _duk_instanceof = _duk_instanceofPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); /// Random double duk_random( ffi.Pointer<duk_context> ctx, ) { return _duk_random( ctx, ); } late final _duk_randomPtr = _lookup< ffi.NativeFunction<duk_double_t Function(ffi.Pointer<duk_context>)>>( 'duk_random'); late final _duk_random = _duk_randomPtr.asFunction<double Function(ffi.Pointer<duk_context>)>(); /// Function (method) calls void duk_call( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_call( ctx, nargs, ); } late final _duk_callPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_call'); late final _duk_call = _duk_callPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_call_method( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_call_method( ctx, nargs, ); } late final _duk_call_methodPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_call_method'); late final _duk_call_method = _duk_call_methodPtr .asFunction<void Function(ffi.Pointer<duk_context>, int)>(); void duk_call_prop( ffi.Pointer<duk_context> ctx, int obj_idx, int nargs, ) { return _duk_call_prop( ctx, obj_idx, nargs, ); } late final _duk_call_propPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_call_prop'); late final _duk_call_prop = _duk_call_propPtr .asFunction<void Function(ffi.Pointer<duk_context>, int, int)>(); int duk_pcall( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_pcall( ctx, nargs, ); } late final _duk_pcallPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_pcall'); late final _duk_pcall = _duk_pcallPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_pcall_method( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_pcall_method( ctx, nargs, ); } late final _duk_pcall_methodPtr = _lookup< ffi.NativeFunction< duk_int_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_pcall_method'); late final _duk_pcall_method = _duk_pcall_methodPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_pcall_prop( ffi.Pointer<duk_context> ctx, int obj_idx, int nargs, ) { return _duk_pcall_prop( ctx, obj_idx, nargs, ); } late final _duk_pcall_propPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, duk_idx_t, duk_idx_t)>>('duk_pcall_prop'); late final _duk_pcall_prop = _duk_pcall_propPtr .asFunction<int Function(ffi.Pointer<duk_context>, int, int)>(); void duk_new( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_new( ctx, nargs, ); } late final _duk_newPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_new'); late final _duk_new = _duk_newPtr.asFunction<void Function(ffi.Pointer<duk_context>, int)>(); int duk_pnew( ffi.Pointer<duk_context> ctx, int nargs, ) { return _duk_pnew( ctx, nargs, ); } late final _duk_pnewPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, duk_idx_t)>>('duk_pnew'); late final _duk_pnew = _duk_pnewPtr.asFunction<int Function(ffi.Pointer<duk_context>, int)>(); int duk_safe_call( ffi.Pointer<duk_context> ctx, duk_safe_call_function func, ffi.Pointer<ffi.Void> udata, int nargs, int nrets, ) { return _duk_safe_call( ctx, func, udata, nargs, nrets, ); } late final _duk_safe_callPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, duk_safe_call_function, ffi.Pointer<ffi.Void>, duk_idx_t, duk_idx_t)>>('duk_safe_call'); late final _duk_safe_call = _duk_safe_callPtr.asFunction< int Function(ffi.Pointer<duk_context>, duk_safe_call_function, ffi.Pointer<ffi.Void>, int, int)>(); /// Compilation and evaluation int duk_eval_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> src_buffer, int src_length, int flags, ) { return _duk_eval_raw( ctx, src_buffer, src_length, flags, ); } late final _duk_eval_rawPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t, duk_uint_t)>>('duk_eval_raw'); late final _duk_eval_raw = _duk_eval_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int, int)>(); int duk_compile_raw( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Char> src_buffer, int src_length, int flags, ) { return _duk_compile_raw( ctx, src_buffer, src_length, flags, ); } late final _duk_compile_rawPtr = _lookup< ffi.NativeFunction< duk_int_t Function(ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, duk_size_t, duk_uint_t)>>('duk_compile_raw'); late final _duk_compile_raw = _duk_compile_rawPtr.asFunction< int Function( ffi.Pointer<duk_context>, ffi.Pointer<ffi.Char>, int, int)>(); /// Bytecode load/dump void duk_dump_function( ffi.Pointer<duk_context> ctx, ) { return _duk_dump_function( ctx, ); } late final _duk_dump_functionPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_dump_function'); late final _duk_dump_function = _duk_dump_functionPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_load_function( ffi.Pointer<duk_context> ctx, ) { return _duk_load_function( ctx, ); } late final _duk_load_functionPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_load_function'); late final _duk_load_function = _duk_load_functionPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); /// Debugging void duk_push_context_dump( ffi.Pointer<duk_context> ctx, ) { return _duk_push_context_dump( ctx, ); } late final _duk_push_context_dumpPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_push_context_dump'); late final _duk_push_context_dump = _duk_push_context_dumpPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); /// Debugger (debug protocol) void duk_debugger_attach( ffi.Pointer<duk_context> ctx, duk_debug_read_function read_cb, duk_debug_write_function write_cb, duk_debug_peek_function peek_cb, duk_debug_read_flush_function read_flush_cb, duk_debug_write_flush_function write_flush_cb, duk_debug_request_function request_cb, duk_debug_detached_function detached_cb, ffi.Pointer<ffi.Void> udata, ) { return _duk_debugger_attach( ctx, read_cb, write_cb, peek_cb, read_flush_cb, write_flush_cb, request_cb, detached_cb, udata, ); } late final _duk_debugger_attachPtr = _lookup< ffi.NativeFunction< ffi.Void Function( ffi.Pointer<duk_context>, duk_debug_read_function, duk_debug_write_function, duk_debug_peek_function, duk_debug_read_flush_function, duk_debug_write_flush_function, duk_debug_request_function, duk_debug_detached_function, ffi.Pointer<ffi.Void>)>>('duk_debugger_attach'); late final _duk_debugger_attach = _duk_debugger_attachPtr.asFunction< void Function( ffi.Pointer<duk_context>, duk_debug_read_function, duk_debug_write_function, duk_debug_peek_function, duk_debug_read_flush_function, duk_debug_write_flush_function, duk_debug_request_function, duk_debug_detached_function, ffi.Pointer<ffi.Void>)>(); void duk_debugger_detach( ffi.Pointer<duk_context> ctx, ) { return _duk_debugger_detach( ctx, ); } late final _duk_debugger_detachPtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_debugger_detach'); late final _duk_debugger_detach = _duk_debugger_detachPtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); void duk_debugger_cooperate( ffi.Pointer<duk_context> ctx, ) { return _duk_debugger_cooperate( ctx, ); } late final _duk_debugger_cooperatePtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_debugger_cooperate'); late final _duk_debugger_cooperate = _duk_debugger_cooperatePtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); int duk_debugger_notify( ffi.Pointer<duk_context> ctx, int nvalues, ) { return _duk_debugger_notify( ctx, nvalues, ); } late final _duk_debugger_notifyPtr = _lookup< ffi.NativeFunction< duk_bool_t Function( ffi.Pointer<duk_context>, duk_idx_t)>>('duk_debugger_notify'); late final _duk_debugger_notify = _duk_debugger_notifyPtr .asFunction<int Function(ffi.Pointer<duk_context>, int)>(); void duk_debugger_pause( ffi.Pointer<duk_context> ctx, ) { return _duk_debugger_pause( ctx, ); } late final _duk_debugger_pausePtr = _lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<duk_context>)>>( 'duk_debugger_pause'); late final _duk_debugger_pause = _duk_debugger_pausePtr .asFunction<void Function(ffi.Pointer<duk_context>)>(); /// Time handling double duk_get_now( ffi.Pointer<duk_context> ctx, ) { return _duk_get_now( ctx, ); } late final _duk_get_nowPtr = _lookup< ffi.NativeFunction<duk_double_t Function(ffi.Pointer<duk_context>)>>( 'duk_get_now'); late final _duk_get_now = _duk_get_nowPtr.asFunction<double Function(ffi.Pointer<duk_context>)>(); void duk_time_to_components( ffi.Pointer<duk_context> ctx, double timeval, ffi.Pointer<duk_time_components> comp, ) { return _duk_time_to_components( ctx, timeval, comp, ); } late final _duk_time_to_componentsPtr = _lookup< ffi.NativeFunction< ffi.Void Function(ffi.Pointer<duk_context>, duk_double_t, ffi.Pointer<duk_time_components>)>>('duk_time_to_components'); late final _duk_time_to_components = _duk_time_to_componentsPtr.asFunction< void Function(ffi.Pointer<duk_context>, double, ffi.Pointer<duk_time_components>)>(); double duk_components_to_time( ffi.Pointer<duk_context> ctx, ffi.Pointer<duk_time_components> comp, ) { return _duk_components_to_time( ctx, comp, ); } late final _duk_components_to_timePtr = _lookup< ffi.NativeFunction< duk_double_t Function(ffi.Pointer<duk_context>, ffi.Pointer<duk_time_components>)>>('duk_components_to_time'); late final _duk_components_to_time = _duk_components_to_timePtr.asFunction< double Function( ffi.Pointer<duk_context>, ffi.Pointer<duk_time_components>)>(); } /// Public API specific typedefs /// /// Many types are wrapped by Duktape for portability to rare platforms /// where e.g. 'int' is a 16-bit type. See practical typing discussion /// in Duktape web documentation. final class duk_thread_state extends ffi.Struct { /// XXX: Enough space to hold internal suspend/resume structure. /// This is rather awkward and to be fixed when the internal /// structure is visible for the public API header. @ffi.Array.multi([128]) external ffi.Array<ffi.Char> data; } final class duk_memory_functions extends ffi.Struct { external duk_alloc_function alloc_func; external duk_realloc_function realloc_func; external duk_free_function free_func; external ffi.Pointer<ffi.Void> udata; } typedef duk_alloc_function = ffi.Pointer<ffi.NativeFunction<duk_alloc_functionFunction>>; typedef duk_alloc_functionFunction = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void> udata, duk_size_t size); typedef Dartduk_alloc_functionFunction = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void> udata, Dartduk_size_t size); /// A few types are assumed to always exist. typedef duk_size_t = ffi.Size; typedef Dartduk_size_t = int; typedef duk_realloc_function = ffi.Pointer<ffi.NativeFunction<duk_realloc_functionFunction>>; typedef duk_realloc_functionFunction = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Void> ptr, duk_size_t size); typedef Dartduk_realloc_functionFunction = ffi.Pointer<ffi.Void> Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Void> ptr, Dartduk_size_t size); typedef duk_free_function = ffi.Pointer<ffi.NativeFunction<duk_free_functionFunction>>; typedef duk_free_functionFunction = ffi.Void Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Void> ptr); typedef Dartduk_free_functionFunction = void Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Void> ptr); final class duk_function_list_entry extends ffi.Struct { external ffi.Pointer<ffi.Char> key; external duk_c_function value; @duk_idx_t() external int nargs; } typedef duk_c_function = ffi.Pointer<ffi.NativeFunction<duk_c_functionFunction>>; typedef duk_c_functionFunction = duk_ret_t Function( ffi.Pointer<duk_context> ctx); typedef Dartduk_c_functionFunction = Dartduk_small_int_t Function( ffi.Pointer<duk_context> ctx); /// Duktape/C function return value, platform int is enough for now to /// represent 0, 1, or negative error code. Must be compatible with /// assigning truth values (e.g. duk_ret_t rc = (foo == bar);). typedef duk_ret_t = duk_small_int_t; /// Small integers (16 bits or more) can fall back to the 'int' type, but /// have a typedef so they are marked "small" explicitly. typedef duk_small_int_t = ffi.Int; typedef Dartduk_small_int_t = int; /// Type used in public API declarations and user code. Typedef maps to /// 'struct duk_hthread' like the 'duk_hthread' typedef which is used /// exclusively in internals. typedef duk_context = duk_hthread; final class duk_hthread extends ffi.Opaque {} /// Index values must have at least 32-bit signed range. typedef duk_idx_t = duk_int_t; typedef duk_int_t = ffi.Int; typedef Dartduk_int_t = int; final class duk_number_list_entry extends ffi.Struct { external ffi.Pointer<ffi.Char> key; @duk_double_t() external double value; } typedef duk_double_t = ffi.Double; typedef Dartduk_double_t = double; final class duk_time_components extends ffi.Struct { /// year, e.g. 2016, ECMAScript year range @duk_double_t() external double year; /// month: 1-12 @duk_double_t() external double month; /// day: 1-31 @duk_double_t() external double day; /// hour: 0-59 @duk_double_t() external double hours; /// minute: 0-59 @duk_double_t() external double minutes; /// second: 0-59 (in POSIX time no leap second) @duk_double_t() external double seconds; /// may contain sub-millisecond fractions @duk_double_t() external double milliseconds; /// weekday: 0-6, 0=Sunday, 1=Monday, ..., 6=Saturday @duk_double_t() external double weekday; } typedef duk_fatal_function = ffi.Pointer<ffi.NativeFunction<duk_fatal_functionFunction>>; typedef duk_fatal_functionFunction = ffi.Void Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> msg); typedef Dartduk_fatal_functionFunction = void Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> msg); typedef duk_uint_t = ffi.UnsignedInt; typedef Dartduk_uint_t = int; /// Error codes are represented with platform int. High bits are used /// for flags and such, so 32 bits are needed. typedef duk_errcode_t = duk_int_t; typedef va_list = __builtin_va_list; typedef __builtin_va_list = ffi.Pointer<ffi.Char>; /// Boolean values are represented with the platform 'unsigned int'. typedef duk_bool_t = duk_small_uint_t; typedef duk_small_uint_t = ffi.UnsignedInt; typedef Dartduk_small_uint_t = int; typedef duk_int32_t = ffi.Int32; typedef Dartduk_int32_t = int; typedef duk_uint32_t = ffi.Uint32; typedef Dartduk_uint32_t = int; typedef duk_uint16_t = ffi.Uint16; typedef Dartduk_uint16_t = int; /// Array index values, could be exact 32 bits. /// Currently no need for signed duk_arridx_t. typedef duk_uarridx_t = duk_uint_t; typedef duk_decode_char_function = ffi.Pointer<ffi.NativeFunction<duk_decode_char_functionFunction>>; typedef duk_decode_char_functionFunction = ffi.Void Function( ffi.Pointer<ffi.Void> udata, duk_codepoint_t codepoint); typedef Dartduk_decode_char_functionFunction = void Function( ffi.Pointer<ffi.Void> udata, Dartduk_int_t codepoint); /// Codepoint type. Must be 32 bits or more because it is used also for /// internal codepoints. The type is signed because negative codepoints /// are used as internal markers (e.g. to mark EOF or missing argument). /// (X)UTF-8/CESU-8 encode/decode take and return an unsigned variant to /// ensure duk_uint32_t casts back and forth nicely. Almost everything /// else uses the signed one. typedef duk_codepoint_t = duk_int_t; typedef duk_map_char_function = ffi.Pointer<ffi.NativeFunction<duk_map_char_functionFunction>>; typedef duk_map_char_functionFunction = duk_codepoint_t Function( ffi.Pointer<ffi.Void> udata, duk_codepoint_t codepoint); typedef Dartduk_map_char_functionFunction = Dartduk_int_t Function( ffi.Pointer<ffi.Void> udata, Dartduk_int_t codepoint); typedef duk_safe_call_function = ffi.Pointer<ffi.NativeFunction<duk_safe_call_functionFunction>>; typedef duk_safe_call_functionFunction = duk_ret_t Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata); typedef Dartduk_safe_call_functionFunction = Dartduk_small_int_t Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata); typedef duk_debug_read_function = ffi.Pointer<ffi.NativeFunction<duk_debug_read_functionFunction>>; typedef duk_debug_read_functionFunction = duk_size_t Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> buffer, duk_size_t length); typedef Dartduk_debug_read_functionFunction = Dartduk_size_t Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> buffer, Dartduk_size_t length); typedef duk_debug_write_function = ffi.Pointer<ffi.NativeFunction<duk_debug_write_functionFunction>>; typedef duk_debug_write_functionFunction = duk_size_t Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> buffer, duk_size_t length); typedef Dartduk_debug_write_functionFunction = Dartduk_size_t Function( ffi.Pointer<ffi.Void> udata, ffi.Pointer<ffi.Char> buffer, Dartduk_size_t length); typedef duk_debug_peek_function = ffi.Pointer<ffi.NativeFunction<duk_debug_peek_functionFunction>>; typedef duk_debug_peek_functionFunction = duk_size_t Function( ffi.Pointer<ffi.Void> udata); typedef Dartduk_debug_peek_functionFunction = Dartduk_size_t Function( ffi.Pointer<ffi.Void> udata); typedef duk_debug_read_flush_function = ffi.Pointer<ffi.NativeFunction<duk_debug_read_flush_functionFunction>>; typedef duk_debug_read_flush_functionFunction = ffi.Void Function( ffi.Pointer<ffi.Void> udata); typedef Dartduk_debug_read_flush_functionFunction = void Function( ffi.Pointer<ffi.Void> udata); typedef duk_debug_write_flush_function = ffi.Pointer<ffi.NativeFunction<duk_debug_write_flush_functionFunction>>; typedef duk_debug_write_flush_functionFunction = ffi.Void Function( ffi.Pointer<ffi.Void> udata); typedef Dartduk_debug_write_flush_functionFunction = void Function( ffi.Pointer<ffi.Void> udata); typedef duk_debug_request_function = ffi.Pointer<ffi.NativeFunction<duk_debug_request_functionFunction>>; typedef duk_debug_request_functionFunction = duk_idx_t Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata, duk_idx_t nvalues); typedef Dartduk_debug_request_functionFunction = Dartduk_int_t Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata, Dartduk_int_t nvalues); typedef duk_debug_detached_function = ffi.Pointer<ffi.NativeFunction<duk_debug_detached_functionFunction>>; typedef duk_debug_detached_functionFunction = ffi.Void Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata); typedef Dartduk_debug_detached_functionFunction = void Function( ffi.Pointer<duk_context> ctx, ffi.Pointer<ffi.Void> udata); const int DUK_VERSION = 20700; const String DUK_GIT_COMMIT = '03d4d728f8365021de6955c649e6dcd05dcca99f'; const String DUK_GIT_DESCRIBE = '03d4d72-dirty'; const String DUK_GIT_BRANCH = 'HEAD'; const int DUK_DEBUG_PROTOCOL_VERSION = 2; const int DUK_INVALID_INDEX = -2147483648; const int DUK_VARARGS = -1; const int DUK_API_ENTRY_STACK = 64; const int DUK_TYPE_MIN = 0; const int DUK_TYPE_NONE = 0; const int DUK_TYPE_UNDEFINED = 1; const int DUK_TYPE_NULL = 2; const int DUK_TYPE_BOOLEAN = 3; const int DUK_TYPE_NUMBER = 4; const int DUK_TYPE_STRING = 5; const int DUK_TYPE_OBJECT = 6; const int DUK_TYPE_BUFFER = 7; const int DUK_TYPE_POINTER = 8; const int DUK_TYPE_LIGHTFUNC = 9; const int DUK_TYPE_MAX = 9; const int DUK_TYPE_MASK_NONE = 1; const int DUK_TYPE_MASK_UNDEFINED = 2; const int DUK_TYPE_MASK_NULL = 4; const int DUK_TYPE_MASK_BOOLEAN = 8; const int DUK_TYPE_MASK_NUMBER = 16; const int DUK_TYPE_MASK_STRING = 32; const int DUK_TYPE_MASK_OBJECT = 64; const int DUK_TYPE_MASK_BUFFER = 128; const int DUK_TYPE_MASK_POINTER = 256; const int DUK_TYPE_MASK_LIGHTFUNC = 512; const int DUK_TYPE_MASK_THROW = 1024; const int DUK_TYPE_MASK_PROMOTE = 2048; const int DUK_HINT_NONE = 0; const int DUK_HINT_STRING = 1; const int DUK_HINT_NUMBER = 2; const int DUK_ENUM_INCLUDE_NONENUMERABLE = 1; const int DUK_ENUM_INCLUDE_HIDDEN = 2; const int DUK_ENUM_INCLUDE_SYMBOLS = 4; const int DUK_ENUM_EXCLUDE_STRINGS = 8; const int DUK_ENUM_OWN_PROPERTIES_ONLY = 16; const int DUK_ENUM_ARRAY_INDICES_ONLY = 32; const int DUK_ENUM_SORT_ARRAY_INDICES = 64; const int DUK_ENUM_NO_PROXY_BEHAVIOR = 128; const int DUK_COMPILE_EVAL = 8; const int DUK_COMPILE_FUNCTION = 16; const int DUK_COMPILE_STRICT = 32; const int DUK_COMPILE_SHEBANG = 64; const int DUK_COMPILE_SAFE = 128; const int DUK_COMPILE_NORESULT = 256; const int DUK_COMPILE_NOSOURCE = 512; const int DUK_COMPILE_STRLEN = 1024; const int DUK_COMPILE_NOFILENAME = 2048; const int DUK_COMPILE_FUNCEXPR = 4096; const int DUK_DEFPROP_WRITABLE = 1; const int DUK_DEFPROP_ENUMERABLE = 2; const int DUK_DEFPROP_CONFIGURABLE = 4; const int DUK_DEFPROP_HAVE_WRITABLE = 8; const int DUK_DEFPROP_HAVE_ENUMERABLE = 16; const int DUK_DEFPROP_HAVE_CONFIGURABLE = 32; const int DUK_DEFPROP_HAVE_VALUE = 64; const int DUK_DEFPROP_HAVE_GETTER = 128; const int DUK_DEFPROP_HAVE_SETTER = 256; const int DUK_DEFPROP_FORCE = 512; const int DUK_DEFPROP_SET_WRITABLE = 9; const int DUK_DEFPROP_CLEAR_WRITABLE = 8; const int DUK_DEFPROP_SET_ENUMERABLE = 18; const int DUK_DEFPROP_CLEAR_ENUMERABLE = 16; const int DUK_DEFPROP_SET_CONFIGURABLE = 36; const int DUK_DEFPROP_CLEAR_CONFIGURABLE = 32; const int DUK_DEFPROP_W = 1; const int DUK_DEFPROP_E = 2; const int DUK_DEFPROP_C = 4; const int DUK_DEFPROP_WE = 3; const int DUK_DEFPROP_WC = 5; const int DUK_DEFPROP_EC = 6; const int DUK_DEFPROP_WEC = 7; const int DUK_DEFPROP_HAVE_W = 8; const int DUK_DEFPROP_HAVE_E = 16; const int DUK_DEFPROP_HAVE_C = 32; const int DUK_DEFPROP_HAVE_WE = 24; const int DUK_DEFPROP_HAVE_WC = 40; const int DUK_DEFPROP_HAVE_EC = 48; const int DUK_DEFPROP_HAVE_WEC = 56; const int DUK_DEFPROP_SET_W = 9; const int DUK_DEFPROP_SET_E = 18; const int DUK_DEFPROP_SET_C = 36; const int DUK_DEFPROP_SET_WE = 27; const int DUK_DEFPROP_SET_WC = 45; const int DUK_DEFPROP_SET_EC = 54; const int DUK_DEFPROP_SET_WEC = 63; const int DUK_DEFPROP_CLEAR_W = 8; const int DUK_DEFPROP_CLEAR_E = 16; const int DUK_DEFPROP_CLEAR_C = 32; const int DUK_DEFPROP_CLEAR_WE = 24; const int DUK_DEFPROP_CLEAR_WC = 40; const int DUK_DEFPROP_CLEAR_EC = 48; const int DUK_DEFPROP_CLEAR_WEC = 56; const int DUK_DEFPROP_ATTR_W = 57; const int DUK_DEFPROP_ATTR_E = 58; const int DUK_DEFPROP_ATTR_C = 60; const int DUK_DEFPROP_ATTR_WE = 59; const int DUK_DEFPROP_ATTR_WC = 61; const int DUK_DEFPROP_ATTR_EC = 62; const int DUK_DEFPROP_ATTR_WEC = 63; const int DUK_THREAD_NEW_GLOBAL_ENV = 1; const int DUK_GC_COMPACT = 1; const int DUK_ERR_NONE = 0; const int DUK_ERR_ERROR = 1; const int DUK_ERR_EVAL_ERROR = 2; const int DUK_ERR_RANGE_ERROR = 3; const int DUK_ERR_REFERENCE_ERROR = 4; const int DUK_ERR_SYNTAX_ERROR = 5; const int DUK_ERR_TYPE_ERROR = 6; const int DUK_ERR_URI_ERROR = 7; const int DUK_RET_ERROR = -1; const int DUK_RET_EVAL_ERROR = -2; const int DUK_RET_RANGE_ERROR = -3; const int DUK_RET_REFERENCE_ERROR = -4; const int DUK_RET_SYNTAX_ERROR = -5; const int DUK_RET_TYPE_ERROR = -6; const int DUK_RET_URI_ERROR = -7; const int DUK_EXEC_SUCCESS = 0; const int DUK_EXEC_ERROR = 1; const int DUK_LEVEL_DEBUG = 0; const int DUK_LEVEL_DDEBUG = 1; const int DUK_LEVEL_DDDEBUG = 2; const int DUK_BUF_FLAG_DYNAMIC = 1; const int DUK_BUF_FLAG_EXTERNAL = 2; const int DUK_BUF_FLAG_NOZERO = 4; const int DUK_BUFOBJ_ARRAYBUFFER = 0; const int DUK_BUFOBJ_NODEJS_BUFFER = 1; const int DUK_BUFOBJ_DATAVIEW = 2; const int DUK_BUFOBJ_INT8ARRAY = 3; const int DUK_BUFOBJ_UINT8ARRAY = 4; const int DUK_BUFOBJ_UINT8CLAMPEDARRAY = 5; const int DUK_BUFOBJ_INT16ARRAY = 6; const int DUK_BUFOBJ_UINT16ARRAY = 7; const int DUK_BUFOBJ_INT32ARRAY = 8; const int DUK_BUFOBJ_UINT32ARRAY = 9; const int DUK_BUFOBJ_FLOAT32ARRAY = 10; const int DUK_BUFOBJ_FLOAT64ARRAY = 11; const int DUK_BUF_MODE_FIXED = 0; const int DUK_BUF_MODE_DYNAMIC = 1; const int DUK_BUF_MODE_DONTCARE = 2; const int DUK_DATE_MSEC_SECOND = 1000; const int DUK_DATE_MSEC_MINUTE = 60000; const int DUK_DATE_MSEC_HOUR = 3600000; const int DUK_DATE_MSEC_DAY = 86400000; const double DUK_DATE_MSEC_100M_DAYS = 8640000000000000.0; const double DUK_DATE_MSEC_100M_DAYS_LEEWAY = 8640000086400000.0; const int DUK_DATE_MIN_ECMA_YEAR = -271821; const int DUK_DATE_MAX_ECMA_YEAR = 275760; const int DUK_DATE_IDX_YEAR = 0; const int DUK_DATE_IDX_MONTH = 1; const int DUK_DATE_IDX_DAY = 2; const int DUK_DATE_IDX_HOUR = 3; const int DUK_DATE_IDX_MINUTE = 4; const int DUK_DATE_IDX_SECOND = 5; const int DUK_DATE_IDX_MILLISECOND = 6; const int DUK_DATE_IDX_WEEKDAY = 7; const int DUK_DATE_IDX_NUM_PARTS = 8; const int DUK_DATE_FLAG_NAN_TO_ZERO = 1; const int DUK_DATE_FLAG_NAN_TO_RANGE_ERROR = 2; const int DUK_DATE_FLAG_ONEBASED = 4; const int DUK_DATE_FLAG_EQUIVYEAR = 8; const int DUK_DATE_FLAG_LOCALTIME = 16; const int DUK_DATE_FLAG_SUB1900 = 32; const int DUK_DATE_FLAG_TOSTRING_DATE = 64; const int DUK_DATE_FLAG_TOSTRING_TIME = 128; const int DUK_DATE_FLAG_TOSTRING_LOCALE = 256; const int DUK_DATE_FLAG_TIMESETTER = 512; const int DUK_DATE_FLAG_YEAR_FIXUP = 1024; const int DUK_DATE_FLAG_SEP_T = 2048; const int DUK_DATE_FLAG_VALUE_SHIFT = 12;
codelabs/ffigen_codelab/step_05/lib/duktape_bindings_generated.dart/0
{'file_path': 'codelabs/ffigen_codelab/step_05/lib/duktape_bindings_generated.dart', 'repo_id': 'codelabs', 'token_count': 77866}
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'app_state.dart'; import 'firebase_options.dart'; import 'logged_in_view.dart'; import 'logged_out_view.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); if (kDebugMode) { try { FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080); await FirebaseAuth.instance.useAuthEmulator('localhost', 9099); } catch (e) { // ignore: avoid_print print(e); } } runApp(MyApp()); } class MyApp extends StatelessWidget { final state = AppState(); MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( scrollBehavior: AppScrollBehavior(), routerConfig: _router(), theme: ThemeData(useMaterial3: true), ); } GoRouter _router() { return GoRouter( redirect: (context, routerState) => state.user == null ? '/login' : null, routes: [ GoRoute( path: '/', builder: (context, routerState) => LoggedInView(state: state), ), GoRoute( path: '/login', builder: (context, routerState) => LoggedOutView(state: state), ), ], ); } } class AppScrollBehavior extends MaterialScrollBehavior { @override Set<PointerDeviceKind> get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, }; }
codelabs/firebase-emulator-suite/complete/lib/main.dart/0
{'file_path': 'codelabs/firebase-emulator-suite/complete/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 693}
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'app_state.dart'; import 'logged_in_view.dart'; import 'logged_out_view.dart'; void main() async { // TODO: Initialize Firebase runApp(MyApp()); } class MyApp extends StatelessWidget { final state = AppState(); MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( scrollBehavior: AppScrollBehavior(), routerConfig: _router(), theme: ThemeData(useMaterial3: true), ); } GoRouter _router() { return GoRouter( redirect: (context, routerState) => state.user == null ? '/login' : null, routes: [ GoRoute( path: '/', builder: (context, routerState) => LoggedInView(state: state), ), GoRoute( path: '/login', builder: (context, routerState) => LoggedOutView(state: state), ), ], ); } } class AppScrollBehavior extends MaterialScrollBehavior { @override Set<PointerDeviceKind> get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, }; }
codelabs/firebase-emulator-suite/start/lib/main.dart/0
{'file_path': 'codelabs/firebase-emulator-suite/start/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 483}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'src/widgets.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Firebase Meetup'), ), body: ListView( children: <Widget>[ Image.asset('assets/codelab.png'), const SizedBox(height: 8), const IconAndDetail(Icons.calendar_today, 'October 30'), const IconAndDetail(Icons.location_city, 'San Francisco'), const Divider( height: 8, thickness: 1, indent: 8, endIndent: 8, color: Colors.grey, ), const Header("What we'll be doing"), const Paragraph( 'Join us for a day full of Firebase Workshops and Pizza!', ), ], ), ); } }
codelabs/firebase-get-to-know-flutter/step_04/lib/home_page.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_04/lib/home_page.dart', 'repo_id': 'codelabs', 'token_count': 477}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider, PhoneAuthProvider; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:flutter/material.dart'; import 'firebase_options.dart'; import 'guest_book_message.dart'; class ApplicationState extends ChangeNotifier { ApplicationState() { init(); } bool _loggedIn = false; bool get loggedIn => _loggedIn; StreamSubscription<QuerySnapshot>? _guestBookSubscription; List<GuestBookMessage> _guestBookMessages = []; List<GuestBookMessage> get guestBookMessages => _guestBookMessages; Future<void> init() async { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); FirebaseUIAuth.configureProviders([ EmailAuthProvider(), ]); FirebaseAuth.instance.userChanges().listen((user) { if (user != null) { _loggedIn = true; _guestBookSubscription = FirebaseFirestore.instance .collection('guestbook') .orderBy('timestamp', descending: true) .snapshots() .listen((snapshot) { _guestBookMessages = []; for (final document in snapshot.docs) { _guestBookMessages.add( GuestBookMessage( name: document.data()['name'] as String, message: document.data()['text'] as String, ), ); } notifyListeners(); }); } else { _loggedIn = false; _guestBookMessages = []; _guestBookSubscription?.cancel(); } notifyListeners(); }); } Future<DocumentReference> addMessageToGuestBook(String message) { if (!_loggedIn) { throw Exception('Must be logged in'); } return FirebaseFirestore.instance .collection('guestbook') .add(<String, dynamic>{ 'text': message, 'timestamp': DateTime.now().millisecondsSinceEpoch, 'name': FirebaseAuth.instance.currentUser!.displayName, 'userId': FirebaseAuth.instance.currentUser!.uid, }); } }
codelabs/firebase-get-to-know-flutter/step_07/lib/app_state.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_07/lib/app_state.dart', 'repo_id': 'codelabs', 'token_count': 953}
include: ../../analysis_options.yaml
codelabs/firebase-get-to-know-flutter/step_09/analysis_options.yaml/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_09/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // GENERATED CODE - DO NOT MODIFY BY HAND part of 'locations.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** LatLng _$LatLngFromJson(Map<String, dynamic> json) => LatLng( lat: (json['lat'] as num).toDouble(), lng: (json['lng'] as num).toDouble(), ); Map<String, dynamic> _$LatLngToJson(LatLng instance) => <String, dynamic>{ 'lat': instance.lat, 'lng': instance.lng, }; Region _$RegionFromJson(Map<String, dynamic> json) => Region( coords: LatLng.fromJson(json['coords'] as Map<String, dynamic>), id: json['id'] as String, name: json['name'] as String, zoom: (json['zoom'] as num).toDouble(), ); Map<String, dynamic> _$RegionToJson(Region instance) => <String, dynamic>{ 'coords': instance.coords, 'id': instance.id, 'name': instance.name, 'zoom': instance.zoom, }; Office _$OfficeFromJson(Map<String, dynamic> json) => Office( address: json['address'] as String, id: json['id'] as String, image: json['image'] as String, lat: (json['lat'] as num).toDouble(), lng: (json['lng'] as num).toDouble(), name: json['name'] as String, phone: json['phone'] as String, region: json['region'] as String, ); Map<String, dynamic> _$OfficeToJson(Office instance) => <String, dynamic>{ 'address': instance.address, 'id': instance.id, 'image': instance.image, 'lat': instance.lat, 'lng': instance.lng, 'name': instance.name, 'phone': instance.phone, 'region': instance.region, }; Locations _$LocationsFromJson(Map<String, dynamic> json) => Locations( offices: (json['offices'] as List<dynamic>) .map((e) => Office.fromJson(e as Map<String, dynamic>)) .toList(), regions: (json['regions'] as List<dynamic>) .map((e) => Region.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$LocationsToJson(Locations instance) => <String, dynamic>{ 'offices': instance.offices, 'regions': instance.regions, };
codelabs/google-maps-in-flutter/step_5/lib/src/locations.g.dart/0
{'file_path': 'codelabs/google-maps-in-flutter/step_5/lib/src/locations.g.dart', 'repo_id': 'codelabs', 'token_count': 1040}
import 'package:flutter/material.dart'; class Shimmer extends StatefulWidget { const Shimmer({ super.key, required this.linearGradient, this.child, }); static ShimmerState? of(BuildContext context) { return context.findAncestorStateOfType<ShimmerState>(); } final LinearGradient linearGradient; final Widget? child; @override ShimmerState createState() => ShimmerState(); } class ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin { late AnimationController shimmerController; @override void initState() { super.initState(); shimmerController = AnimationController.unbounded(vsync: this) ..repeat(min: -0.5, max: 1.5, period: const Duration(milliseconds: 1000)); } @override void dispose() { shimmerController.dispose(); super.dispose(); } LinearGradient get gradient => LinearGradient( colors: widget.linearGradient.colors, stops: widget.linearGradient.stops, begin: widget.linearGradient.begin, end: widget.linearGradient.end, transform: SlidingGradientTransform(slidePercent: shimmerController.value), ); bool get isSized { if (context.findRenderObject() != null) { return (context.findRenderObject()! as RenderBox).hasSize; } else { return false; } } Size get size => (context.findRenderObject()! as RenderBox).size; Offset getDescendantOffset({ required RenderBox descendant, Offset offset = Offset.zero, }) { final RenderBox shimmerBox = context.findRenderObject()! as RenderBox; return descendant.localToGlobal(offset, ancestor: shimmerBox); } Listenable get shimmerChanges => shimmerController; @override Widget build(BuildContext context) { return widget.child ?? const SizedBox(); } } class SlidingGradientTransform extends GradientTransform { const SlidingGradientTransform({ required this.slidePercent, }); final double slidePercent; @override Matrix4? transform(Rect bounds, {TextDirection? textDirection}) { return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0); } } class ShimmerLoading extends StatefulWidget { const ShimmerLoading({ super.key, required this.isLoading, required this.child, }); final bool isLoading; final Widget child; @override State<ShimmerLoading> createState() => ShimmerLoadingState(); } class ShimmerLoadingState extends State<ShimmerLoading> { Listenable? shimmerChanges; @override void didChangeDependencies() { super.didChangeDependencies(); if (shimmerChanges != null) { shimmerChanges!.removeListener(onShimmerChange); } shimmerChanges = Shimmer.of(context)?.shimmerChanges; if (shimmerChanges != null) { shimmerChanges!.addListener(onShimmerChange); } } @override void dispose() { shimmerChanges?.removeListener(onShimmerChange); super.dispose(); } void onShimmerChange() { if (widget.isLoading) { setState(() { // update the shimmer painting. }); } } @override Widget build(BuildContext context) { if (!widget.isLoading) { return widget.child; } // Collect ancestor shimmer info. final ShimmerState shimmer = Shimmer.of(context)!; if (!shimmer.isSized) { // The ancestor Shimmer widget has not laid // itself out yet. Return an empty box. return const SizedBox(); } final Size shimmerSize = shimmer.size; final LinearGradient gradient = shimmer.gradient; final Offset offsetWithinShimmer = shimmer.getDescendantOffset( descendant: context.findRenderObject()! as RenderBox, ); return ShaderMask( blendMode: BlendMode.srcATop, shaderCallback: (Rect bounds) { return gradient.createShader( Rect.fromLTWH( -offsetWithinShimmer.dx, -offsetWithinShimmer.dy, shimmerSize.width, shimmerSize.height, ), ); }, child: widget.child, ); } }
codelabs/haiku_generator/finished/lib/widgets/shimmer_loading.dart/0
{'file_path': 'codelabs/haiku_generator/finished/lib/widgets/shimmer_loading.dart', 'repo_id': 'codelabs', 'token_count': 1440}
import '../data/repositories/product_repository_impl.dart'; import '../domain/models/product.dart'; import '../domain/repositories/abstract/product_repository.dart'; class ProductController { final ProductRepository productRepository = ProductRepositoryImpl(); Future<List<Product>> getProducts() { return productRepository.getAllProducts(); } }
codelabs/haiku_generator/step0/lib/controller/product_controller.dart/0
{'file_path': 'codelabs/haiku_generator/step0/lib/controller/product_controller.dart', 'repo_id': 'codelabs', 'token_count': 109}
import 'package:flutter/material.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:provider/provider.dart'; import 'logic/dash_counter.dart'; import 'logic/dash_purchases.dart'; import 'logic/dash_upgrades.dart'; import 'logic/firebase_notifier.dart'; import 'pages/home_page.dart'; import 'pages/purchase_page.dart'; import 'repo/iap_repo.dart'; // Gives the option to override in tests. class IAPConnection { static InAppPurchase? _instance; static set instance(InAppPurchase value) { _instance = value; } static InAppPurchase get instance { _instance ??= InAppPurchase.instance; return _instance!; } } void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Dash Clicker', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Dash Clicker'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } typedef PageBuilder = Widget Function(); class _MyHomePageState extends State<MyHomePage> { int _selectedIndex = 0; static final List<Widget> _widgetOptions = [ const HomePage(), const PurchasePage(), ]; @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<FirebaseNotifier>( create: (_) => FirebaseNotifier()), ChangeNotifierProvider<DashCounter>(create: (_) => DashCounter()), ChangeNotifierProvider<DashUpgrades>( create: (context) => DashUpgrades( context.read<DashCounter>(), context.read<FirebaseNotifier>(), ), ), ChangeNotifierProvider<IAPRepo>( create: (context) => IAPRepo(context.read<FirebaseNotifier>()), ), ChangeNotifierProvider<DashPurchases>( create: (context) => DashPurchases( context.read<DashCounter>(), context.read<FirebaseNotifier>(), context.read<IAPRepo>(), ), lazy: false, ), ], child: Scaffold( appBar: AppBar( title: Text(widget.title), ), body: _widgetOptions[_selectedIndex], bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.shop), label: 'Purchase', ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: (index) => setState(() => _selectedIndex = index), ), ), ); } }
codelabs/in_app_purchases/complete/app/lib/main.dart/0
{'file_path': 'codelabs/in_app_purchases/complete/app/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 1283}
// Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:flutter/material.dart'; import 'package:particle_field/particle_field.dart'; import 'package:rnd/rnd.dart'; class ParticleOverlay extends StatelessWidget { const ParticleOverlay({super.key, required this.color, required this.energy}); final Color color; final double energy; @override Widget build(BuildContext context) { return ParticleField( spriteSheet: SpriteSheet( image: const AssetImage('assets/images/particle-wave.png'), ), // blend the image's alpha with the specified color: blendMode: BlendMode.dstIn, // this runs every tick: onTick: (controller, _, size) { List<Particle> particles = controller.particles; // add a new particle with random angle, distance & velocity: double a = rnd(pi * 2); double dist = rnd(1, 4) * 35 + 150 * energy; double vel = rnd(1, 2) * (1 + energy * 1.8); particles.add(Particle( // how many ticks this particle will live: lifespan: rnd(1, 2) * 20 + energy * 15, // starting distance from center: x: cos(a) * dist, y: sin(a) * dist, // starting velocity: vx: cos(a) * vel, vy: sin(a) * vel, // other starting values: rotation: a, scale: rnd(1, 2) * 0.6 + energy * 0.5, )); // update all of the particles: for (int i = particles.length - 1; i >= 0; i--) { Particle p = particles[i]; if (p.lifespan <= 0) { // particle is expired, remove it: particles.removeAt(i); continue; } p.update( scale: p.scale * 1.025, vx: p.vx * 1.025, vy: p.vy * 1.025, color: color.withOpacity(p.lifespan * 0.001 + 0.01), lifespan: p.lifespan - 1, ); } }, ); } }
codelabs/next-gen-ui/step_06/lib/title_screen/particle_overlay.dart/0
{'file_path': 'codelabs/next-gen-ui/step_06/lib/title_screen/particle_overlay.dart', 'repo_id': 'codelabs', 'token_count': 946}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:io/io.dart' as io; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'blueprint.dart'; final _logger = Logger('rebuild_blueprint'); Future<void> rebuildFromBlueprint(Directory cwd, Blueprint blueprint) async { _logger.info(blueprint.name); if (!blueprint.isValid) { _logger.warning('Invalid blueprint'); exit(-1); } for (final step in blueprint.steps) { await _buildBlueprintStep(cwd, step); } } Future<void> _buildBlueprintStep(Directory cwd, BlueprintStep step) async { _logger.info(step.name); final stop = step.stop; if (stop != null && stop == true) { _logger.info('Stopping.'); exit(0); } final platforms = step.platforms; if (platforms != null) { if (!platforms.contains(Platform.operatingSystem)) { _logger.info( 'Skipping because ${Platform.operatingSystem} is not in [${platforms.join(',')}].'); return; } } final steps = step.steps; if (steps.isNotEmpty) { for (final subStep in steps) { await _buildBlueprintStep(cwd, subStep); } return; } if (step.mkdir != null || step.mkdirs.isNotEmpty) { final dir = step.mkdir; if (dir != null) { _mkdir( step.path != null ? p.join(cwd.path, step.path, dir) : p.join(cwd.path, dir), step: step); } else { for (final dir in step.mkdirs) { _mkdir( step.path != null ? p.join(cwd.path, step.path, dir) : p.join(cwd.path, dir), step: step); } } return; } if (step.rmdir != null || step.rmdirs.isNotEmpty) { final dir = step.rmdir; if (dir != null) { _rmdir( step.path != null ? p.join(cwd.path, step.path, dir) : p.join(cwd.path, dir), step: step); } else { for (final dir in step.rmdirs) { _rmdir( step.path != null ? p.join(cwd.path, step.path, dir) : p.join(cwd.path, dir), step: step); } } return; } final rename = step.rename; if (rename != null) { if (step.path != null) { _rename( from: p.join(cwd.path, step.path, rename.from), to: p.join(cwd.path, step.path, rename.to), step: step); } else { _rename( from: p.join(cwd.path, rename.from), to: p.join(cwd.path, rename.to), step: step); } return; } final cpdir = step.copydir; if (cpdir != null) { if (step.path != null) { _cpdir( from: p.join(cwd.path, step.path, cpdir.from), to: p.join(cwd.path, step.path, cpdir.to), step: step); } else { _cpdir( from: p.join(cwd.path, cpdir.from), to: p.join(cwd.path, cpdir.to), step: step); } return; } final cp = step.copy; if (cp != null) { if (step.path != null) { _cp( from: p.join(cwd.path, step.path, cp.from), to: p.join(cwd.path, step.path, cp.to), step: step); } else { _cp( from: p.join(cwd.path, cp.from), to: p.join(cwd.path, cp.to), step: step); } return; } final rm = step.rm; if (rm != null) { late final File target; if (step.path != null) { target = File(p.join(cwd.path, step.path, rm)); } else { target = File(p.join(cwd.path, rm)); } if (!target.existsSync()) { _logger.severe("File ${target.path} doesn't exist: ${step.name}"); exit(-1); } target.deleteSync(); return; } final retrieveUrl = step.retrieveUrl; if (retrieveUrl != null) { final request = await HttpClient().getUrl(Uri.parse(retrieveUrl)); final response = await request.close(); await response.pipe(File(p.join(cwd.path, step.path!)).openWrite()); return; } final pod = step.pod; if (pod != null) { await _runNamedCommand( command: 'pod', step: step, cwd: cwd, args: pod, exitOnStdErr: false, // pod update writes lots of warnings we ignore ); return; } final dart = step.dart; if (dart != null) { await _runNamedCommand( command: 'dart', step: step, cwd: cwd, args: dart, ); return; } final flutter = step.flutter; if (flutter != null) { await _runNamedCommand( command: 'flutter', step: step, cwd: cwd, args: flutter, exitOnStdErr: false, // flutter prints status info to stderr. ); return; } final git = step.git; if (git != null) { await _runNamedCommand( command: 'git', step: step, cwd: cwd, args: git, exitOnStdErr: false, // git prints status info to stderr. Sigh. ); return; } final tar = step.tar; if (tar != null) { await _runNamedCommand( command: 'tar', step: step, cwd: cwd, args: tar, ); return; } final sevenZip = step.sevenZip; if (sevenZip != null) { await _runNamedCommand( command: '7z', step: step, cwd: cwd, args: sevenZip, ); return; } final stripLinesContaining = step.stripLinesContaining; if (stripLinesContaining != null) { final target = File(p.join(cwd.path, step.path)); final lines = target.readAsLinesSync(); lines.removeWhere((line) => line.contains(stripLinesContaining)); final buff = StringBuffer(); for (final line in lines) { buff.writeln(line); } target.writeAsStringSync(buff.toString()); return; } final xcodeAddFile = step.xcodeAddFile; final xcodeProjectPath = step.xcodeProjectPath; if (xcodeAddFile != null && xcodeProjectPath != null) { final script = ''' require "xcodeproj" project = Xcodeproj::Project.open("$xcodeProjectPath") group = project.main_group["Runner"] project.targets.first.add_file_references([group.new_file("$xcodeAddFile")]) project.save ''' .split('\n') .map((str) => "-e '$str'") .join(' '); await _runNamedCommand( command: 'ruby', step: step, cwd: cwd, args: script, exitOnStdErr: false); return; } final path = step.path; if (path == null) { _logger.severe( 'patch, base64-contents and replace-contents require a path: ${step.name}'); exit(-1); } final patch = step.patch; final patchU = step.patchU; final patchC = step.patchC; if (patch != null || patchC != null || patchU != null) { bool seenError = false; final fullPath = p.canonicalize(p.join(cwd.path, path)); if (!FileSystemEntity.isFileSync(fullPath)) { File(fullPath).createSync(); } late final Process process; if (patch != null) { process = await Process.start('patch', [fullPath], workingDirectory: cwd.path); } else if (patchC != null) { process = await Process.start('patch', ['-c', fullPath], workingDirectory: cwd.path); } else if (patchU != null) { process = await Process.start('patch', ['-u', fullPath], workingDirectory: cwd.path); } process.stderr.transform(utf8.decoder).listen((str) { seenError = true; _logger.warning(str.trimRight()); }); process.stdout.transform(utf8.decoder).listen((str) { _logger.info(str.trimRight()); }); process.stdin.write(patch ?? patchC ?? patchU); await process.stdin.flush(); await process.stdin.close(); final exitCode = await process.exitCode; if (exitCode != 0 || seenError) { _logger.severe('patch $fullPath failed.'); exit(-1); } return; } final base64Contents = step.base64Contents; if (base64Contents != null) { File(p.join(cwd.path, path)) .writeAsBytesSync(base64Decode(base64Contents.split('\n').join(''))); return; } final replaceContents = step.replaceContents; if (replaceContents != null) { File(p.join(cwd.path, path)).writeAsStringSync(replaceContents); return; } // Shouldn't get this far. _logger.severe('Invalid step: ${step.name}'); exit(-1); } Future<void> _runNamedCommand({ required String command, required BlueprintStep step, required Directory cwd, required String args, bool exitOnStdErr = true, }) async { var seenStdErr = false; final String workingDirectory = p .canonicalize(step.path != null ? p.join(cwd.path, step.path) : cwd.path); final shellSplit = io.shellSplit(args); final process = await Process.start( command, shellSplit, workingDirectory: workingDirectory, runInShell: true, ); process.stderr.transform(utf8.decoder).listen((str) { seenStdErr = true; _logger.warning(str.trimRight()); }); process.stdout.transform(utf8.decoder).listen((str) { _logger.info(str.trimRight()); }); final exitCode = await process.exitCode; if (exitCode != 0 || exitOnStdErr && seenStdErr) { _logger.severe("'$command $args' failed"); exit(-1); } return; } void _rename({ required String from, required String to, required BlueprintStep step, }) { from = p.canonicalize(from); to = p.canonicalize(to); File(from).renameSync(to); } void _cpdir({ required String from, required String to, required BlueprintStep step, }) { from = p.canonicalize(from); to = p.canonicalize(to); if (!FileSystemEntity.isDirectorySync(from)) { _logger.warning("Invalid cpdir for '$from': ${step.name}"); } io.copyPathSync(from, to); } void _cp({ required String from, required String to, required BlueprintStep step, }) { from = p.canonicalize(from); to = p.canonicalize(to); if (!FileSystemEntity.isFileSync(from)) { _logger.warning("Invalid cp for '$from': ${step.name}"); } File(from).copySync(to); } void _rmdir(String dir, {required BlueprintStep step}) { dir = p.canonicalize(dir); if (!FileSystemEntity.isDirectorySync(dir)) { _logger.warning("Invalid rmdir for '$dir': ${step.name}"); } Directory(dir).deleteSync(recursive: true); } void _mkdir(String dir, {required BlueprintStep step}) { p.canonicalize(dir); Directory(dir).createSync(recursive: true); }
codelabs/tooling/codelab_rebuild/lib/src/rebuild_blueprint.dart/0
{'file_path': 'codelabs/tooling/codelab_rebuild/lib/src/rebuild_blueprint.dart', 'repo_id': 'codelabs', 'token_count': 4499}
name: codemagic_bloc_unit_tests description: A new Flutter project. version: 1.0.0+1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter equatable: ^0.6.1 flutter_bloc: ^2.0.0 meta: ^1.1.7 weather_repository: path: ./weather_repository dev_dependencies: flutter_test: sdk: flutter bloc_test: ^2.1.0 mockito: ^4.0.0 flutter: uses-material-design: true
codemagic_bloc_unit_tests/pubspec.yaml/0
{'file_path': 'codemagic_bloc_unit_tests/pubspec.yaml', 'repo_id': 'codemagic_bloc_unit_tests', 'token_count': 191}
name: replay_cubit on: push: branches: - master paths: - ".github/workflows/replay_cubit.yaml" - "packages/replay_cubit/**" pull_request: branches: - master paths: - ".github/workflows/replay_cubit.yaml" - "packages/replay_cubit/**" jobs: build: defaults: run: working-directory: packages/replay_cubit runs-on: ubuntu-latest container: image: google/dart:2.8.3 steps: - uses: actions/checkout@v2 - name: Install Dependencies run: pub get - name: Format run: dartfmt --dry-run --set-exit-if-changed . - name: Analyze run: dartanalyzer --fatal-infos --fatal-warnings lib test - name: Run tests run: pub run test_coverage - name: Check Code Coverage uses: ChicagoFlutter/lcov-cop@v1.0.0 with: path: packages/replay_cubit/coverage/lcov.info
cubit/.github/workflows/replay_cubit.yaml/0
{'file_path': 'cubit/.github/workflows/replay_cubit.yaml', 'repo_id': 'cubit', 'token_count': 444}
import 'package:angular/angular.dart'; import 'package:angular_counter/src/counter_page/counter_page_component.dart'; @Component( selector: 'my-app', templateUrl: 'app_component.html', directives: [CounterPageComponent], ) class AppComponent {}
cubit/examples/angular_counter/lib/app_component.dart/0
{'file_path': 'cubit/examples/angular_counter/lib/app_component.dart', 'repo_id': 'cubit', 'token_count': 79}
targets: $default: builders: json_serializable: options: field_rename: snake create_to_json: false checked: true
cubit/examples/flutter_weather/build.yaml/0
{'file_path': 'cubit/examples/flutter_weather/build.yaml', 'repo_id': 'cubit', 'token_count': 83}
import 'package:flutter/material.dart'; class CitySearch extends StatefulWidget { const CitySearch._({Key key}) : super(key: key); static Route<String> route() { return MaterialPageRoute( builder: (_) => const CitySearch._(), ); } @override State<CitySearch> createState() => _CitySearchState(); } class _CitySearchState extends State<CitySearch> { final TextEditingController _textController = TextEditingController(); String get _text => _textController.text; @override void dispose() { _textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('City Search')), body: Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: _textController, decoration: const InputDecoration( labelText: 'City', hintText: 'Chicago', ), ), ), ), IconButton( icon: const Icon(Icons.search), onPressed: () => Navigator.of(context).pop(_text), ) ], ), ); } }
cubit/examples/flutter_weather/lib/app/search/city_search.dart/0
{'file_path': 'cubit/examples/flutter_weather/lib/app/search/city_search.dart', 'repo_id': 'cubit', 'token_count': 576}
import 'package:cubit/cubit.dart'; class MyCubitObserver extends CubitObserver { @override void onTransition(Cubit cubit, Transition transition) { print(transition); super.onTransition(cubit, transition); } } void main() async { Cubit.observer = MyCubitObserver(); final cubit = CounterCubit()..increment(); await cubit.close(); } class CounterCubit extends Cubit<int> { CounterCubit() : super(0); void increment() => emit(state + 1); }
cubit/packages/cubit/example/main.dart/0
{'file_path': 'cubit/packages/cubit/example/main.dart', 'repo_id': 'cubit', 'token_count': 164}
import 'package:cubit/cubit.dart'; class MultiCounterCubit extends Cubit<int> { MultiCounterCubit() : super(0); void increment() { emit(state + 1); emit(state + 1); } }
cubit/packages/cubit_test/test/helpers/multi_counter_cubit.dart/0
{'file_path': 'cubit/packages/cubit_test/test/helpers/multi_counter_cubit.dart', 'repo_id': 'cubit', 'token_count': 73}
library flutter_cubit; export 'src/cubit_builder.dart'; export 'src/cubit_consumer.dart'; export 'src/cubit_listener.dart'; export 'src/cubit_provider.dart'; export 'src/multi_cubit_listener.dart'; export 'src/multi_cubit_provider.dart';
cubit/packages/flutter_cubit/lib/flutter_cubit.dart/0
{'file_path': 'cubit/packages/flutter_cubit/lib/flutter_cubit.dart', 'repo_id': 'cubit', 'token_count': 102}
library hydrated_cubit; export 'src/hydrated_cipher.dart'; export 'src/hydrated_cubit.dart'; export 'src/hydrated_storage.dart';
cubit/packages/hydrated_cubit/lib/hydrated_cubit.dart/0
{'file_path': 'cubit/packages/hydrated_cubit/lib/hydrated_cubit.dart', 'repo_id': 'cubit', 'token_count': 52}
void main(List<String> args) {}
dart-for-beginners-course/012_inheritance/main.dart/0
{'file_path': 'dart-for-beginners-course/012_inheritance/main.dart', 'repo_id': 'dart-for-beginners-course', 'token_count': 11}
/* * SPDX-FileCopyrightText: © Vegard IT GmbH (https://vegardit.com) and contributors * SPDX-FileContributor: Sebastian Thomschke, Vegard IT GmbH * SPDX-License-Identifier: Apache-2.0 */ library; String substringAfter(final String searchIn, final String searchFor) { if (searchIn.isEmpty) { return searchIn; } final pos = searchIn.indexOf(searchFor); return pos < 0 ? '' : searchIn.substring(pos + searchFor.length); }
dart-hotreloader/lib/src/util/strings.dart/0
{'file_path': 'dart-hotreloader/lib/src/util/strings.dart', 'repo_id': 'dart-hotreloader', 'token_count': 148}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async' show FutureOr; import 'dart:collection' show UnmodifiableListView; import 'package:meta/meta.dart' show sealed; Future<T> _defaultRunStep<T>(Step<T> step, Future<T> Function() fn) => fn(); /// A [RunStepWrapper] is a function that can wrap the [runStep] function. /// /// See the constructor of [Runner] for examples. typedef RunStepWrapper = Future<T> Function<T>( Step<T> step, Future<T> Function() runStep, ); /// A [Runner] can run a [Step] and its dependencies, caching the results of /// each step. /// /// A given [Step] is evaluated at-most once in a given [Runner]. Hence, if /// `stepA` and `stepB` both depends on `stepC`, evaluating the result of both /// `stepA` and `stepB` will not run `stepC` more than once. To run a step more /// than once, it is necessary to create a new [Runner] instance. /// /// It can sometimes be useful to _override_ the result of a specific [Step]. /// This can be achieved using the [override] method. When doing so a [Step] /// must be overwritten before it is evaluated. It is always safe to override /// steps before any calls to [run]. /// /// Overriding a [Step] causes the step to not be evaluated, and the overriden /// value to be used instead. This is useful when injecting initial options /// into an acyclic graph of steps, or when overriding specific components with /// mocks/fakes in a testing setup. @sealed class Runner { final Map<Step<Object?>, dynamic> _cache = {}; final RunStepWrapper _wrapRunStep; /// Create a [Runner] instance with an empty cache. /// /// The optional [wrapRunStep] parameters allows specification of a function /// that will wrap the `runStep` methods provided in the [Step] definitons. /// This can be used to catch exceptions, run steps in a zone, measure /// execution time of a step (excluding dependencies), or simply log step /// execution as illustrated in the example below. /// /// ```dart /// /// Define a step that return 'Hello World!' /// final helloWorldStep = Step.define('hello-world').build(() => 'Hello World!'); /// /// /// Define a step that depends on helloWorldStep and prints its return /// /// value. /// final Step<void> printStep = Step.define('print-msg') /// // Declare dependency on helloWorldStep /// .dep(helloWorldStep) /// // Build step, result from helloWorldStep will be passed in as `msg` /// .build((msg) { /// print(msg); /// }); /// /// /// Implementation of [RunStepWrapper] that logs start and finish for /// /// each step. /// Future<T> wrapStepWithLogging<T>( /// Step<T> step, /// Future<T> Function() runStep, /// ) async { /// print('Starting to run ${step.name}'); /// try { /// return await runStep(); /// } finally { /// print('Finishing running ${step.name}'); /// } /// } /// /// Future<void> main() async { /// // This creates a Runner that will wrap calls to runStep with /// // wrapStepWithLogging, hence, printing log entries for step execution. /// final r = Runner(wrapRunStep: wrapStepWithLogging); /// await r.run(printStep); /// } /// ``` Runner({ RunStepWrapper wrapRunStep = _defaultRunStep, }) : _wrapRunStep = wrapRunStep; /// Override [step] with [value], ensuring that [step] evaluates to [value] /// when [run] is called in this [Runner]. /// /// Overriding a [Step] is a useful technique for injecting input that steps /// depend on, as illstrated in the example below. It can also be useful for /// injecting mock objects or fakes when writing tests. /// /// Overriding a [step] after it has been evaluated or overriden once is not /// allowed. /// /// ## Example overriding a step to provide input /// ```dart /// /// A step that provides a message, this is a _virtual step_ because it /// /// doesn't have an implementation instead it throws an error. Hence, to /// /// evaluate a step that depends on [messageStep] it is necessary to /// /// override this step, by injecting a value to replace it. /// final Step<String> messageStep = Step.define('message').build( /// () => throw UnimplementedError('message must be overriden with input'), /// ); /// /// /// A step that provides date and time /// final dateTimeStep = /// Step.define('date-time').build(() => DateTime.now().toString()); /// /// /// A step which has side effects. /// final Step<void> printStep = Step.define('print') /// // Dependencies: /// .dep(messageStep) /// .dep(dateTimeStep) /// .build(( /// msg, // result from evaluation of messageStep /// time, // result from evaluation of dateTimeStep /// ) { /// print('$msg at $time'); /// }); /// /// Future<void> main() async { /// final r = Runner(); /// // Override [messageStep] to provide an input value. /// r.override(messageStep, 'hello world'); /// // Evaluate [printStep] which in turn evaluates [dateTimeStep], and re-uses /// // the overridden value for [messageStep]. /// await r.run(printStep); /// } /// ``` void override<T, S extends Step<T>>(S step, FutureOr<T> value) { if (_cache.containsKey(step)) { throw StateError('Value for $step is already cached'); } _cache[step] = Future.value(value); } /// Evaluate [step] after evaluating dependencies or re-use cached values. /// /// This will return the value of [step] as cached in this [Runner], if [Step] /// has been evaluated or overridden. Otherwise, this wil evaluate the /// dependencies of [step], execute the step and cache the result. /// /// Call this method on a given instance of [Runner] with the same [step] /// will always produce the same result. /// /// ## Example evaluation of a step /// ```dart /// class MyComponent { /// // ... /// } /// /// final Step<MyComponent> myStep = /// Step.define('my-component').build(() => MyComponent()); /// /// Future<void> main() async { /// final r = Runner(); /// // Create a MyComponent instance using myStep /// final myComponent1 = await r.run(myStep); /// // Retrieve the previoysly cached result /// final myComponent2 = await r.run(myStep); /// // myComponent1 and myComponent2 will be the same instance. /// // to create a new instance a new Runner must be used. /// assert(myComponent1 == myComponent2); /// } /// ``` Future<T> run<T>(Step<T> step) => _cache.putIfAbsent( step, () => step._create( this, (fn) => _wrapRunStep(step, () => Future.value(fn())), ), ); } /// A [Step] is a function that may depend on the result of other steps. /// /// A [Step] has a [name], a set of [directDependencies], a type [T], and an /// internal function that given the result of all the dependencies can /// compute a result of type [T]. /// /// On its own a [Step] cannot be evaluated. To execute a [Step] a [Runner] /// must be used. A [Runner] caches the result of steps as they are evaluated. /// Hence, within a given [Runner] instance a single [Step] instance is /// evaluated at most once. /// /// To evaluate a [Step] call [Runner.run] passing in the step. This will /// evaluate dependencies (if results are not already cached), and evaluate /// the step passed in. /// /// Do not implement the [Step] interface, this class is sealed. Instances /// should be created using the static method [define] which returns a /// [StepBuilder] that can be used to build a step without dependencies or /// create a [StepBuilder1] which can build a step with 1 dependency, or create /// a [StepBuilder2] which can build a step with 2 dependencies, or create /// [StepBuilder3] an so forth until [StepBuilder9] which holds 9 dependencies. /// /// If more than 9 dependencies is needed, then [StepBuilder.deps] can be used /// to create a [StepBuilderN] which takes `N` dependencies. This allows an /// arbitrary number of dependencies, but consuming the result may require type /// casting. @sealed class Step<T> { /// Name of the step. /// /// This is used to identify the step, typically for debugging, logging or /// other instrospection purposes, such as [toString]. final String name; /// Direct dependencies of this step. /// /// This is the steps that this step depends on, directly. These steps may /// depend on other steps and so forth. However, as the set of dependencies /// must be specified when a [Step] is created, it is not possible for there /// to be any dependency cycles. final Iterable<Step<Object?>> directDependencies; /// Internal method for creating an [T] given a [Runner] [r] that evaluate /// the [directDependencies]. /// /// After [r] has been called to provide dependencies, the [wrap] function /// should wrap the actual user-provided method that generates the result. /// This allows [RunStepWrapper] to interscept exceptions, retry steps, log /// step execution, record step execution time, etc. /// /// This method is intentionally private, and should only be called from /// [Runner.run]. final Future<T> Function( Runner r, Future<T> Function(FutureOr<T> Function()) wrap, ) _create; @override String toString() => 'Step[$name]'; Step._(this.name, this._create, List<Step<Object?>> dependencies) : directDependencies = UnmodifiableListView(dependencies); /// Define a [Step] using a [StepBuilder]. /// /// This method returns a _builder_ which has two methods `dep` and `build`. /// Calling `builder.dep(stepA)` adds a dependency on `stepA` and returns /// a new builder. Calling `builder.build(runStep)` creates a [Step<T>] if /// `runStep` is a function that returns `T` and takes the result value /// from dependent steps. /// /// As adding new dependenices with `builder.dep` changes the number of /// arguments for the `runStep` method required by the `builder.build` method, /// the type of the _builder_ will be [StepBuilder], [StepBuilder1] through /// [StepBuilder9] depending on the number of dependenices. The `StepBuilder` /// types have the same interface, except the [StepBuilder] and /// [StepBuilder9] which offers a `builder.deps(Iterable<Step<S>> steps)` /// method that allows for an arbitrary number of dependencies. This useful if /// all the dependent steps have the same type, or if a step has more than 9 /// dependencies. /// /// ### Example /// ```dart /// // Define a step without dependencies /// final Step<Router> routerStep = Step.define('router').build(() { /// return Router(/* setup request router */); /// }); /// /// // Define a step without dependencies /// final Step<Database> databaseStep = Step.define('database').build(() { /// return Database(/* setup database connection and schema */); /// }); /// /// // Define a step with two dependencies /// final Step<Server> server = Step.define('server') /// .dep(routerStep) /// .dep(databaseStep) /// .build((router, router) async { /// // Setup Server using router and database /// }); /// ``` static StepBuilder define(String name) => StepBuilder._(name); } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder { final String _name; StepBuilder._(this._name); /// Add dependency on [stepA] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder1<A> dep<A>(Step<A> stepA) { return StepBuilder1._(_name, stepA); } /// Add dependency on an arbitrary number of steps [dependencies] and return /// a new _builder_ from which to continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilderN<S> deps<S>(Iterable<Step<S>> dependencies) { final dependencies_ = List<Step<S>>.from(dependencies); return StepBuilderN._(_name, dependencies_); } /// Build a step without dependencies. /// /// This methods requires a [runStep] function which runs the step. The /// [runStep] method may be asynchronous. The [runStep] method will be invoked /// by `Runner.run` when the step is evaluated. /// /// This method returns the [Step] built by the builder, see [Step.define] for /// how to define steps using this API. Step<T> build<T>(FutureOr<T> Function() runStep) { return Step._(_name, (r, wrap) async { return await wrap(() => runStep()); }, []); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilderN<S> { final String _name; final List<Step<S>> _dependencies; StepBuilderN._(this._name, this._dependencies); /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `values` passed to [runStep] have /// already be defined when this object was created. See [Step.define] for /// how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>(FutureOr<T> Function(List<S> values) runStep) => Step._(_name, (r, wrap) async { final values = await Future.wait(_dependencies.map(r.run)); return await wrap(() => runStep(values)); }, [..._dependencies]); } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder1<A> { final String _name; final Step<A> _a; StepBuilder1._(this._name, this._a); /// Add dependency on [stepB] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder2<A, B> dep<B>(Step<B> stepB) { return StepBuilder2._(_name, _a, stepB); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent [Step] which creates `valueA` passed to [runStep] have /// already be defined when this object was created. See [Step.define] for /// how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>(FutureOr<T> Function(A valueA) runStep) => Step._(_name, (r, wrap) async { final a_ = r.run(_a); await Future.wait([a_]); final a = await a_; return await wrap(() => runStep(a)); }, [_a]); } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder2<A, B> { final String _name; final Step<A> _a; final Step<B> _b; StepBuilder2._(this._name, this._a, this._b); /// Add dependency on [stepC] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder3<A, B, C> dep<C>(Step<C> stepC) { return StepBuilder3._(_name, _a, _b, stepC); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA` and `valueB` passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>(FutureOr<T> Function(A valueA, B valueB) runStep) => Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); await Future.wait([a_, b_]); final a = await a_; final b = await b_; return await wrap(() => runStep(a, b)); }, [_a, _b]); } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder3<A, B, C> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; StepBuilder3._( this._name, this._a, this._b, this._c, ); /// Add dependency on [stepD] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder4<A, B, C, D> dep<D>(Step<D> stepD) { return StepBuilder4._(_name, _a, _b, _c, stepD); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); await Future.wait([a_, b_, c_]); final a = await a_; final b = await b_; final c = await c_; return await wrap(() => runStep(a, b, c)); }, [_a, _b, _c]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder4<A, B, C, D> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; StepBuilder4._( this._name, this._a, this._b, this._c, this._d, ); /// Add dependency on [stepE] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder5<A, B, C, D, E> dep<E>(Step<E> stepE) { return StepBuilder5._(_name, _a, _b, _c, _d, stepE); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); await Future.wait([a_, b_, c_, d_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; return await wrap(() => runStep(a, b, c, d)); }, [_a, _b, _c, _d]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder5<A, B, C, D, E> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; StepBuilder5._( this._name, this._a, this._b, this._c, this._d, this._e, ); /// Add dependency on [stepF] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder6<A, B, C, D, E, F> dep<F>(Step<F> stepF) { return StepBuilder6._(_name, _a, _b, _c, _d, _e, stepF); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); await Future.wait([a_, b_, c_, d_, e_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; return await wrap(() => runStep(a, b, c, d, e)); }, [_a, _b, _c, _d, _e]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder6<A, B, C, D, E, F> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; final Step<F> _f; StepBuilder6._( this._name, this._a, this._b, this._c, this._d, this._e, this._f, ); /// Add dependency on [stepG] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder7<A, B, C, D, E, F, G> dep<G>(Step<G> stepG) { return StepBuilder7._(_name, _a, _b, _c, _d, _e, _f, stepG); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, F valueF, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); final f_ = r.run(_f); await Future.wait([a_, b_, c_, d_, e_, f_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; final f = await f_; return await wrap(() => runStep(a, b, c, d, e, f)); }, [_a, _b, _c, _d, _e, _f]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder7<A, B, C, D, E, F, G> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; final Step<F> _f; final Step<G> _g; StepBuilder7._( this._name, this._a, this._b, this._c, this._d, this._e, this._f, this._g, ); /// Add dependency on [stepH] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder8<A, B, C, D, E, F, G, H> dep<H>(Step<H> stepH) { return StepBuilder8._(_name, _a, _b, _c, _d, _e, _f, _g, stepH); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, F valueF, G valueG, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); final f_ = r.run(_f); final g_ = r.run(_g); await Future.wait([a_, b_, c_, d_, e_, f_, g_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; final f = await f_; final g = await g_; return await wrap(() => runStep(a, b, c, d, e, f, g)); }, [_a, _b, _c, _d, _e, _f, _g]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder8<A, B, C, D, E, F, G, H> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; final Step<F> _f; final Step<G> _g; final Step<H> _h; StepBuilder8._( this._name, this._a, this._b, this._c, this._d, this._e, this._f, this._g, this._h, ); /// Add dependency on [stepI] and return a new _builder_ from which to /// continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder9<A, B, C, D, E, F, G, H, I> dep<I>(Step<I> stepI) { return StepBuilder9._(_name, _a, _b, _c, _d, _e, _f, _g, _h, stepI); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, F valueF, G valueG, H valueH, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); final f_ = r.run(_f); final g_ = r.run(_g); final h_ = r.run(_h); await Future.wait([a_, b_, c_, d_, e_, f_, g_, h_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; final f = await f_; final g = await g_; final h = await h_; return await wrap(() => runStep(a, b, c, d, e, f, g, h)); }, [_a, _b, _c, _d, _e, _f, _g, _h]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder9<A, B, C, D, E, F, G, H, I> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; final Step<F> _f; final Step<G> _g; final Step<H> _h; final Step<I> _i; StepBuilder9._( this._name, this._a, this._b, this._c, this._d, this._e, this._f, this._g, this._h, this._i, ); /// Add dependency on an arbitrary number of steps [deps] and return /// a new _builder_ from which to continue (building the final step). /// /// This methods returns a new builder to be used as an intermediate result in /// the expression defining a step. See [Step.define] for how to define steps. StepBuilder9N<A, B, C, D, E, F, G, H, I, S> deps<S>(Iterable<Step<S>> deps) { ArgumentError.checkNotNull(deps, 'deps'); final _deps = List<Step<S>>.from(deps); return StepBuilder9N._(_name, _a, _b, _c, _d, _e, _f, _g, _h, _i, _deps); } /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, F valueF, G valueG, H valueH, I valueI, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); final f_ = r.run(_f); final g_ = r.run(_g); final h_ = r.run(_h); final i_ = r.run(_i); await Future.wait([a_, b_, c_, d_, e_, f_, g_, h_, i_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; final f = await f_; final g = await g_; final h = await h_; final i = await i_; return await wrap(() => runStep(a, b, c, d, e, f, g, h, i)); }, [_a, _b, _c, _d, _e, _f, _g, _h, _i]); } } /// Builder for creating a [Step]. /// /// This type is only intended to be used an intermediate result in an /// expression defining a step. See [Step.define] for how to define steps. @sealed class StepBuilder9N<A, B, C, D, E, F, G, H, I, S> { final String _name; final Step<A> _a; final Step<B> _b; final Step<C> _c; final Step<D> _d; final Step<E> _e; final Step<F> _f; final Step<G> _g; final Step<H> _h; final Step<I> _i; final List<Step<S>> _dependencies; StepBuilder9N._( this._name, this._a, this._b, this._c, this._d, this._e, this._f, this._g, this._h, this._i, this._dependencies, ); /// Build a step with a single dependency. /// /// This methods requires a [runStep] function which runs the step, given /// values from evaluation of dependent steps. The [runStep] method may be /// asynchronous. The [runStep] method will be invoked by `Runner.run` when /// the step is evaluated. /// /// The dependent steps which creates `valueA`, `valueB`, ..., passed to /// [runStep] have already be defined when this object was created. /// See [Step.define] for how to define steps using this API. /// /// This method returns the [Step] built by the builder. Step<T> build<T>( FutureOr<T> Function( A valueA, B valueB, C valueC, D valueD, E valueE, F valueF, G valueG, H valueH, I valueI, List<S> values, ) runStep, ) { return Step._(_name, (r, wrap) async { final a_ = r.run(_a); final b_ = r.run(_b); final c_ = r.run(_c); final d_ = r.run(_d); final e_ = r.run(_e); final f_ = r.run(_f); final g_ = r.run(_g); final h_ = r.run(_h); final i_ = r.run(_i); final values_ = _dependencies.map(r.run).toList(); await Future.wait([a_, b_, c_, d_, e_, f_, g_, h_, i_, ...values_]); final a = await a_; final b = await b_; final c = await c_; final d = await d_; final e = await e_; final f = await f_; final g = await g_; final h = await h_; final i = await i_; final values = await Future.wait(values_); return await wrap(() => runStep(a, b, c, d, e, f, g, h, i, values)); }, [_a, _b, _c, _d, _e, _f, _g, _h, _i, ..._dependencies]); } }
dart-neats/acyclic_steps/lib/src/fluent_api.dart/0
{'file_path': 'dart-neats/acyclic_steps/lib/src/fluent_api.dart', 'repo_id': 'dart-neats', 'token_count': 12535}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:convert' show utf8; import 'dart:math' as math; import 'dart:typed_data' show Uint8List; import 'fast_unorm.dart' show fastNfc; /// Convert ascii [character] to integer. /// /// This function requires that [character] is a single ascii character. int char(String character) { assert(character.length == 1, 'expected string with a length of 1'); assert(character.codeUnitAt(0) <= 128, 'expected an ascii character'); return character.codeUnitAt(0); } class RawMapEntry { final Uint8List key; final Object? value; RawMapEntry(this.key, this.value); static Iterable<RawMapEntry> fromMap(Map<String, Object?> map) sync* { for (final e in map.entries) { final s = fastNfc(e.key).replaceAll(r'\', r'\\').replaceAll('"', r'\"'); final b = utf8.encode(s); final k = Uint8List(b.length + 2) ..first = char('"') ..setAll(1, b) ..last = char('"'); yield RawMapEntry(k, e.value); } } static int compare(RawMapEntry a, RawMapEntry b) { final N = math.min(a.key.length, b.key.length); for (var i = 0; i < N; i++) { final r = a.key[i].compareTo(b.key[i]); if (r != 0) { return r; } } if (a.key.length < b.key.length) { return -1; } if (b.key.length < a.key.length) { return 1; } return 0; } } /// Return [data] as [Uint8List] or return a [Uint8List] copy of [data]. /// /// This won't make a clone of [data] if [data] is already a [Uint8List]. Uint8List ensureUint8List(List<int> data) { if (data is Uint8List) { return data; } return Uint8List.fromList(data); }
dart-neats/canonical_json/lib/src/utils.dart/0
{'file_path': 'dart-neats/canonical_json/lib/src/utils.dart', 'repo_id': 'dart-neats', 'token_count': 834}
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:test/test.dart'; import 'package:chunked_stream/chunked_stream.dart'; void main() { for (var N = 1; N < 6; N++) { test('asChunkedStream (N = $N) preserves elements', () async { final s = (() async* { for (var j = 0; j < 97; j++) { yield j; } })(); final result = await readChunkedStream(asChunkedStream(N, s)); expect(result, hasLength(97)); expect(result, equals(List.generate(97, (j) => j))); }); test('asChunkedStream (N = $N) has chunk size N', () async { final s = (() async* { for (var j = 0; j < 97; j++) { yield j; } })(); final chunks = await asChunkedStream(N, s).toList(); // Last chunk may be smaller than N expect(chunks.removeLast(), hasLength(lessThanOrEqualTo(N))); // Last chunk must be N expect(chunks, everyElement(hasLength(N))); }); } }
dart-neats/chunked_stream/test/chunk_stream_test.dart/0
{'file_path': 'dart-neats/chunked_stream/test/chunk_stream_test.dart', 'repo_id': 'dart-neats', 'token_count': 564}
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:convert'; import 'package:neat_cache/cache_provider.dart'; import 'package:logging/logging.dart'; import 'package:convert/convert.dart' show IdentityCodec; void setupLogging() { Logger.root.level = Level.ALL; Logger.root.onRecord.listen((LogRecord rec) { print('${rec.level.name}: ${rec.message}'); }); } /// Simple class to wrap a `CacheProvider<T>` + `Codec<String, T>` to get a /// `CacheProvider<String>`. /// /// This is just meant to be useful for testing. class StringCacheProvider<T> implements CacheProvider<String> { final CacheProvider<T> cache; final Codec<String, T> codec; StringCacheProvider({ required this.cache, this.codec = const IdentityCodec(), }); @override Future<String?> get(String key) async { final val = await cache.get(key); if (val == null) { return null; } return codec.decode(val); } @override Future set(String key, String value, [Duration? ttl]) { if (ttl != null) { return cache.set(key, codec.encode(value), ttl); } return cache.set(key, codec.encode(value)); } @override Future purge(String key) => cache.purge(key); @override Future close() => cache.close(); }
dart-neats/neat_cache/test/utils.dart/0
{'file_path': 'dart-neats/neat_cache/test/utils.dart', 'repo_id': 'dart-neats', 'token_count': 595}
include: package:lints/recommended.yaml
dart-neats/pem/analysis_options.yaml/0
{'file_path': 'dart-neats/pem/analysis_options.yaml', 'repo_id': 'dart-neats', 'token_count': 13}
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Retry asynchronous functions with exponential backoff. /// /// For a simple solution see [retry], to modify and persist retry options see /// [RetryOptions]. Note, in many cases the added configurability is /// unnecessary and using [retry] is perfectly fine. library retry; import 'dart:async'; import 'dart:math' as math; final _rand = math.Random(); /// Object holding options for retrying a function. /// /// With the default configuration functions will be retried up-to 7 times /// (8 attempts in total), sleeping 1st, 2nd, 3rd, ..., 7th attempt: /// 1. 400 ms +/- 25% /// 2. 800 ms +/- 25% /// 3. 1600 ms +/- 25% /// 4. 3200 ms +/- 25% /// 5. 6400 ms +/- 25% /// 6. 12800 ms +/- 25% /// 7. 25600 ms +/- 25% /// /// **Example** /// ```dart /// final r = RetryOptions(); /// final response = await r.retry( /// // Make a GET request /// () => http.get('https://google.com').timeout(Duration(seconds: 5)), /// // Retry on SocketException or TimeoutException /// retryIf: (e) => e is SocketException || e is TimeoutException, /// ); /// print(response.body); /// ``` class RetryOptions { /// Delay factor to double after every attempt. /// /// Defaults to 200 ms, which results in the following delays: /// /// 1. 400 ms /// 2. 800 ms /// 3. 1600 ms /// 4. 3200 ms /// 5. 6400 ms /// 6. 12800 ms /// 7. 25600 ms /// /// Before application of [randomizationFactor]. final Duration delayFactor; /// Percentage the delay should be randomized, given as fraction between /// 0 and 1. /// /// If [randomizationFactor] is `0.25` (default) this indicates 25 % of the /// delay should be increased or decreased by 25 %. final double randomizationFactor; /// Maximum delay between retries, defaults to 30 seconds. final Duration maxDelay; /// Maximum number of attempts before giving up, defaults to 8. final int maxAttempts; /// Create a set of [RetryOptions]. /// /// Defaults to 8 attempts, sleeping as following after 1st, 2nd, 3rd, ..., /// 7th attempt: /// 1. 400 ms +/- 25% /// 2. 800 ms +/- 25% /// 3. 1600 ms +/- 25% /// 4. 3200 ms +/- 25% /// 5. 6400 ms +/- 25% /// 6. 12800 ms +/- 25% /// 7. 25600 ms +/- 25% const RetryOptions({ this.delayFactor = const Duration(milliseconds: 200), this.randomizationFactor = 0.25, this.maxDelay = const Duration(seconds: 30), this.maxAttempts = 8, }); /// Delay after [attempt] number of attempts. /// /// This is computed as `pow(2, attempt) * delayFactor`, then is multiplied by /// between `-randomizationFactor` and `randomizationFactor` at random. Duration delay(int attempt) { assert(attempt >= 0, 'attempt cannot be negative'); if (attempt <= 0) { return Duration.zero; } final rf = (randomizationFactor * (_rand.nextDouble() * 2 - 1) + 1); final exp = math.min(attempt, 31); // prevent overflows. final delay = (delayFactor * math.pow(2.0, exp) * rf); return delay < maxDelay ? delay : maxDelay; } /// Call [fn] retrying so long as [retryIf] return `true` for the exception /// thrown. /// /// At every retry the [onRetry] function will be called (if given). The /// function [fn] will be invoked at-most [this.attempts] times. /// /// If no [retryIf] function is given this will retry any for any [Exception] /// thrown. To retry on an [Error], the error must be caught and _rethrown_ /// as an [Exception]. Future<T> retry<T>( FutureOr<T> Function() fn, { FutureOr<bool> Function(Exception)? retryIf, FutureOr<void> Function(Exception)? onRetry, }) async { var attempt = 0; // ignore: literal_only_boolean_expressions while (true) { attempt++; // first invocation is the first attempt try { return await fn(); } on Exception catch (e) { if (attempt >= maxAttempts || (retryIf != null && !(await retryIf(e)))) { rethrow; } if (onRetry != null) { await onRetry(e); } } // Sleep for a delay await Future.delayed(delay(attempt)); } } } /// Call [fn] retrying so long as [retryIf] return `true` for the exception /// thrown, up-to [maxAttempts] times. /// /// Defaults to 8 attempts, sleeping as following after 1st, 2nd, 3rd, ..., /// 7th attempt: /// 1. 400 ms +/- 25% /// 2. 800 ms +/- 25% /// 3. 1600 ms +/- 25% /// 4. 3200 ms +/- 25% /// 5. 6400 ms +/- 25% /// 6. 12800 ms +/- 25% /// 7. 25600 ms +/- 25% /// /// ```dart /// final response = await retry( /// // Make a GET request /// () => http.get('https://google.com').timeout(Duration(seconds: 5)), /// // Retry on SocketException or TimeoutException /// retryIf: (e) => e is SocketException || e is TimeoutException, /// ); /// print(response.body); /// ``` /// /// If no [retryIf] function is given this will retry any for any [Exception] /// thrown. To retry on an [Error], the error must be caught and _rethrown_ /// as an [Exception]. Future<T> retry<T>( FutureOr<T> Function() fn, { Duration delayFactor = const Duration(milliseconds: 200), double randomizationFactor = 0.25, Duration maxDelay = const Duration(seconds: 30), int maxAttempts = 8, FutureOr<bool> Function(Exception)? retryIf, FutureOr<void> Function(Exception)? onRetry, }) => RetryOptions( delayFactor: delayFactor, randomizationFactor: randomizationFactor, maxDelay: maxDelay, maxAttempts: maxAttempts, ).retry(fn, retryIf: retryIf, onRetry: onRetry);
dart-neats/retry/lib/retry.dart/0
{'file_path': 'dart-neats/retry/lib/retry.dart', 'repo_id': 'dart-neats', 'token_count': 2053}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // @dart=2.12 import 'dart:async' show Future; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_router/shelf_router.dart'; // Generated code will be written to 'main.g.dart' part 'main.g.dart'; class Service { // A handler is annotated with @Route.<verb>('<route>'), the '<route>' may // embed URL-parameters, and these may be taken as parameters by the handler. // But either all URL-parameters or none of the URL parameters must be taken // as parameters by the handler. @Route.get('/say-hi/<name>') Response _hi(Request request, String name) => Response.ok('hi $name'); // Embedded URL parameters may also be associated with a regular-expression // that the pattern must match. @Route.get('/user/<userId|[0-9]+>') Response _user(Request request, String userId) => Response.ok('User has the user-number: $userId'); // Handlers can be asynchronous (returning `FutureOr` is also allowed). @Route.get('/wave') Future<Response> _wave(Request request) async { await Future.delayed(const Duration(milliseconds: 100)); return Response.ok('_o/'); } // Other routers can be mounted... @Route.mount('/api/') Router get _api => Api().router; // You can catch all verbs and use a URL-parameter with a regular expression // that matches everything to catch app. @Route.all('/<ignored|.*>') Response _notFound(Request request) => Response.notFound('Page not found'); // The generated function _$ServiceRouter can be used to get a [Handler] // for this object. This can be used with [shelf_io.serve]. Handler get handler => _$ServiceRouter(this); } class Api { // A handler can have more that one route :) @Route.get('/messages') @Route.get('/messages/') Future<Response> _messages(Request request) async => Response.ok('[]'); // This nested catch-all, will only catch /api/.* when mounted above. // Notice that ordering if annotated handlers and mounts is significant. @Route.all('/<ignored|.*>') Response _notFound(Request request) => Response.notFound('null'); // The generated function _$ApiRouter can be used to expose a [Router] for // this object. Router get router => _$ApiRouter(this); } // Run shelf server and host a [Service] instance on port 8080. void main() async { final service = Service(); final server = await shelf_io.serve(service.handler, 'localhost', 8080); print('Server running on localhost:${server.port}'); }
dart-neats/shelf_router_generator/example/main.dart/0
{'file_path': 'dart-neats/shelf_router_generator/example/main.dart', 'repo_id': 'dart-neats', 'token_count': 932}
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:io' show exit, Platform, stderr, stdout; import 'package:io/io.dart' show ExitCode; import 'package:vendor/src/context.dart' show Context; import 'package:vendor/src/exceptions.dart' show VendorFailure; import 'package:vendor/src/vendor.dart' show vendor; import 'package:args/args.dart' show ArgParser, ArgResults; import 'package:path/path.dart' as p; import 'package:io/ansi.dart' as ansi; import 'package:http/http.dart' as http; final _parser = ArgParser(usageLineLength: 80) ..addFlag( 'dry-run', abbr: 'n', negatable: false, help: 'Show changes to be made without making any.', ) ..addFlag( 'help', abbr: 'h', negatable: false, help: 'Display this help message', ); final _usage = ''' Utility for vendoring pub packages. Usage: dart pub run vendor Options: ${_parser.usage} '''; /// Get `PUB_HOSTED_URL`, defaulting to `https://pub.dartlang.org/`. Uri get _pubHostedUrl { final hostedUrl = Platform.environment['PUB_HOSTED_URL']; if (hostedUrl != null && hostedUrl.isNotEmpty) { try { final u = Uri.parse(hostedUrl); if (!u.isScheme('http') && !u.isScheme('https')) { throw VendorFailure( ExitCode.config, 'PUB_HOSTED_URL must be a http:// or https:// URL', ); } return u; } on FormatException catch (e) { throw VendorFailure( ExitCode.config, 'Failed to parse PUB_HOSTED_URL: $e', ); } } return Uri.https('pub.dartlang.org', '/'); } class _Context extends Context { @override final http.Client client; @override final Uri rootPackageFolder; @override final Uri defaultHostedUrl; @override _Context({ required this.rootPackageFolder, required this.client, required this.defaultHostedUrl, }); @override void log(String message) => stdout.writeln( message.startsWith('#') ? ansi.wrapWith(message, [ansi.styleBold]) : message, ); @override void warning(String message) => stderr.writeln(ansi.wrapWith( message, [ansi.red, ansi.styleBold], )); } Future<ExitCode> _main(List<String> arguments) async { try { ArgResults args; try { args = _parser.parse(arguments); } on FormatException catch (e) { print(e.message); print(_usage); return ExitCode.usage; } if (args['help']) { print(_usage); return ExitCode.success; } final ctx = _Context( rootPackageFolder: Uri.directory(p.current), defaultHostedUrl: _pubHostedUrl, client: http.Client(), ); try { await vendor( ctx, dryRun: args['dry-run'] ?? false, ); } on VendorFailure catch (e) { ctx.warning(e.message); return e.exitCode; } finally { ctx.client.close(); } } catch (e, st) { print('Internal Error in package:vendor:'); print(e); print(st); print(''); print('Consider reporting:'); print(Uri.parse('https://github.com/google/dart-neats/issues/new') .replace(queryParameters: { 'labels': 'pkg:yaml_edit+pending-triage', 'title': '$e', 'body': '''Internal error occured: ``` $e $st ``` Running on `vendor.yaml` as follows: ```yaml TODO: Include `vendor.yaml`. ``` ''', })); return ExitCode.software; } return ExitCode.success; } void main(List<String> arguments) async => exit((await _main(arguments)).code);
dart-neats/vendor/bin/vendor.dart/0
{'file_path': 'dart-neats/vendor/bin/vendor.dart', 'repo_id': 'dart-neats', 'token_count': 1598}
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extension IterableExt<T> on Iterable<T> { /// Returns `true`, if [other] is a prefix of all the elements in `this`. bool startsWith( Iterable<T> other, [ bool Function(T a, T b) isEqual = _isEqual, ]) { final i = iterator; for (final v in other) { if (!i.moveNext() || !isEqual(i.current, v)) { return false; } } return true; } } bool _isEqual(Object? a, Object? b) => a == b;
dart-neats/vendor/lib/src/utils/iterable_ext.dart/0
{'file_path': 'dart-neats/vendor/lib/src/utils/iterable_ext.dart', 'repo_id': 'dart-neats', 'token_count': 334}
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:test/test.dart'; import 'package:vendor/src/utils/map_ext.dart'; void main() { test('Map.where((k, v) => k == \'a\' && v == 1)', () { expect( { 'a': 1, 'b': 2, }.where((k, v) => k == 'a' && v == 1), equals({ 'a': 1, }), ); }); test('Map.where((k, v) => true)', () { expect( { 'a': 1, 'b': 2, }.where((k, v) => true), equals({ 'a': 1, 'b': 2, }), ); }); test('Map.where((k, v) => false)', () { expect( { 'a': 1, 'b': 2, }.where((k, v) => false), equals({}), ); }); test('Map.where((k, v) => v > 3)', () { expect( { 'a': 1, 'b': 2, 'A': 4, 'B': 6, }.where((k, v) => v > 3), equals({ 'A': 4, 'B': 6, }), ); }); test('Map.mapPairs((k, v) => k)', () { expect( { 'a': 1, 'b': 2, }.mapPairs((k, v) => k).toList(), equals([ 'a', 'b', ]), ); }); test('Map.mapPairs((k, v) => v)', () { expect( { 'a': 1, 'b': 2, }.mapPairs((k, v) => v).toList(), equals([ 1, 2, ]), ); }); test('Map.mapPairs((k, v) => \'\$k-\$v\')', () { expect( { 'a': 1, 'b': 2, }.mapPairs((k, v) => '$k-$v').toList(), equals([ 'a-1', 'b-2', ]), ); }); }
dart-neats/vendor/test/utils/map_ext_test.dart/0
{'file_path': 'dart-neats/vendor/test/utils/map_ext_test.dart', 'repo_id': 'dart-neats', 'token_count': 1080}
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library editor.codemirror; import 'dart:async'; import 'dart:convert'; import 'dart:html' as html; import 'dart:js'; import 'dart:math'; import 'package:codemirror/codemirror.dart' hide Position; import 'package:codemirror/codemirror.dart' as pos show Position; import 'package:codemirror/hints.dart'; import 'editor.dart' hide Position; import 'editor.dart' as ed show Position; export 'editor.dart'; final CodeMirrorFactory codeMirrorFactory = CodeMirrorFactory._(); class CodeMirrorFactory extends EditorFactory { CodeMirrorFactory._(); String get version => CodeMirror.version; @override List<String> get modes => CodeMirror.MODES; @override List<String> get themes => CodeMirror.THEMES; @override Editor createFromElement(html.Element element, {Map options}) { options ??= { 'continueComments': {'continueLineComment': false}, 'autofocus': false, // Removing this - with this enabled you can't type a forward slash. //'autoCloseTags': true, 'autoCloseBrackets': true, 'matchBrackets': true, 'tabSize': 2, 'lineWrapping': true, 'indentUnit': 2, 'cursorHeight': 0.85, // Increase the number of lines that are rendered above and before what's // visible. 'viewportMargin': 100, //'gutters': [_gutterId], 'extraKeys': { 'Cmd-/': 'toggleComment', 'Ctrl-/': 'toggleComment', 'Tab': 'insertSoftTab' }, 'hintOptions': {'completeSingle': false}, //'lint': true, 'theme': 'zenburn' // ambiance, vibrant-ink, monokai, zenburn }; var editor = CodeMirror.fromElement(element, options: options); CodeMirror.addCommand('goLineLeft', _handleGoLineLeft); return _CodeMirrorEditor._(this, editor); } @override void registerCompleter(String mode, CodeCompleter completer) { Hints.registerHintsHelperAsync(mode, (CodeMirror editor, [HintsOptions options]) { return _completionHelper(editor, completer, options); }); } // Change the cmd-left behavior to move the cursor to the leftmost non-ws char. void _handleGoLineLeft(CodeMirror editor) { editor.execCommand('goLineLeftSmart'); } Future<HintResults> _completionHelper( CodeMirror editor, CodeCompleter completer, HintsOptions options) { var ed = _CodeMirrorEditor._fromExisting(this, editor); return completer .complete(ed, onlyShowFixes: ed._lookingForQuickFix) .then((CompletionResult result) { var doc = editor.getDoc(); var from = doc.posFromIndex(result.replaceOffset); var to = doc.posFromIndex(result.replaceOffset + result.replaceLength); var stringToReplace = doc.getValue().substring( result.replaceOffset, result.replaceOffset + result.replaceLength); var hints = result.completions.map((completion) { return HintResult( completion.value, displayText: completion.displayString, className: completion.type, hintApplier: (CodeMirror editor, HintResult hint, pos.Position from, pos.Position to) { doc.replaceRange(hint.text, from, to); if (completion.type == 'type-quick_fix') { for (final edit in completion.quickFixes) { ed.document.applyEdit(edit); } } if (completion.absoluteCursorPosition != null) { doc.setCursor( doc.posFromIndex(completion.absoluteCursorPosition)); } else if (completion.cursorOffset != null) { var diff = hint.text.length - completion.cursorOffset; doc.setCursor(pos.Position( editor.getCursor().line, editor.getCursor().ch - diff)); } }, hintRenderer: (html.Element element, HintResult hint) { var escapeHtml = HtmlEscape().convert; if (completion.type != 'type-quick_fix') { element.innerHtml = escapeHtml(completion.displayString) .replaceFirst(escapeHtml(stringToReplace), '<em>${escapeHtml(stringToReplace)}</em>'); } else { element.innerHtml = escapeHtml(completion.displayString); } }, ); }).toList(); if (hints.isEmpty && ed._lookingForQuickFix) { hints = [ HintResult(stringToReplace, displayText: 'No fixes available', className: 'type-no_suggestions') ]; } else if (hints.isEmpty && (ed.completionActive || (!ed.completionActive && !ed.completionAutoInvoked))) { // Only show 'no suggestions' if the completion was explicitly invoked // or if the popup was already active. hints = [ HintResult(stringToReplace, displayText: 'No suggestions', className: 'type-no_suggestions') ]; } return HintResults.fromHints(hints, from, to); }); } } class _CodeMirrorEditor extends Editor { // Map from JsObject codemirror instances to existing dartpad wrappers. static final Map<dynamic, _CodeMirrorEditor> _instances = {}; final CodeMirror cm; _CodeMirrorDocument _document; bool _lookingForQuickFix; _CodeMirrorEditor._(CodeMirrorFactory factory, this.cm) : super(factory) { _document = _CodeMirrorDocument._(this, cm.getDoc()); _instances[cm.jsProxy] = this; } factory _CodeMirrorEditor._fromExisting( CodeMirrorFactory factory, CodeMirror cm) { // TODO: We should ensure that the Dart `CodeMirror` wrapper returns the // same instances to us when possible (or, identity is based on the // underlying JS proxy). if (_instances.containsKey(cm.jsProxy)) { return _instances[cm.jsProxy]; } else { return _CodeMirrorEditor._(factory, cm); } } @override Document get document => _document; @override Document createDocument({String content, String mode}) { if (mode == 'html') mode = 'text/html'; content ??= ''; // TODO: For `html`, enable and disable the 'autoCloseTags' option. return _CodeMirrorDocument._(this, Doc(content, mode)); } @override void execCommand(String name) => cm.execCommand(name); @override void showCompletions({bool autoInvoked = false, bool onlyShowFixes = false}) { if (autoInvoked) { completionAutoInvoked = true; } else { completionAutoInvoked = false; } if (onlyShowFixes) { _lookingForQuickFix = true; } else { _lookingForQuickFix = false; } execCommand('autocomplete'); } @override bool get completionActive { if (cm.jsProxy['state']['completionActive'] == null) { return false; } else { return cm.jsProxy['state']['completionActive']['widget'] != null; } } @override bool get autoCloseBrackets => cm.getOption('autoCloseBrackets') as bool; @override set autoCloseBrackets(bool value) => cm.setOption('autoCloseBrackets', value); @override String get mode => cm.getMode(); @override set mode(String str) => cm.setMode(str); @override String get theme => cm.getTheme(); @override set theme(String str) => cm.setTheme(str); @override bool get hasFocus => cm.jsProxy['state']['focused'] as bool; @override Stream<html.MouseEvent> get onMouseDown => cm.onMouseDown; @override Point getCursorCoords({ed.Position position}) { JsObject js; if (position == null) { js = cm.call('cursorCoords') as JsObject; } else { js = cm.callArg('cursorCoords', _document._posToPos(position).toProxy()) as JsObject; } return Point(js['left'] as num, js['top'] as num); } @override void focus() => cm.focus(); @override void resize() => cm.refresh(); @override bool get readOnly => cm.getReadOnly(); @override set readOnly(bool ro) => cm.setReadOnly(ro); @override bool get showLineNumbers => cm.getLineNumbers(); @override set showLineNumbers(bool ln) => cm.setLineNumbers(ln); @override void swapDocument(Document document) { _document = document as _CodeMirrorDocument; cm.swapDoc(_document.doc); } @override void dispose() { _instances.remove(cm.jsProxy); } } class _CodeMirrorDocument extends Document<_CodeMirrorEditor> { final Doc doc; final List<LineWidget> widgets = []; final List<html.DivElement> nodes = []; /// We use `_lastSetValue` here to avoid a change notification when we /// programmatically change the `value` field. String _lastSetValue; _CodeMirrorDocument._(_CodeMirrorEditor editor, this.doc) : super(editor); _CodeMirrorEditor get parent => editor; @override String get value => doc.getValue(); @override set value(String str) { _lastSetValue = str; doc.setValue(str); doc.markClean(); doc.clearHistory(); } @override void updateValue(String str) { doc.setValue(str); } @override ed.Position get cursor => _posFromPos(doc.getCursor()); @override void select(ed.Position start, [ed.Position end]) { if (end != null) { doc.setSelection(_posToPos(start), head: _posToPos(end)); } else { doc.setSelection(_posToPos(start)); } } @override String get selection => doc.getSelection(value); @override String get mode => parent.mode; @override bool get isClean => doc.isClean(); @override void markClean() => doc.markClean(); @override void applyEdit(SourceEdit edit) { doc.replaceRange(edit.replacement, _posToPos(posFromIndex(edit.offset)), _posToPos(posFromIndex(edit.offset + edit.length))); } @override void setAnnotations(List<Annotation> annotations) { for (var marker in doc.getAllMarks()) { marker.clear(); } for (var widget in widgets) { widget.clear(); } widgets.clear(); for (var e in nodes) { e.parent.children.remove(e); } nodes.clear(); // Sort annotations so that the errors are set first. annotations.sort(); var lastLine = -1; for (var an in annotations) { // Create in-line squiggles. doc.markText(_posToPos(an.start), _posToPos(an.end), className: 'squiggle-${an.type}', title: an.message); // Create markers in the margin. if (lastLine == an.line) continue; lastLine = an.line; } } @override int indexFromPos(ed.Position position) => doc.indexFromPos(_posToPos(position)); @override ed.Position posFromIndex(int index) => _posFromPos(doc.posFromIndex(index)); pos.Position _posToPos(ed.Position position) => pos.Position(position.line, position.char); ed.Position _posFromPos(pos.Position position) => ed.Position(position.line, position.ch); @override Stream get onChange { return doc.onChange.where((_) { if (value != _lastSetValue) { _lastSetValue = null; return true; } else { //_lastSetValue = null; return false; } }); } }
dart-pad/lib/editing/editor_codemirror.dart/0
{'file_path': 'dart-pad/lib/editing/editor_codemirror.dart', 'repo_id': 'dart-pad', 'token_count': 4355}
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:html'; import 'package:dart_pad/util/logging.dart'; import 'package:html_unescape/html_unescape.dart'; import 'package:logging/logging.dart'; import 'inject_parser.dart'; Logger _logger = Logger('dartpad-embed'); // Use this prefix for local development: //var iframePrefix = '../'; var iframePrefix = 'https://dartpad.dev/'; /// Replaces all code snippets marked with the 'run-dartpad' class with an /// instance of DartPad. void main() { _logger.onRecord.listen(logToJsConsole); var snippets = querySelectorAll('code'); for (var snippet in snippets) { if (snippet.classes.isEmpty) { continue; } var className = snippet.classes.first; var parser = LanguageStringParser(className); if (!parser.isValid) { continue; } _injectEmbed(snippet, parser.options); } } String iframeSrc(Map<String, String> options) { var prefix = 'embed-${_valueOr(options, 'mode', 'dart')}.html'; var theme = 'theme=${_valueOr(options, 'theme', 'light')}'; var run = 'run=${_valueOr(options, 'run', 'false')}'; var split = 'split=${_valueOr(options, 'split', 'false')}'; // A unique ID used to distinguish between DartPad instances in an article or // codelab. var analytics = 'ga_id=${_valueOr(options, 'ga_id', 'false')}'; return '$iframePrefix$prefix?$theme&$run&$split&$analytics'; } String _valueOr(Map<String, String> map, String value, String defaultValue) { if (map.containsKey(value)) { return map[value]; } return defaultValue; } /// Replaces [host] with an instance of DartPad as an embedded iframe. /// /// Code snippets are assumed to be a div containing `pre` and `code` tags: /// /// <pre> /// <code class="run-dartpad langauge-run-dartpad"> /// void main() => print("Hello, World!"); /// </code> /// </pre> void _injectEmbed(Element snippet, Map<String, String> options) { var preElement = snippet.parent; if (preElement is! PreElement) { _logUnexpectedHtml(); return; } if (preElement.children.length != 1) { _logUnexpectedHtml(); return; } var files = _parseFiles(HtmlUnescape().convert(snippet.innerHtml)); var hostIndex = preElement.parent.children.indexOf(preElement); var host = DivElement(); preElement.parent.children[hostIndex] = host; InjectedEmbed(host, files, options); } Map<String, String> _parseFiles(String snippet) { return InjectParser(snippet).read(); } /// Clears children in [host], instantiates an iframe, and sends it a message /// with the source code when it's ready class InjectedEmbed { final DivElement host; final Map<String, String> files; final Map<String, String> options; InjectedEmbed(this.host, this.files, this.options) { _init(); } Future _init() async { host.children.clear(); var iframe = IFrameElement()..attributes = {'src': iframeSrc(options)}; if (options.containsKey('width')) { iframe.style.width = options['width']; } if (options.containsKey('height')) { iframe.style.height = options['height']; } host.children.add(iframe); window.addEventListener('message', (dynamic e) { if (e.data['type'] == 'ready') { var m = {'sourceCode': files, 'type': 'sourceCode'}; iframe.contentWindow.postMessage(m, '*'); } }); } } void _logUnexpectedHtml() { var message = '''Incorrect HTML for "dartpad-embed". Please use this format: <pre> <code class="run-dartpad"> [code here] </code> </pre> '''; _logger.warning(message); }
dart-pad/lib/inject/inject_embed.dart/0
{'file_path': 'dart-pad/lib/inject/inject_embed.dart', 'repo_id': 'dart-pad', 'token_count': 1331}
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:yaml/yaml.dart' as yaml; /// An exception thrown when a metadata file has missing or invalid fields. class MetadataException implements Exception { final String message; const MetadataException(this.message); } /// Modes for individual exercises. /// /// The DartPad editors, output windows, and so on will be configured according /// to this value. enum ExerciseMode { dart, html, flutter, } final exerciseModeNames = <String, ExerciseMode>{ 'dart': ExerciseMode.dart, 'html': ExerciseMode.html, 'flutter': ExerciseMode.flutter, }; /// Metadata for a single file within a larger exercise. class ExerciseFileMetadata { String name; String alternatePath; String get path => (alternatePath == null || alternatePath.isEmpty) ? name : alternatePath; ExerciseFileMetadata.fromMap(map) { if (map == null) { throw MetadataException('Null json was given to ExerciseFileMetadata().'); } if (map['name'] == null || map['name'] is! String || map['name'].isEmpty as bool) { throw MetadataException('The "name" field is required for each file.'); } name = map['name'] as String; alternatePath = map['alternatePath'] as String; } } /// Represents the metadata for a single codelab exercise, as defined by the /// exercise's `dartpad-metadata.json` file. /// /// This data will be deserialized from that file when an exercise is loaded /// from GitHub, and used to set up the DartPad environment for that exercise. class ExerciseMetadata { String name; ExerciseMode mode; List<ExerciseFileMetadata> files; ExerciseMetadata.fromMap(map) { if (map == null) { throw MetadataException('Null json was given to ExerciseMetadata().'); } if (map['name'] == null || map['name'] is! String || map['name'].isEmpty as bool) { throw MetadataException('The "name" field is required for an exercise.'); } if (map['mode'] == null || map['mode'] is! String || !exerciseModeNames.containsKey(map['mode'])) { throw MetadataException('A "mode" field of "dart", "html" or "flutter" ' 'is required for an exercise.'); } if (map['files'] == null || map['files'] is! List<dynamic> || map['files'].isEmpty as bool) { throw MetadataException('Each exercise must have at least one file in ' 'its "files" array.'); } name = map['name'] as String; mode = exerciseModeNames[map['mode']]; files = (map['files'] as yaml.YamlList) .map((f) => ExerciseFileMetadata.fromMap(f)) .toList(); } }
dart-pad/lib/sharing/exercise_metadata.dart/0
{'file_path': 'dart-pad/lib/sharing/exercise_metadata.dart', 'repo_id': 'dart-pad', 'token_count': 959}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library dart_pad.web_test; import 'core/dependencies_test.dart' as dependencies_test; import 'core/keys_test.dart' as keys_test; import 'documentation_test.dart' as documentation_test; import 'services/common_test.dart' as common_test; import 'sharing/gists_test.dart' as gists_test; import 'sharing/mutable_gist_test.dart' as mutable_gist_test; void main() { // Define the tests. dependencies_test.defineTests(); keys_test.defineTests(); documentation_test.defineTests(); common_test.defineTests(); gists_test.defineTests(); mutable_gist_test.defineTests(); }
dart-pad/test/web.dart/0
{'file_path': 'dart-pad/test/web.dart', 'repo_id': 'dart-pad', 'token_count': 260}
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // To meet GAE needs this file must be called 'server.dart'. library appengine.services.bin; import 'dart:async'; import 'package:dart_services/services_gae.dart' as server; import 'package:dart_services/src/sdk_manager.dart'; Future<void> main(List<String> args) async { // Ensure the Dart SDK is downloaded (if already up-to-date, no work is // performed). await SdkManager.sdk.init(); await SdkManager.flutterSdk.init(); server.main(args); }
dart-services/bin/server.dart/0
{'file_path': 'dart-services/bin/server.dart', 'repo_id': 'dart-services', 'token_count': 213}
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library services.common_server_api_test; import 'dart:async'; import 'dart:convert'; import 'package:dart_services/src/common.dart'; import 'package:dart_services/src/common_server_impl.dart'; import 'package:dart_services/src/common_server_api.dart'; import 'package:dart_services/src/flutter_web.dart'; import 'package:dart_services/src/sdk_manager.dart'; import 'package:dart_services/src/server_cache.dart'; import 'package:logging/logging.dart'; import 'package:mock_request/mock_request.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:test/test.dart'; const versions = ['v1', 'v2']; const quickFixesCode = r''' import 'dart:async'; void main() { int i = 0; } '''; const preFormattedCode = r''' void main() { int i = 0; } '''; const postFormattedCode = r''' void main() { int i = 0; } '''; const formatBadCode = r''' void main() { print('foo') } '''; const assistCode = r''' main() { int v = 0; } '''; void main() => defineTests(); void defineTests() { CommonServerApi commonServerApi; CommonServerImpl commonServerImpl; FlutterWebManager flutterWebManager; MockContainer container; MockCache cache; Future<MockHttpResponse> _sendPostRequest( String path, dynamic jsonData, ) async { assert(commonServerApi != null); final uri = Uri.parse('/api/$path'); final request = MockHttpRequest('POST', uri); request.headers.add('content-type', JSON_CONTENT_TYPE); request.add(utf8.encode(json.encode(jsonData))); await request.close(); await shelf_io.handleRequest(request, commonServerApi.router.handler); return request.response; } Future<MockHttpResponse> _sendGetRequest( String path, ) async { assert(commonServerApi != null); final uri = Uri.parse('/api/$path'); final request = MockHttpRequest('POST', uri); request.headers.add('content-type', JSON_CONTENT_TYPE); await request.close(); await shelf_io.handleRequest(request, commonServerApi.router.handler); return request.response; } group('CommonServerProto JSON', () { setUpAll(() async { container = MockContainer(); cache = MockCache(); flutterWebManager = FlutterWebManager(SdkManager.flutterSdk); commonServerImpl = CommonServerImpl(sdkPath, flutterWebManager, container, cache); commonServerApi = CommonServerApi(commonServerImpl); await commonServerImpl.init(); // Some piece of initialization doesn't always happen fast enough for this // request to work in time for the test. So try it here until the server // returns something valid. // TODO(jcollins-g): determine which piece of initialization isn't // happening and deal with that in warmup/init. { var decodedJson = {}; final jsonData = {'source': sampleCodeError}; while (decodedJson.isEmpty) { final response = await _sendPostRequest('dartservices/v2/analyze', jsonData); expect(response.statusCode, 200); expect(response.headers['content-type'], ['application/json; charset=utf-8']); final data = await response.transform(utf8.decoder).join(); decodedJson = json.decode(data) as Map<dynamic, dynamic>; } } }); tearDownAll(() async { await commonServerImpl.shutdown(); }); setUp(() { log.onRecord.listen((LogRecord rec) { print('${rec.level.name}: ${rec.time}: ${rec.message}'); }); }); tearDown(log.clearListeners); test('analyze Dart', () async { for (final version in versions) { final jsonData = {'source': sampleCode}; final response = await _sendPostRequest('dartservices/$version/analyze', jsonData); expect(response.statusCode, 200); final data = await response.transform(utf8.decoder).join(); expect(json.decode(data), {}); } }); test('analyze Flutter', () async { for (final version in versions) { final jsonData = {'source': sampleCodeFlutter}; final response = await _sendPostRequest('dartservices/$version/analyze', jsonData); expect(response.statusCode, 200); final data = await response.transform(utf8.decoder).join(); expect(json.decode(data), { 'packageImports': ['flutter'] }); } }); test('analyze errors', () async { for (final version in versions) { final jsonData = {'source': sampleCodeError}; final response = await _sendPostRequest('dartservices/$version/analyze', jsonData); expect(response.statusCode, 200); expect(response.headers['content-type'], ['application/json; charset=utf-8']); final data = await response.transform(utf8.decoder).join(); final expectedJson = { 'issues': [ { 'kind': 'error', 'line': 2, 'sourceName': 'main.dart', 'message': "Expected to find ';'.", 'hasFixes': true, 'charStart': 29, 'charLength': 1 } ] }; expect(json.decode(data), expectedJson); } }); test('analyze negative-test noSource', () async { for (final version in versions) { final jsonData = {}; final response = await _sendPostRequest('dartservices/$version/analyze', jsonData); expect(response.statusCode, 400); } }); test('compile', () async { for (final version in versions) { final jsonData = {'source': sampleCode}; final response = await _sendPostRequest('dartservices/$version/compile', jsonData); expect(response.statusCode, 200); final data = await response.transform(utf8.decoder).join(); expect(json.decode(data), isNotEmpty); } }); test('compile error', () async { for (final version in versions) { final jsonData = {'source': sampleCodeError}; final response = await _sendPostRequest('dartservices/$version/compile', jsonData); expect(response.statusCode, 400); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, isNotEmpty); expect(data['error']['message'], contains('Error: Expected')); } }); test('compile negative-test noSource', () async { for (final version in versions) { final jsonData = {}; final response = await _sendPostRequest('dartservices/$version/compile', jsonData); expect(response.statusCode, 400); } }); test('compileDDC', () async { for (final version in versions) { final jsonData = {'source': sampleCode}; final response = await _sendPostRequest( 'dartservices/$version/compileDDC', jsonData); expect(response.statusCode, 200); final data = await response.transform(utf8.decoder).join(); expect(json.decode(data), isNotEmpty); } }); test('complete', () async { for (final version in versions) { final jsonData = {'source': 'void main() {print("foo");}', 'offset': 1}; final response = await _sendPostRequest('dartservices/$version/complete', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, isNotEmpty); } }); test('complete no data', () async { for (final version in versions) { final response = await _sendPostRequest('dartservices/$version/complete', {}); expect(response.statusCode, 400); } }); test('complete param missing', () async { for (final version in versions) { final jsonData = {'offset': 1}; final response = await _sendPostRequest('dartservices/$version/complete', jsonData); expect(response.statusCode, 400); } }); test('complete param missing 2', () async { for (final version in versions) { final jsonData = {'source': 'void main() {print("foo");}'}; final response = await _sendPostRequest('dartservices/$version/complete', jsonData); expect(response.statusCode, 400); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data['error']['message'], 'Missing parameter: \'offset\''); } }); test('document', () async { for (final version in versions) { final jsonData = { 'source': 'void main() {print("foo");}', 'offset': 17 }; final response = await _sendPostRequest('dartservices/$version/document', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, isNotEmpty); } }); test('document little data', () async { for (final version in versions) { final jsonData = {'source': 'void main() {print("foo");}', 'offset': 2}; final response = await _sendPostRequest('dartservices/$version/document', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, { 'info': {}, }); } }); test('document no data', () async { for (final version in versions) { final jsonData = { 'source': 'void main() {print("foo");}', 'offset': 12 }; final response = await _sendPostRequest('dartservices/$version/document', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, {'info': {}}); } }); test('document negative-test noSource', () async { for (final version in versions) { final jsonData = {'offset': 12}; final response = await _sendPostRequest('dartservices/$version/document', jsonData); expect(response.statusCode, 400); } }); test('document negative-test noOffset', () async { for (final version in versions) { final jsonData = {'source': 'void main() {print("foo");}'}; final response = await _sendPostRequest('dartservices/$version/document', jsonData); expect(response.statusCode, 400); } }); test('format', () async { for (final version in versions) { final jsonData = {'source': preFormattedCode}; final response = await _sendPostRequest('dartservices/$version/format', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data['newString'], postFormattedCode); } }); test('format bad code', () async { for (final version in versions) { final jsonData = {'source': formatBadCode}; final response = await _sendPostRequest('dartservices/$version/format', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data['newString'], formatBadCode); } }); test('format position', () async { for (final version in versions) { final jsonData = {'source': preFormattedCode, 'offset': 21}; final response = await _sendPostRequest('dartservices/$version/format', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data['newString'], postFormattedCode); expect(data['offset'], 24); } }); test('fix', () async { for (final version in versions) { final jsonData = {'source': quickFixesCode, 'offset': 10}; final response = await _sendPostRequest('dartservices/$version/fixes', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); final fixes = data['fixes']; expect(fixes.length, 1); final problemAndFix = fixes[0]; expect(problemAndFix['problemMessage'], isNotNull); } }); test('fixes completeness', () async { for (final version in versions) { final jsonData = { 'source': ''' void main() { for (int i = 0; i < 4; i++) { print('hello \$i') } } ''', 'offset': 67, }; final response = await _sendPostRequest('dartservices/$version/fixes', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data, { 'fixes': [ { 'fixes': [ { 'message': "Insert ';'", 'edits': [ {'offset': 67, 'length': 0, 'replacement': ';'} ] } ], 'problemMessage': "Expected to find ';'.", 'offset': 66, 'length': 1 } ] }); } }); test('assist', () async { for (final version in versions) { final jsonData = {'source': assistCode, 'offset': 15}; final response = await _sendPostRequest('dartservices/$version/assists', jsonData); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); final assists = data['assists'] as List; expect(assists, hasLength(2)); expect(assists.first['edits'], isNotNull); expect(assists.first['edits'], hasLength(1)); expect(assists.where((m) { final map = m as Map<String, dynamic>; return map['message'] == 'Remove type annotation'; }), isNotEmpty); } }); test('version', () async { for (final version in versions) { final response = await _sendGetRequest('dartservices/$version/version'); expect(response.statusCode, 200); final data = json.decode(await response.transform(utf8.decoder).join()); expect(data['sdkVersion'], isNotNull); expect(data['runtimeVersion'], isNotNull); } }); }); } class MockContainer implements ServerContainer { @override String get version => vmVersion; } class MockCache implements ServerCache { @override Future<String> get(String key) => Future.value(null); @override Future set(String key, String value, {Duration expiration}) => Future.value(); @override Future remove(String key) => Future.value(); @override Future<void> shutdown() => Future.value(); }
dart-services/test/common_server_api_test.dart/0
{'file_path': 'dart-services/test/common_server_api_test.dart', 'repo_id': 'dart-services', 'token_count': 6182}
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:convert' as convert; import 'dart:io'; import 'package:http/http.dart' as http; const BASE_PATH = '/api/dartservices/v2/'; const count = 200; const dartSource = "import 'dart:html'; void main() { var a = 3; var b = a.abs(); int c = 7;}"; const flutterSource = """import 'package:flutter/material.dart'; void main() { final widget = Container(color: Colors.white); runApp(widget); } """; const dartData = {'offset': 17, 'source': dartSource}; const dartCompileData = {'source': dartSource}; const dartDocData = {'offset': 84, 'source': dartSource}; const flutterData = {'offset': 96, 'source': flutterSource}; const flutterCompileDDCData = {'source': flutterSource}; const flutterDocData = {'offset': 93, 'source': flutterSource}; final dartPayload = convert.json.encode(dartData); final dartCompilePayload = convert.json.encode(dartCompileData); final dartDocPayload = convert.json.encode(dartDocData); final flutterPayload = convert.json.encode(flutterData); final flutterCompileDDCPayload = convert.json.encode(flutterCompileDDCData); final flutterDocPayload = convert.json.encode(flutterDocData); String uri; Future<void> main(List<String> args) async { String appHost; if (args.isNotEmpty) { appHost = '${args[0]}'; } else { print('''Pass the fully qualified dart-services hostname (no protocol, no path) as the first argument when invoking this script. For example: dart warmup.dart 20200124t152413-dot-dart-services-0.appspot.com '''); exit(1); } // Use an insecure connection for test driving to avoid cert problems // with the prefixed app version. uri = 'http://$appHost$BASE_PATH'; print('Target URI\n$uri'); for (var j = 0; j < count; j++) { await request('Dart', 'complete', dartPayload); await request('Dart', 'analyze', dartPayload); await request('Dart', 'compile', dartCompilePayload); await request('Dart', 'document', dartDocPayload); await request('Flutter', 'complete', flutterPayload); await request('Flutter', 'analyze', flutterPayload); await request('Flutter', 'compileDDC', flutterCompileDDCPayload); await request('Flutter', 'document', flutterDocPayload); } } Future<int> request(String codeType, String verb, String postPayload) async { final sw = Stopwatch()..start(); final response = await http.post( Uri.parse(uri + verb), body: postPayload, headers: {'content-type': 'text/plain; charset=utf-8'}, ); final status = response.statusCode; if (status != 200) { print('$codeType $verb \t $status \t ${response.body} ${response.headers}'); } else { print('$codeType $verb \t ${sw.elapsedMilliseconds} \t $status'); } return response.statusCode; }
dart-services/tool/warmup.dart/0
{'file_path': 'dart-services/tool/warmup.dart', 'repo_id': 'dart-services', 'token_count': 999}