From c2cac8336150d8e7f5cb6f0a494f77101eb85dae Mon Sep 17 00:00:00 2001 From: iota9star Date: Mon, 1 Dec 2025 00:44:04 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20refactor:=20restructure=20API?= =?UTF-8?q?=20with=20engine,=20error,=20runtime,=20and=20source=20modules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove deprecated js API modules - Add new engine, error, runtime, and source API modules - Update example app with new API screens - Add widgets directory for UI components - Update package dependencies and changelog --- CHANGELOG.md | 11 + example/lib/app/app.dart | 666 +-- example/lib/app/home_screen.dart | 806 +++ example/lib/app/router.dart | 39 +- example/lib/screens/api_overview_screen.dart | 362 ++ example/lib/screens/engine_api_screen.dart | 629 +++ example/lib/screens/error_api_screen.dart | 603 ++ example/lib/screens/runtime_api_screen.dart | 446 ++ example/lib/screens/source_api_screen.dart | 579 ++ example/lib/screens/value_api_screen.dart | 565 ++ example/lib/test_js_examples.dart | 77 - example/lib/test_load_verification.dart | 43 - example/lib/widgets/api_test_card.dart | 295 + example/lib/widgets/code_editor_widget.dart | 277 + example/lib/widgets/responsive_layout.dart | 90 + example/lib/widgets/widgets.dart | 3 + example/pubspec.lock | 8 +- lib/fjs.dart | 13 +- lib/src/engine.dart | 101 +- lib/src/frb/api/engine.dart | 140 + lib/src/frb/api/engine.freezed.dart | 2093 +++++++ lib/src/frb/api/error.dart | 172 + lib/src/frb/api/error.freezed.dart | 1922 +++++++ lib/src/frb/api/js.dart | 992 ---- lib/src/frb/api/js.freezed.dart | 5250 ------------------ lib/src/frb/api/runtime.dart | 202 + lib/src/frb/api/source.dart | 184 + lib/src/frb/api/source.freezed.dart | 2053 +++++++ lib/src/frb/api/value.dart | 131 +- lib/src/frb/api/value.freezed.dart | 328 ++ lib/src/frb/frb_generated.dart | 2200 +++++--- lib/src/frb/frb_generated.io.dart | 23 +- lib/src/frb/frb_generated.web.dart | 23 +- libfjs/src/api/engine.rs | 487 ++ libfjs/src/api/error.rs | 442 ++ libfjs/src/api/js.rs | 2145 ------- libfjs/src/api/mod.rs | 20 +- libfjs/src/api/module.rs | 171 +- libfjs/src/api/runtime.rs | 613 ++ libfjs/src/api/source.rs | 440 ++ libfjs/src/api/value.rs | 484 +- libfjs/src/frb_generated.rs | 2398 ++++++-- pubspec.yaml | 2 +- 43 files changed, 17877 insertions(+), 10651 deletions(-) create mode 100644 example/lib/app/home_screen.dart create mode 100644 example/lib/screens/api_overview_screen.dart create mode 100644 example/lib/screens/engine_api_screen.dart create mode 100644 example/lib/screens/error_api_screen.dart create mode 100644 example/lib/screens/runtime_api_screen.dart create mode 100644 example/lib/screens/source_api_screen.dart create mode 100644 example/lib/screens/value_api_screen.dart delete mode 100644 example/lib/test_js_examples.dart delete mode 100644 example/lib/test_load_verification.dart create mode 100644 example/lib/widgets/api_test_card.dart create mode 100644 example/lib/widgets/code_editor_widget.dart create mode 100644 example/lib/widgets/responsive_layout.dart create mode 100644 example/lib/widgets/widgets.dart create mode 100644 lib/src/frb/api/engine.dart create mode 100644 lib/src/frb/api/engine.freezed.dart create mode 100644 lib/src/frb/api/error.dart create mode 100644 lib/src/frb/api/error.freezed.dart delete mode 100644 lib/src/frb/api/js.dart delete mode 100644 lib/src/frb/api/js.freezed.dart create mode 100644 lib/src/frb/api/runtime.dart create mode 100644 lib/src/frb/api/source.dart create mode 100644 lib/src/frb/api/source.freezed.dart create mode 100644 libfjs/src/api/engine.rs create mode 100644 libfjs/src/api/error.rs delete mode 100644 libfjs/src/api/js.rs create mode 100644 libfjs/src/api/runtime.rs create mode 100644 libfjs/src/api/source.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 21f0d3d..b0ceaf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.3.1 + +* **PERFORMANCE**: Optimized BigInt conversion using native rquickjs API instead of JavaScript evaluation +* **PERFORMANCE**: Improved Symbol description extraction using native rquickjs Symbol API +* **PERFORMANCE**: Simplified file reading with direct `tokio::fs::read()` call +* **FIX**: Fixed `DynamicModuleResolver` to properly check module existence before resolving +* **FIX**: Fixed `build_loaders()` to properly include additional modules in resolver and loader chains +* **FIX**: Fixed `GlobalAttachment` to correctly initialize each context independently using context-level userdata +* **INTERNAL**: Removed unused variable in bridge call function +* **INTERNAL**: Improved code clarity and reduced redundant logic + ## 1.3.0 * **FEATURE**: Added `JsCode.bytes()` variant for direct `Uint8List` support from Dart diff --git a/example/lib/app/app.dart b/example/lib/app/app.dart index c7559da..83e3cd1 100644 --- a/example/lib/app/app.dart +++ b/example/lib/app/app.dart @@ -1,11 +1,9 @@ -import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; -import '../app/router.dart'; -import '../app/theme.dart'; - +import 'router.dart'; +import 'theme.dart'; +import 'home_screen.dart'; import '../services/fjs_service.dart'; import '../services/js_actions_service.dart'; import '../services/js_examples_service.dart'; @@ -23,15 +21,15 @@ class FjsExampleApp extends StatelessWidget { ChangeNotifierProvider(create: (_) => JsExamplesService()), ChangeNotifierProvider(create: (_) => StorageService()), ], - child: Consumer3( - builder: (context, storageService, fjsService, examplesService, child) { + child: Consumer( + builder: (context, storageService, child) { return MaterialApp( title: 'FJS - JavaScript Runtime', debugShowCheckedModeBanner: false, theme: AppTheme.lightTheme, darkTheme: AppTheme.darkTheme, themeMode: storageService.themeMode, - home: const HomePage(), + home: const HomeScreen(), onGenerateRoute: AppRouter.onGenerateRoute, ); }, @@ -39,655 +37,3 @@ class FjsExampleApp extends StatelessWidget { ); } } - -class HomePage extends StatefulWidget { - const HomePage({super.key}); - - @override - State createState() => _HomePageState(); -} - -class _HomePageState extends State { - final TextEditingController _codeController = TextEditingController(); - String _result = ''; - bool _isExecuting = false; - bool _copiedToClipboard = false; - - @override - void dispose() { - _codeController.dispose(); - super.dispose(); - } - - Future _executeCode() async { - if (_codeController.text.trim().isEmpty) return; - - setState(() { - _isExecuting = true; - _result = ''; - }); - - try { - final fjsService = Provider.of(context, listen: false); - - // Check for import statements to auto-select mode - final hasImport = RegExp( - r'^\s*import\s+.*\s+from\s+', - multiLine: true, - ).hasMatch(_codeController.text); - - dynamic result; - if (hasImport) { - result = await fjsService.executeAsModule(_codeController.text); - } else { - result = await fjsService.executeAsScript(_codeController.text); - } - - setState(() { - _result = JsonEncoder.withIndent(' ').convert(result.value); - }); - } catch (e) { - setState(() { - _result = 'Error: $e'; - }); - } finally { - setState(() { - _isExecuting = false; - }); - } - } - - Future _copyResultToClipboard() async { - if (_result.trim().isEmpty) return; - - try { - await Clipboard.setData(ClipboardData(text: _result)); - - setState(() { - _copiedToClipboard = true; - }); - - // Reset the copied state after 2 seconds - Future.delayed(const Duration(seconds: 2), () { - if (mounted) { - setState(() { - _copiedToClipboard = false; - }); - } - }); - - // Show a snackbar for better feedback - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: const Text('Result copied to clipboard!'), - duration: const Duration(seconds: 1), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - margin: const EdgeInsets.all(16), - ), - ); - } - } catch (e) { - // Show error message if copy fails - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Failed to copy: $e'), - backgroundColor: Colors.red, - duration: const Duration(seconds: 2), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - margin: const EdgeInsets.all(16), - ), - ); - } - } - } - - Future _copyCodeToClipboard() async { - if (_codeController.text.trim().isEmpty) return; - - try { - await Clipboard.setData(ClipboardData(text: _codeController.text)); - - // Show a snackbar for feedback - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: const Text('Code copied to clipboard!'), - duration: const Duration(seconds: 1), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - margin: const EdgeInsets.all(16), - ), - ); - } - } catch (e) { - // Show error message if copy fails - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Failed to copy: $e'), - backgroundColor: Colors.red, - duration: const Duration(seconds: 2), - behavior: SnackBarBehavior.floating, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - margin: const EdgeInsets.all(16), - ), - ); - } - } - } - - @override - Widget build(BuildContext context) { - final screenWidth = MediaQuery.of(context).size.width; - final screenHeight = MediaQuery.of(context).size.height; - final isTablet = screenWidth >= 600; - final isDesktop = screenWidth >= 1200; - - // Responsive padding - final horizontalPadding = isDesktop ? 32.0 : (isTablet ? 24.0 : 16.0); - final verticalPadding = isDesktop ? 24.0 : (isTablet ? 20.0 : 16.0); - - return Scaffold( - appBar: AppBar( - title: const Text('FJS JavaScript Runtime'), - actions: [ - IconButton( - icon: const Icon(Icons.play_circle_outline), - onPressed: _executeCode, - tooltip: 'Execute Code', - ), - Consumer( - builder: (context, storageService, child) { - return IconButton( - icon: Icon( - storageService.themeMode == ThemeMode.dark - ? Icons.light_mode - : Icons.dark_mode, - ), - onPressed: () { - storageService.toggleTheme(); - }, - tooltip: 'Toggle Theme', - ); - }, - ), - PopupMenuButton( - onSelected: (value) { - if (value == 'playground') { - Navigator.pushNamed(context, '/playground'); - } else if (value == 'js-actions-test') { - Navigator.pushNamed(context, '/js-actions-test'); - } - }, - itemBuilder: (context) => [ - const PopupMenuItem( - value: 'playground', - child: Row( - children: [ - Icon(Icons.code), - SizedBox(width: 8), - Text('Playground'), - ], - ), - ), - const PopupMenuItem( - value: 'js-actions-test', - child: Row( - children: [ - Icon(Icons.science), - SizedBox(width: 8), - Text('JsActions Test'), - ], - ), - ), - ], - ), - ], - ), - body: SingleChildScrollView( - padding: EdgeInsets.symmetric( - horizontal: horizontalPadding, - vertical: verticalPadding, - ), - child: ConstrainedBox( - constraints: BoxConstraints( - minHeight: screenHeight - - AppBar().preferredSize.height - - MediaQuery.of(context).padding.top - - MediaQuery.of(context).padding.bottom - - verticalPadding * 2, - ), - child: isDesktop - ? _buildDesktopLayout(context) - : (isTablet - ? _buildTabletLayout(context) - : _buildMobileLayout(context)), - ), - ), - ); - } - - // Mobile layout (vertical stack) - Widget _buildMobileLayout(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _buildCodeEditorSection(context, height: 200), - const SizedBox(height: 16), - _buildResultSection(context), - const SizedBox(height: 16), - _buildExamplesSection(context), - ], - ); - } - - // Tablet layout (vertical stack with more space) - Widget _buildTabletLayout(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _buildCodeEditorSection(context, height: 250), - const SizedBox(height: 20), - _buildResultSection(context), - const SizedBox(height: 20), - _buildExamplesSection(context), - ], - ); - } - - // Desktop layout (side-by-side) - Widget _buildDesktopLayout(BuildContext context) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Top row with code editor and result - IntrinsicHeight( - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Code editor (left side) - Expanded( - flex: 3, - child: _buildCodeEditorSection(context, height: 400), - ), - const SizedBox(width: 20), - // Result (right side) - Expanded( - flex: 2, - child: _buildResultSection(context), - ), - ], - ), - ), - const SizedBox(height: 20), - // Examples section (bottom) - _buildExamplesSection(context), - ], - ); - } - - Widget _buildCodeEditorSection(BuildContext context, - {required double height}) { - return Card( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon( - Icons.code, - size: 20, - color: Theme.of(context).colorScheme.primary, - ), - const SizedBox(width: 8), - Text( - 'JavaScript Code', - style: Theme.of(context).textTheme.titleMedium, - ), - const Spacer(), - // Copy code button - if (_codeController.text.trim().isNotEmpty) - Container( - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(20), - ), - child: IconButton.filled( - onPressed: _isExecuting ? null : _copyCodeToClipboard, - icon: const Icon(Icons.copy, size: 18), - iconSize: 18, - style: IconButton.styleFrom( - minimumSize: const Size(36, 36), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - ), - tooltip: 'Copy Code', - ), - ), - ], - ), - const SizedBox(height: 12), - Container( - height: height, - constraints: const BoxConstraints( - minHeight: 150, - maxHeight: 500, - ), - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: Theme.of(context) - .colorScheme - .outline - .withValues(alpha: 0.2), - ), - ), - child: TextField( - controller: _codeController, - maxLines: null, - expands: true, - style: const TextStyle( - fontFamily: 'monospace', - fontSize: 14, - ), - decoration: const InputDecoration( - border: InputBorder.none, - contentPadding: EdgeInsets.all(12), - hintText: - '// Enter your JavaScript code here...\nconsole.log("Hello, FJS!");', - ), - ), - ), - const SizedBox(height: 16), - SizedBox( - width: double.infinity, - child: FilledButton.icon( - onPressed: _isExecuting ? null : _executeCode, - icon: _isExecuting - ? const SizedBox( - width: 16, - height: 16, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Icon(Icons.play_arrow), - label: Text(_isExecuting ? 'Executing...' : 'Execute Code'), - ), - ), - ], - ), - ), - ); - } - - Widget _buildResultSection(BuildContext context) { - return Card( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon( - Icons.output, - size: 20, - color: Theme.of(context).colorScheme.primary, - ), - const SizedBox(width: 8), - Text( - 'Result', - style: Theme.of(context).textTheme.titleMedium, - ), - const Spacer(), - // Copy result button with dynamic state - if (_result.isNotEmpty) - Container( - decoration: BoxDecoration( - color: _copiedToClipboard - ? Colors.green.shade100 - : Theme.of(context).colorScheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: _copiedToClipboard - ? Colors.green.shade300 - : Colors.transparent, - ), - ), - child: IconButton.filled( - onPressed: _isExecuting ? null : _copyResultToClipboard, - icon: Icon( - _copiedToClipboard - ? Icons.check_circle - : Icons.copy, - size: 18, - ), - iconSize: 18, - style: IconButton.styleFrom( - backgroundColor: _copiedToClipboard - ? Colors.green.shade200 - : null, - foregroundColor: _copiedToClipboard - ? Colors.green.shade700 - : null, - minimumSize: const Size(36, 36), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - ), - tooltip: _copiedToClipboard ? 'Copied!' : 'Copy Result', - ), - ), - const SizedBox(width: 8), - if (_result.isNotEmpty) - IconButton( - icon: const Icon(Icons.clear, size: 20), - onPressed: () { - setState(() { - _result = ''; - }); - }, - tooltip: 'Clear Result', - ), - ], - ), - const SizedBox(height: 12), - Container( - width: double.infinity, - constraints: const BoxConstraints( - minHeight: 100, - maxHeight: 300, - ), - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: _result.startsWith('Error:') - ? Colors.red.shade50 - : Colors.green.shade50, - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: _result.startsWith('Error:') - ? Colors.red.shade200 - : Colors.green.shade200, - ), - ), - child: SingleChildScrollView( - child: _result.isEmpty - ? Text( - 'Result will appear here...', - style: TextStyle( - color: Colors.grey.shade600, - fontStyle: FontStyle.italic, - ), - ) - : Text( - _result, - style: TextStyle( - fontFamily: 'monospace', - fontSize: 14, - color: _result.startsWith('Error:') - ? Colors.red.shade700 - : Colors.green.shade700, - ), - ), - ), - ), - ], - ), - ), - ); - } - - Widget _buildExamplesSection(BuildContext context) { - return Consumer( - builder: (context, examplesService, child) { - if (examplesService.isLoading) { - return Card( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Center( - child: Column( - children: [ - const CircularProgressIndicator(), - const SizedBox(height: 16), - Text( - 'Loading examples...', - style: Theme.of(context).textTheme.bodyMedium, - ), - ], - ), - ), - ), - ); - } - - if (examplesService.error != null) { - return Card( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Column( - children: [ - Icon(Icons.error_outline, color: Colors.red), - const SizedBox(height: 8), - Text( - 'Error loading examples', - style: Theme.of(context).textTheme.titleMedium, - ), - const SizedBox(height: 8), - Text( - examplesService.error!, - style: Theme.of(context).textTheme.bodySmall, - textAlign: TextAlign.center, - ), - ], - ), - ), - ); - } - - return Card( - child: Padding( - padding: const EdgeInsets.all(16.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - Icon( - Icons.lightbulb_outline, - size: 20, - color: Theme.of(context).colorScheme.primary, - ), - const SizedBox(width: 8), - Text( - 'Quick Examples', - style: Theme.of(context).textTheme.titleMedium, - ), - ], - ), - const SizedBox(height: 12), - // Build examples from JsExamplesService - ...JsExampleCategory.values.map((category) { - final examples = examplesService.getExamplesByCategory(category); - if (examples.isEmpty) return const SizedBox.shrink(); - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - category.displayName, - style: const TextStyle( - fontSize: 14, - fontWeight: FontWeight.w500, - color: Colors.grey, - ), - ), - const SizedBox(height: 8), - Wrap( - spacing: 8, - runSpacing: 8, - children: examples.map((example) => - _ExampleChip( - label: example.label, - fileName: example.fileName, - executionMode: example.executionMode, - onPressed: () => _loadAndSetExample(example), - ), - ).toList(), - ), - if (category != JsExampleCategory.values.last) - const SizedBox(height: 16), - ], - ); - }), - ], - ), - ), - ); - }, - ); - } - - Future _loadAndSetExample(JsExample example) async { - final examplesService = Provider.of(context, listen: false); - - final code = await examplesService.loadExampleCode(example.fileName); - if (code != null) { - _codeController.text = code; - } - } - - -} - -class _ExampleChip extends StatelessWidget { - final String label; - final String fileName; - final VoidCallback onPressed; - final JsExecutionMode? executionMode; - - const _ExampleChip({ - required this.label, - required this.fileName, - required this.onPressed, - this.executionMode, - }); - - @override - Widget build(BuildContext context) { - return ActionChip( - label: Text(label), - onPressed: onPressed, - ); - } -} diff --git a/example/lib/app/home_screen.dart b/example/lib/app/home_screen.dart new file mode 100644 index 0000000..9dd1484 --- /dev/null +++ b/example/lib/app/home_screen.dart @@ -0,0 +1,806 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; + +import '../services/fjs_service.dart'; +import '../services/js_examples_service.dart'; +import '../services/storage_service.dart'; +import '../widgets/widgets.dart'; + +/// Home screen with navigation to all features +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key}); + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + final TextEditingController _codeController = TextEditingController(); + String _result = ''; + bool _isExecuting = false; + bool _copiedToClipboard = false; + int _selectedNavIndex = 0; + + @override + void dispose() { + _codeController.dispose(); + super.dispose(); + } + + Future _executeCode() async { + if (_codeController.text.trim().isEmpty) return; + + setState(() { + _isExecuting = true; + _result = ''; + }); + + try { + final fjsService = Provider.of(context, listen: false); + + // Check for import statements to auto-select mode + final hasImport = RegExp( + r'^\s*import\s+.*\s+from\s+', + multiLine: true, + ).hasMatch(_codeController.text); + + dynamic result; + if (hasImport) { + result = await fjsService.executeAsModule(_codeController.text); + } else { + result = await fjsService.executeAsScript(_codeController.text); + } + + setState(() { + _result = const JsonEncoder.withIndent(' ').convert(result.value); + }); + } catch (e) { + setState(() { + _result = 'Error: $e'; + }); + } finally { + setState(() { + _isExecuting = false; + }); + } + } + + Future _copyResultToClipboard() async { + if (_result.trim().isEmpty) return; + + try { + await Clipboard.setData(ClipboardData(text: _result)); + + setState(() { + _copiedToClipboard = true; + }); + + Future.delayed(const Duration(seconds: 2), () { + if (mounted) { + setState(() { + _copiedToClipboard = false; + }); + } + }); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Result copied to clipboard!'), + duration: const Duration(seconds: 1), + behavior: SnackBarBehavior.floating, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + margin: const EdgeInsets.all(16), + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to copy: $e'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 2), + ), + ); + } + } + } + + @override + Widget build(BuildContext context) { + final isDesktop = ResponsiveLayout.isDesktop(context); + + if (isDesktop) { + return _buildDesktopLayout(context); + } + return _buildMobileLayout(context); + } + + Widget _buildMobileLayout(BuildContext context) { + return Scaffold( + appBar: _buildAppBar(context), + drawer: _buildDrawer(context), + body: SingleChildScrollView( + padding: EdgeInsets.all(ResponsiveLayout.horizontalPadding(context)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildWelcomeCard(context), + const SizedBox(height: 16), + _buildQuickActionsCard(context), + const SizedBox(height: 16), + _buildCodeEditorSection(context), + const SizedBox(height: 16), + _buildResultSection(context), + const SizedBox(height: 16), + _buildExamplesSection(context), + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildDesktopLayout(BuildContext context) { + return Scaffold( + body: Row( + children: [ + // Side navigation + NavigationRail( + selectedIndex: _selectedNavIndex, + onDestinationSelected: (index) { + setState(() => _selectedNavIndex = index); + _handleNavigation(index); + }, + labelType: NavigationRailLabelType.all, + leading: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + Icons.javascript, + color: Theme.of(context).colorScheme.primary, + ), + ), + const SizedBox(height: 4), + Text( + 'FJS', + style: Theme.of(context).textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + trailing: Expanded( + child: Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Consumer( + builder: (context, storageService, _) { + return IconButton( + icon: Icon( + storageService.themeMode == ThemeMode.dark + ? Icons.light_mode + : Icons.dark_mode, + ), + onPressed: () => storageService.toggleTheme(), + tooltip: 'Toggle Theme', + ); + }, + ), + ), + ), + ), + destinations: const [ + NavigationRailDestination( + icon: Icon(Icons.home_outlined), + selectedIcon: Icon(Icons.home), + label: Text('Home'), + ), + NavigationRailDestination( + icon: Icon(Icons.code_outlined), + selectedIcon: Icon(Icons.code), + label: Text('Playground'), + ), + NavigationRailDestination( + icon: Icon(Icons.api_outlined), + selectedIcon: Icon(Icons.api), + label: Text('API'), + ), + NavigationRailDestination( + icon: Icon(Icons.science_outlined), + selectedIcon: Icon(Icons.science), + label: Text('Tests'), + ), + ], + ), + const VerticalDivider(width: 1), + // Main content + Expanded( + child: Scaffold( + appBar: _buildAppBar(context, showDrawer: false), + body: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedContent( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _buildWelcomeCard(context), + const SizedBox(height: 24), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + flex: 3, + child: Column( + children: [ + _buildCodeEditorSection(context), + const SizedBox(height: 16), + _buildExamplesSection(context), + ], + ), + ), + const SizedBox(width: 24), + Expanded( + flex: 2, + child: Column( + children: [ + _buildQuickActionsCard(context), + const SizedBox(height: 16), + _buildResultSection(context), + ], + ), + ), + ], + ), + const SizedBox(height: 32), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } + + void _handleNavigation(int index) { + switch (index) { + case 0: + // Already on home + break; + case 1: + Navigator.pushNamed(context, '/playground'); + break; + case 2: + Navigator.pushNamed(context, '/api'); + break; + case 3: + Navigator.pushNamed(context, '/js-actions-test'); + break; + } + } + + PreferredSizeWidget _buildAppBar(BuildContext context, {bool showDrawer = true}) { + return AppBar( + title: const Text('FJS JavaScript Runtime'), + automaticallyImplyLeading: showDrawer, + actions: [ + IconButton( + icon: const Icon(Icons.play_circle_outline), + onPressed: _executeCode, + tooltip: 'Execute Code', + ), + if (!ResponsiveLayout.isDesktop(context)) + Consumer( + builder: (context, storageService, child) { + return IconButton( + icon: Icon( + storageService.themeMode == ThemeMode.dark + ? Icons.light_mode + : Icons.dark_mode, + ), + onPressed: () => storageService.toggleTheme(), + tooltip: 'Toggle Theme', + ); + }, + ), + PopupMenuButton( + onSelected: (value) { + switch (value) { + case 'playground': + Navigator.pushNamed(context, '/playground'); + break; + case 'api': + Navigator.pushNamed(context, '/api'); + break; + case 'js-actions-test': + Navigator.pushNamed(context, '/js-actions-test'); + break; + } + }, + itemBuilder: (context) => [ + const PopupMenuItem( + value: 'playground', + child: Row( + children: [ + Icon(Icons.code), + SizedBox(width: 8), + Text('Playground'), + ], + ), + ), + const PopupMenuItem( + value: 'api', + child: Row( + children: [ + Icon(Icons.api), + SizedBox(width: 8), + Text('API Reference'), + ], + ), + ), + const PopupMenuItem( + value: 'js-actions-test', + child: Row( + children: [ + Icon(Icons.science), + SizedBox(width: 8), + Text('JsActions Test'), + ], + ), + ), + ], + ), + ], + ); + } + + Widget _buildDrawer(BuildContext context) { + return Drawer( + child: ListView( + padding: EdgeInsets.zero, + children: [ + DrawerHeader( + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + Theme.of(context).colorScheme.primary, + Theme.of(context).colorScheme.secondary, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Icon( + Icons.javascript, + size: 48, + color: Theme.of(context).colorScheme.onPrimary, + ), + const SizedBox(height: 8), + Text( + 'FJS', + style: Theme.of(context).textTheme.headlineSmall?.copyWith( + color: Theme.of(context).colorScheme.onPrimary, + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Flutter JavaScript Runtime', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onPrimary.withValues(alpha: 0.8), + ), + ), + ], + ), + ), + ListTile( + leading: const Icon(Icons.home), + title: const Text('Home'), + selected: true, + onTap: () => Navigator.pop(context), + ), + ListTile( + leading: const Icon(Icons.code), + title: const Text('Playground'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/playground'); + }, + ), + const Divider(), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Text( + 'API Reference', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Colors.grey, + ), + ), + ), + ListTile( + leading: const Icon(Icons.api), + title: const Text('Overview'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api'); + }, + ), + ListTile( + leading: const Icon(Icons.memory), + title: const Text('JsEngine'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api/engine'); + }, + ), + ListTile( + leading: const Icon(Icons.play_arrow), + title: const Text('JsRuntime'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api/runtime'); + }, + ), + ListTile( + leading: const Icon(Icons.data_object), + title: const Text('JsValue'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api/value'); + }, + ), + ListTile( + leading: const Icon(Icons.error_outline), + title: const Text('JsError'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api/error'); + }, + ), + ListTile( + leading: const Icon(Icons.code), + title: const Text('Source'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/api/source'); + }, + ), + const Divider(), + ListTile( + leading: const Icon(Icons.science), + title: const Text('JsActions Test'), + onTap: () { + Navigator.pop(context); + Navigator.pushNamed(context, '/js-actions-test'); + }, + ), + ], + ), + ); + } + + Widget _buildWelcomeCard(BuildContext context) { + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + theme.colorScheme.primaryContainer, + theme.colorScheme.secondaryContainer, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.javascript, + size: 32, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Welcome to FJS', + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Flutter JavaScript Runtime powered by QuickJS', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onPrimaryContainer, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + _FeatureChip(icon: Icons.speed, label: 'Fast'), + _FeatureChip(icon: Icons.security, label: 'Safe'), + _FeatureChip(icon: Icons.sync, label: 'Async'), + _FeatureChip(icon: Icons.view_module, label: 'Modules'), + ], + ), + ], + ), + ); + } + + Widget _buildQuickActionsCard(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.flash_on, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Quick Actions', + style: Theme.of(context).textTheme.titleMedium, + ), + ], + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + FilledButton.tonalIcon( + onPressed: () => Navigator.pushNamed(context, '/playground'), + icon: const Icon(Icons.code), + label: const Text('Playground'), + ), + FilledButton.tonalIcon( + onPressed: () => Navigator.pushNamed(context, '/api'), + icon: const Icon(Icons.api), + label: const Text('API Docs'), + ), + FilledButton.tonalIcon( + onPressed: () => Navigator.pushNamed(context, '/js-actions-test'), + icon: const Icon(Icons.science), + label: const Text('Run Tests'), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildCodeEditorSection(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.code, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'JavaScript Code', + style: Theme.of(context).textTheme.titleMedium, + ), + ], + ), + const SizedBox(height: 12), + CodeEditorWidget( + controller: _codeController, + hintText: '// Enter your JavaScript code here...\nconsole.log("Hello, FJS!");', + height: 200, + isLoading: _isExecuting, + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: _isExecuting ? null : _executeCode, + icon: _isExecuting + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.play_arrow), + label: Text(_isExecuting ? 'Executing...' : 'Execute Code'), + ), + ), + ], + ), + ), + ); + } + + Widget _buildResultSection(BuildContext context) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.output, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Result', + style: Theme.of(context).textTheme.titleMedium, + ), + const Spacer(), + if (_result.isNotEmpty) + IconButton( + icon: Icon( + _copiedToClipboard ? Icons.check : Icons.copy, + size: 18, + ), + onPressed: _copyResultToClipboard, + tooltip: 'Copy Result', + ), + if (_result.isNotEmpty) + IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () => setState(() => _result = ''), + tooltip: 'Clear', + ), + ], + ), + const SizedBox(height: 12), + ResultDisplayWidget( + result: _result.isNotEmpty && !_result.startsWith('Error:') ? _result : null, + error: _result.startsWith('Error:') ? _result : null, + isLoading: _isExecuting, + height: 200, + ), + ], + ), + ), + ); + } + + Widget _buildExamplesSection(BuildContext context) { + return Consumer( + builder: (context, examplesService, child) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.lightbulb_outline, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Quick Examples', + style: Theme.of(context).textTheme.titleMedium, + ), + ], + ), + const SizedBox(height: 12), + ...JsExampleCategory.values.take(4).map((category) { + final examples = examplesService.getExamplesByCategory(category); + if (examples.isEmpty) return const SizedBox.shrink(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + category.displayName, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: examples.take(4).map((example) => ActionChip( + label: Text(example.label), + onPressed: () => _loadExample(example), + )).toList(), + ), + const SizedBox(height: 12), + ], + ); + }), + ], + ), + ), + ); + }, + ); + } + + Future _loadExample(JsExample example) async { + final examplesService = Provider.of(context, listen: false); + final code = await examplesService.loadExampleCode(example.fileName); + if (code != null) { + _codeController.text = code; + } + } +} + +class _FeatureChip extends StatelessWidget { + final IconData icon; + final String label; + + const _FeatureChip({required this.icon, required this.label}); + + @override + Widget build(BuildContext context) { + return Chip( + avatar: Icon(icon, size: 16), + label: Text(label), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + ); + } +} diff --git a/example/lib/app/router.dart b/example/lib/app/router.dart index 7af7340..3074480 100644 --- a/example/lib/app/router.dart +++ b/example/lib/app/router.dart @@ -1,14 +1,21 @@ import 'package:flutter/material.dart'; -import '../screens/playground_screen.dart'; + +import '../screens/api_overview_screen.dart'; +import '../screens/engine_api_screen.dart'; +import '../screens/error_api_screen.dart'; import '../screens/js_actions_test_screen.dart'; -import '../app/app.dart'; +import '../screens/playground_screen.dart'; +import '../screens/runtime_api_screen.dart'; +import '../screens/source_api_screen.dart'; +import '../screens/value_api_screen.dart'; +import 'home_screen.dart'; class AppRouter { static Route onGenerateRoute(RouteSettings settings) { switch (settings.name) { case '/': return MaterialPageRoute( - builder: (_) => const HomePage(), + builder: (_) => const HomeScreen(), ); case '/playground': return MaterialPageRoute( @@ -18,9 +25,33 @@ class AppRouter { return MaterialPageRoute( builder: (_) => const JsActionsTestScreen(), ); + case '/api': + return MaterialPageRoute( + builder: (_) => const ApiOverviewScreen(), + ); + case '/api/engine': + return MaterialPageRoute( + builder: (_) => const EngineApiScreen(), + ); + case '/api/runtime': + return MaterialPageRoute( + builder: (_) => const RuntimeApiScreen(), + ); + case '/api/value': + return MaterialPageRoute( + builder: (_) => const ValueApiScreen(), + ); + case '/api/error': + return MaterialPageRoute( + builder: (_) => const ErrorApiScreen(), + ); + case '/api/source': + return MaterialPageRoute( + builder: (_) => const SourceApiScreen(), + ); default: return MaterialPageRoute( - builder: (_) => const HomePage(), + builder: (_) => const HomeScreen(), ); } } diff --git a/example/lib/screens/api_overview_screen.dart b/example/lib/screens/api_overview_screen.dart new file mode 100644 index 0000000..b086664 --- /dev/null +++ b/example/lib/screens/api_overview_screen.dart @@ -0,0 +1,362 @@ +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Main API overview screen with navigation to all API test screens +class ApiOverviewScreen extends StatelessWidget { + const ApiOverviewScreen({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar( + title: const Text('FJS API Reference'), + centerTitle: true, + ), + body: SingleChildScrollView( + child: ConstrainedContent( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Hero section + _buildHeroSection(context), + const SizedBox(height: 24), + + // API Categories + Text( + 'API Categories', + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + _buildApiGrid(context), + + const SizedBox(height: 32), + + // Quick Reference + Text( + 'Quick Reference', + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + _buildQuickReference(context), + + const SizedBox(height: 32), + ], + ), + ), + ), + ); + } + + Widget _buildHeroSection(BuildContext context) { + final theme = Theme.of(context); + + return Container( + width: double.infinity, + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + theme.colorScheme.primaryContainer, + theme.colorScheme.secondaryContainer, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.api, + size: 32, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'FJS API Reference', + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Complete API documentation and interactive tests', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onPrimaryContainer, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + _buildChip(context, 'JsEngine', Icons.memory), + _buildChip(context, 'JsRuntime', Icons.play_arrow), + _buildChip(context, 'JsValue', Icons.data_object), + _buildChip(context, 'JsError', Icons.error_outline), + _buildChip(context, 'JsModule', Icons.view_module), + ], + ), + ], + ), + ); + } + + Widget _buildChip(BuildContext context, String label, IconData icon) { + return Chip( + avatar: Icon(icon, size: 16), + label: Text(label), + visualDensity: VisualDensity.compact, + ); + } + + Widget _buildApiGrid(BuildContext context) { + final apis = [ + _ApiCategory( + title: 'JsEngine', + subtitle: 'High-level JavaScript engine API', + icon: Icons.memory, + color: Colors.blue, + route: '/api/engine', + features: ['eval()', 'modules', 'bridge'], + ), + _ApiCategory( + title: 'JsRuntime', + subtitle: 'Runtime and context management', + icon: Icons.play_arrow, + color: Colors.green, + route: '/api/runtime', + features: ['memory', 'gc', 'jobs'], + ), + _ApiCategory( + title: 'JsValue', + subtitle: 'Value types and conversion', + icon: Icons.data_object, + color: Colors.orange, + route: '/api/value', + features: ['types', 'conversion', 'checks'], + ), + _ApiCategory( + title: 'JsError', + subtitle: 'Error handling and types', + icon: Icons.error_outline, + color: Colors.red, + route: '/api/error', + features: ['errors', 'JsResult', 'recovery'], + ), + _ApiCategory( + title: 'Source', + subtitle: 'Code, modules, and options', + icon: Icons.code, + color: Colors.purple, + route: '/api/source', + features: ['JsCode', 'JsModule', 'options'], + ), + ]; + + return ResponsiveLayout( + mobile: Column( + children: apis.map((api) => _buildApiCard(context, api)).toList(), + ), + tablet: GridView.count( + crossAxisCount: 2, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 16, + crossAxisSpacing: 16, + childAspectRatio: 1.5, + children: apis.map((api) => _buildApiCard(context, api)).toList(), + ), + desktop: GridView.count( + crossAxisCount: 3, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 16, + crossAxisSpacing: 16, + childAspectRatio: 1.3, + children: apis.map((api) => _buildApiCard(context, api)).toList(), + ), + ); + } + + Widget _buildApiCard(BuildContext context, _ApiCategory api) { + final theme = Theme.of(context); + + return Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => Navigator.pushNamed(context, api.route), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: api.color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(api.icon, color: api.color), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + api.title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + api.subtitle, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + Icon( + Icons.arrow_forward_ios, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + ], + ), + const Spacer(), + Wrap( + spacing: 6, + runSpacing: 6, + children: api.features.map((f) => Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(4), + ), + child: Text( + f, + style: theme.textTheme.labelSmall, + ), + )).toList(), + ), + ], + ), + ), + ), + ); + } + + Widget _buildQuickReference(BuildContext context) { + final theme = Theme.of(context); + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Basic Usage', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 12), + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(8), + ), + child: SelectableText( + '''// Initialize +final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), +); +final context = await JsAsyncContext.from(rt: runtime); +final engine = JsEngine(context); +await engine.init(); + +// Evaluate code +final result = await engine.eval( + JsCode.code('Math.random() * 100'), +); +print(result.value); + +// Declare modules +await engine.declareNewModule( + JsModule.fromCode( + module: 'utils', + code: 'export function add(a, b) { return a + b; }', + ), +); + +// Cleanup +await engine.dispose();''', + style: TextStyle( + fontFamily: 'monospace', + fontSize: 13, + color: theme.colorScheme.onSurface, + ), + ), + ), + ], + ), + ); + } +} + +class _ApiCategory { + final String title; + final String subtitle; + final IconData icon; + final Color color; + final String route; + final List features; + + _ApiCategory({ + required this.title, + required this.subtitle, + required this.icon, + required this.color, + required this.route, + required this.features, + }); +} diff --git a/example/lib/screens/engine_api_screen.dart b/example/lib/screens/engine_api_screen.dart new file mode 100644 index 0000000..ca8bfd4 --- /dev/null +++ b/example/lib/screens/engine_api_screen.dart @@ -0,0 +1,629 @@ + +import 'package:fjs/fjs.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Screen to test JsEngine APIs - the main high-level API +class EngineApiScreen extends StatefulWidget { + const EngineApiScreen({super.key}); + + @override + State createState() => _EngineApiScreenState(); +} + +class _EngineApiScreenState extends State { + JsAsyncRuntime? _runtime; + JsAsyncContext? _context; + JsEngine? _engine; + bool _isInitialized = false; + bool _isLoading = false; + + final Map _testResults = {}; + final TextEditingController _codeController = TextEditingController(); + + @override + void initState() { + super.initState(); + _initializeEngine(); + _codeController.text = '2 + 2'; + } + + Future _initializeEngine() async { + setState(() => _isLoading = true); + try { + _runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + _context = await JsAsyncContext.from(rt: _runtime!); + _engine = JsEngine(_context!); + await _engine!.init( + bridgeCall: (value) async { + if (kDebugMode) { + print('Bridge call received: ${value.value}'); + } + return JsValue.string('Response from Dart: ${value.value}'); + }, + ); + setState(() => _isInitialized = true); + } catch (e) { + if (kDebugMode) print('Failed to initialize engine: $e'); + } finally { + setState(() => _isLoading = false); + } + } + + Future _runTest(String testId, Future Function() test) async { + setState(() { + _testResults[testId] = _TestResult(isLoading: true); + }); + try { + final result = await test(); + setState(() { + _testResults[testId] = _TestResult( + isSuccess: true, + result: result, + ); + }); + } catch (e) { + setState(() { + _testResults[testId] = _TestResult( + isSuccess: false, + error: e.toString(), + ); + }); + } + } + + @override + void dispose() { + _engine?.dispose(); + _codeController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('JsEngine API Tests'), + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () async { + await _engine?.dispose(); + setState(() { + _isInitialized = false; + _testResults.clear(); + }); + await _initializeEngine(); + }, + tooltip: 'Reinitialize Engine', + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : SingleChildScrollView( + child: Column( + children: [ + _buildStatusBar(), + + // Engine Status + const ApiTestSection( + title: 'Engine Status', + description: 'Check engine state', + icon: Icons.info, + ), + _buildStatusTests(), + + // Code Evaluation + const ApiTestSection( + title: 'Code Evaluation', + description: 'Test eval() and options', + icon: Icons.code, + ), + _buildEvalTests(), + + // Module Management + const ApiTestSection( + title: 'Module Management', + description: 'Test module declaration and evaluation', + icon: Icons.view_module, + ), + _buildModuleTests(), + + // Bridge Communication + const ApiTestSection( + title: 'Bridge Communication', + description: 'Test Dart-JS bridge', + icon: Icons.sync_alt, + ), + _buildBridgeTests(), + + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildStatusBar() { + return Container( + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: _isInitialized ? Colors.green.shade50 : Colors.orange.shade50, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: _isInitialized ? Colors.green.shade200 : Colors.orange.shade200, + ), + ), + child: Row( + children: [ + Icon( + _isInitialized ? Icons.check_circle : Icons.warning, + color: _isInitialized ? Colors.green : Colors.orange, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _isInitialized ? 'Engine Ready' : 'Engine Not Ready', + style: TextStyle( + fontWeight: FontWeight.w600, + color: _isInitialized + ? Colors.green.shade700 + : Colors.orange.shade700, + ), + ), + if (_engine != null) + Text( + 'initialized: ${_engine!.initialized}, running: ${_engine!.running}, disposed: ${_engine!.disposed}', + style: TextStyle( + fontSize: 12, + color: _isInitialized + ? Colors.green.shade600 + : Colors.orange.shade600, + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildStatusTests() { + return Column( + children: [ + ApiTestCard( + title: 'engine.initialized', + subtitle: 'Check if engine is initialized', + icon: Icons.power_settings_new, + isSuccess: _testResults['initialized']?.isSuccess, + isLoading: _testResults['initialized']?.isLoading ?? false, + result: _testResults['initialized']?.result, + error: _testResults['initialized']?.error, + onRun: () => _runTest('initialized', () async { + return {'initialized': _engine?.initialized ?? false}; + }), + ), + ApiTestCard( + title: 'engine.running', + subtitle: 'Check if engine is running', + icon: Icons.play_circle, + isSuccess: _testResults['running']?.isSuccess, + isLoading: _testResults['running']?.isLoading ?? false, + result: _testResults['running']?.result, + error: _testResults['running']?.error, + onRun: () => _runTest('running', () async { + return {'running': _engine?.running ?? false}; + }), + ), + ApiTestCard( + title: 'engine.disposed', + subtitle: 'Check if engine is disposed', + icon: Icons.delete, + isSuccess: _testResults['disposed']?.isSuccess, + isLoading: _testResults['disposed']?.isLoading ?? false, + result: _testResults['disposed']?.result, + error: _testResults['disposed']?.error, + onRun: () => _runTest('disposed', () async { + return {'disposed': _engine?.disposed ?? true}; + }), + ), + ], + ); + } + + Widget _buildEvalTests() { + return Column( + children: [ + // Custom code input + Container( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: CodeEditorWidget( + controller: _codeController, + hintText: '// Enter JavaScript code to evaluate', + height: 120, + ), + ), + ApiTestCard( + title: 'eval(JsCode.code())', + subtitle: 'Evaluate inline JavaScript code', + icon: Icons.play_arrow, + isSuccess: _testResults['eval_code']?.isSuccess, + isLoading: _testResults['eval_code']?.isLoading ?? false, + result: _testResults['eval_code']?.result, + error: _testResults['eval_code']?.error, + onRun: () => _runTest('eval_code', () async { + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code(_codeController.text), + ); + return { + 'code': _codeController.text, + 'result': result.value, + 'typeName': result.typeName(), + }; + }), + ), + ApiTestCard( + title: 'eval() with JsEvalOptions', + subtitle: 'Test different evaluation options', + icon: Icons.tune, + isSuccess: _testResults['eval_options']?.isSuccess, + isLoading: _testResults['eval_options']?.isLoading ?? false, + result: _testResults['eval_options']?.result, + error: _testResults['eval_options']?.error, + onRun: () => _runTest('eval_options', () async { + if (_engine == null) throw 'Engine not initialized'; + + // Test with strict mode + final strictResult = await _engine!.eval( + JsCode.code('"use strict"; let x = 10; x * 2'), + options: JsEvalOptions(strict: true), + ); + + // Test with global scope + final globalResult = await _engine!.eval( + JsCode.code('globalThis.myGlobal = 42; globalThis.myGlobal'), + options: JsEvalOptions(global: true), + ); + + return { + 'strictMode': { + 'result': strictResult.value, + }, + 'globalScope': { + 'result': globalResult.value, + }, + 'optionPresets': { + 'defaults': JsEvalOptions.defaults().toString(), + 'module': JsEvalOptions.module().toString(), + 'withPromise': JsEvalOptions.withPromise().toString(), + }, + }; + }), + ), + ApiTestCard( + title: 'eval() with Promises', + subtitle: 'Test async JavaScript code', + icon: Icons.hourglass_empty, + isSuccess: _testResults['eval_promise']?.isSuccess, + isLoading: _testResults['eval_promise']?.isLoading ?? false, + result: _testResults['eval_promise']?.result, + error: _testResults['eval_promise']?.error, + onRun: () => _runTest('eval_promise', () async { + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code(''' + (async () => { + const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await delay(100); + return "Async result after 100ms"; + })() + '''), + ); + return { + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'eval() Complex Expressions', + subtitle: 'Test various JavaScript expressions', + icon: Icons.calculate, + isSuccess: _testResults['eval_complex']?.isSuccess, + isLoading: _testResults['eval_complex']?.isLoading ?? false, + result: _testResults['eval_complex']?.result, + error: _testResults['eval_complex']?.error, + onRun: () => _runTest('eval_complex', () async { + if (_engine == null) throw 'Engine not initialized'; + + final expressions = { + 'math': 'Math.sqrt(16) + Math.pow(2, 3)', + 'string': '"Hello".split("").reverse().join("")', + 'array': '[1,2,3].map(x => x * 2).filter(x => x > 2)', + 'object': '({name: "FJS", version: "1.0", features: ["fast", "safe"]})', + 'date': 'new Date().toISOString()', + 'json': 'JSON.stringify({a: 1, b: [2, 3]})', + }; + + final results = {}; + for (final entry in expressions.entries) { + final result = await _engine!.eval(JsCode.code(entry.value)); + results[entry.key] = { + 'expression': entry.value, + 'result': result.value, + }; + } + return results; + }), + ), + ], + ); + } + + Widget _buildModuleTests() { + return Column( + children: [ + ApiTestCard( + title: 'declareNewModule()', + subtitle: 'Declare a new module', + icon: Icons.add_box, + isSuccess: _testResults['declare_module']?.isSuccess, + isLoading: _testResults['declare_module']?.isLoading ?? false, + result: _testResults['declare_module']?.result, + error: _testResults['declare_module']?.error, + onRun: () => _runTest('declare_module', () async { + if (_engine == null) throw 'Engine not initialized'; + await _engine!.declareNewModule( + JsModule( + name: 'test-math', + source: JsCode.code(''' + export function add(a, b) { return a + b; } + export function multiply(a, b) { return a * b; } + export const PI = 3.14159; + '''), + ), + ); + return {'status': 'Module "test-math" declared successfully'}; + }), + ), + ApiTestCard( + title: 'declareNewModules()', + subtitle: 'Declare multiple modules at once', + icon: Icons.library_add, + isSuccess: _testResults['declare_modules']?.isSuccess, + isLoading: _testResults['declare_modules']?.isLoading ?? false, + result: _testResults['declare_modules']?.result, + error: _testResults['declare_modules']?.error, + onRun: () => _runTest('declare_modules', () async { + if (_engine == null) throw 'Engine not initialized'; + await _engine!.declareNewModules([ + JsModule( + name: 'string-utils', + source: JsCode.code(''' + export function reverse(s) { return s.split('').reverse().join(''); } + export function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); } + '''), + ), + JsModule( + name: 'array-utils', + source: JsCode.code(''' + export function sum(arr) { return arr.reduce((a, b) => a + b, 0); } + export function unique(arr) { return [...new Set(arr)]; } + '''), + ), + ]); + return {'status': 'Modules declared: string-utils, array-utils'}; + }), + ), + ApiTestCard( + title: 'getDeclaredModules()', + subtitle: 'Get list of declared modules', + icon: Icons.list, + isSuccess: _testResults['get_modules']?.isSuccess, + isLoading: _testResults['get_modules']?.isLoading ?? false, + result: _testResults['get_modules']?.result, + error: _testResults['get_modules']?.error, + onRun: () => _runTest('get_modules', () async { + if (_engine == null) throw 'Engine not initialized'; + final modules = await _engine!.getDeclaredModules(); + return { + 'modules': modules, + 'count': modules.length, + }; + }), + ), + ApiTestCard( + title: 'isModuleDeclared()', + subtitle: 'Check if a module is declared', + icon: Icons.search, + isSuccess: _testResults['is_module_declared']?.isSuccess, + isLoading: _testResults['is_module_declared']?.isLoading ?? false, + result: _testResults['is_module_declared']?.result, + error: _testResults['is_module_declared']?.error, + onRun: () => _runTest('is_module_declared', () async { + if (_engine == null) throw 'Engine not initialized'; + final exists = await _engine!.isModuleDeclared('test-math'); + final notExists = await _engine!.isModuleDeclared('non-existent'); + return { + 'test-math': exists, + 'non-existent': notExists, + }; + }), + ), + ApiTestCard( + title: 'evaluateModule()', + subtitle: 'Evaluate a module directly', + icon: Icons.play_circle_fill, + isSuccess: _testResults['evaluate_module']?.isSuccess, + isLoading: _testResults['evaluate_module']?.isLoading ?? false, + result: _testResults['evaluate_module']?.result, + error: _testResults['evaluate_module']?.error, + onRun: () => _runTest('evaluate_module', () async { + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.evaluateModule( + JsModule( + name: 'eval-test', + source: JsCode.code(''' + export default { + message: "Hello from module", + timestamp: Date.now(), + }; + '''), + ), + ); + return { + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'Use Declared Module', + subtitle: 'Import and use a declared module', + icon: Icons.integration_instructions, + isSuccess: _testResults['use_module']?.isSuccess, + isLoading: _testResults['use_module']?.isLoading ?? false, + result: _testResults['use_module']?.result, + error: _testResults['use_module']?.error, + onRun: () => _runTest('use_module', () async { + if (_engine == null) throw 'Engine not initialized'; + + // First make sure module is declared + await _engine!.declareNewModule( + JsModule( + name: 'calc-module', + source: JsCode.code(''' + export function calculate(a, b, op) { + switch(op) { + case '+': return a + b; + case '-': return a - b; + case '*': return a * b; + case '/': return a / b; + default: throw new Error('Unknown operation'); + } + } + '''), + ), + ); + + // Then use it via dynamic import + final result = await _engine!.eval( + JsCode.code(''' + (async () => { + const { calculate } = await import('calc-module'); + return { + add: calculate(10, 5, '+'), + sub: calculate(10, 5, '-'), + mul: calculate(10, 5, '*'), + div: calculate(10, 5, '/'), + }; + })() + '''), + ); + return result.value; + }), + ), + ApiTestCard( + title: 'clearNewModules()', + subtitle: 'Clear all declared modules', + icon: Icons.delete_sweep, + isSuccess: _testResults['clear_modules']?.isSuccess, + isLoading: _testResults['clear_modules']?.isLoading ?? false, + result: _testResults['clear_modules']?.result, + error: _testResults['clear_modules']?.error, + onRun: () => _runTest('clear_modules', () async { + if (_engine == null) throw 'Engine not initialized'; + await _engine!.clearNewModules(); + final modules = await _engine!.getDeclaredModules(); + return { + 'status': 'All modules cleared', + 'remainingModules': modules, + }; + }), + ), + ], + ); + } + + Widget _buildBridgeTests() { + return Column( + children: [ + ApiTestCard( + title: 'Bridge Call from JS', + subtitle: 'Call Dart function from JavaScript', + icon: Icons.call_made, + isSuccess: _testResults['bridge_call']?.isSuccess, + isLoading: _testResults['bridge_call']?.isLoading ?? false, + result: _testResults['bridge_call']?.result, + error: _testResults['bridge_call']?.error, + onRun: () => _runTest('bridge_call', () async { + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code(''' + (async () => { + const response = await fjs.bridge_call("Hello from JavaScript!"); + return { + sent: "Hello from JavaScript!", + received: response, + }; + })() + '''), + ); + return result.value; + }), + ), + ApiTestCard( + title: 'Bridge with Complex Data', + subtitle: 'Pass complex objects through bridge', + icon: Icons.data_object, + isSuccess: _testResults['bridge_complex']?.isSuccess, + isLoading: _testResults['bridge_complex']?.isLoading ?? false, + result: _testResults['bridge_complex']?.result, + error: _testResults['bridge_complex']?.error, + onRun: () => _runTest('bridge_complex', () async { + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code(''' + (async () => { + const data = { + type: "request", + payload: { + items: [1, 2, 3], + metadata: { timestamp: Date.now() } + } + }; + const response = await fjs.bridge_call(JSON.stringify(data)); + return { sent: data, response }; + })() + '''), + ); + return result.value; + }), + ), + ], + ); + } +} + +class _TestResult { + final bool isLoading; + final bool? isSuccess; + final dynamic result; + final String? error; + + _TestResult({ + this.isLoading = false, + this.isSuccess, + this.result, + this.error, + }); +} diff --git a/example/lib/screens/error_api_screen.dart b/example/lib/screens/error_api_screen.dart new file mode 100644 index 0000000..c06d023 --- /dev/null +++ b/example/lib/screens/error_api_screen.dart @@ -0,0 +1,603 @@ +import 'package:fjs/fjs.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Screen to test JsError types and error handling +class ErrorApiScreen extends StatefulWidget { + const ErrorApiScreen({super.key}); + + @override + State createState() => _ErrorApiScreenState(); +} + +class _ErrorApiScreenState extends State { + JsAsyncRuntime? _runtime; + JsAsyncContext? _context; + JsEngine? _engine; + // ignore: unused_field - used for internal state tracking + bool _isInitialized = false; + bool _isLoading = false; + + final Map _testResults = {}; + + @override + void initState() { + super.initState(); + _initializeEngine(); + } + + Future _initializeEngine() async { + setState(() => _isLoading = true); + try { + _runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + _context = await JsAsyncContext.from(rt: _runtime!); + _engine = JsEngine(_context!); + await _engine!.init(); + setState(() => _isInitialized = true); + } catch (e) { + if (kDebugMode) print('Failed to initialize engine: $e'); + } finally { + setState(() => _isLoading = false); + } + } + + Future _runTest(String testId, Future Function() test) async { + setState(() { + _testResults[testId] = _TestResult(isLoading: true); + }); + try { + final result = await test(); + setState(() { + _testResults[testId] = _TestResult( + isSuccess: true, + result: result, + ); + }); + } catch (e) { + setState(() { + _testResults[testId] = _TestResult( + isSuccess: false, + error: e.toString(), + ); + }); + } + } + + @override + void dispose() { + _engine?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Error Handling Tests'), + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () async { + await _engine?.dispose(); + setState(() { + _isInitialized = false; + _testResults.clear(); + }); + await _initializeEngine(); + }, + tooltip: 'Reinitialize', + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : SingleChildScrollView( + child: Column( + children: [ + // Error Types + const ApiTestSection( + title: 'JsError Types', + description: 'Create and inspect different error types', + icon: Icons.error_outline, + ), + _buildErrorTypesTests(), + + // Runtime Errors + const ApiTestSection( + title: 'Runtime Errors', + description: 'Test JavaScript runtime errors', + icon: Icons.warning, + ), + _buildRuntimeErrorTests(), + + // Syntax Errors + const ApiTestSection( + title: 'Syntax Errors', + description: 'Test JavaScript syntax errors', + icon: Icons.code_off, + ), + _buildSyntaxErrorTests(), + + // JsResult + const ApiTestSection( + title: 'JsResult Handling', + description: 'Test JsResult ok/err pattern', + icon: Icons.check_box, + ), + _buildResultTests(), + + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildErrorTypesTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsError.promise()', + subtitle: 'Promise-related errors', + icon: Icons.pending, + isSuccess: _testResults['error_promise']?.isSuccess, + isLoading: _testResults['error_promise']?.isLoading ?? false, + result: _testResults['error_promise']?.result, + error: _testResults['error_promise']?.error, + onRun: () => _runTest('error_promise', () async { + const error = JsError.promise('Promise rejected with error'); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.module()', + subtitle: 'Module-related errors', + icon: Icons.view_module, + isSuccess: _testResults['error_module']?.isSuccess, + isLoading: _testResults['error_module']?.isLoading ?? false, + result: _testResults['error_module']?.result, + error: _testResults['error_module']?.error, + onRun: () => _runTest('error_module', () async { + const error = JsError.module( + module: 'my-module', + method: 'doSomething', + message: 'Module not found', + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.context()', + subtitle: 'Context attachment errors', + icon: Icons.layers, + isSuccess: _testResults['error_context']?.isSuccess, + isLoading: _testResults['error_context']?.isLoading ?? false, + result: _testResults['error_context']?.result, + error: _testResults['error_context']?.error, + onRun: () => _runTest('error_context', () async { + const error = JsError.context('Failed to attach global object'); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.io()', + subtitle: 'File I/O errors', + icon: Icons.folder, + isSuccess: _testResults['error_io']?.isSuccess, + isLoading: _testResults['error_io']?.isLoading ?? false, + result: _testResults['error_io']?.result, + error: _testResults['error_io']?.error, + onRun: () => _runTest('error_io', () async { + const error = JsError.io( + path: '/path/to/file.js', + message: 'File not found', + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.conversion()', + subtitle: 'Type conversion errors', + icon: Icons.swap_horiz, + isSuccess: _testResults['error_conversion']?.isSuccess, + isLoading: _testResults['error_conversion']?.isLoading ?? false, + result: _testResults['error_conversion']?.result, + error: _testResults['error_conversion']?.error, + onRun: () => _runTest('error_conversion', () async { + const error = JsError.conversion( + from: 'string', + to: 'number', + message: 'Cannot convert "abc" to number', + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.timeout()', + subtitle: 'Timeout errors', + icon: Icons.timer_off, + isSuccess: _testResults['error_timeout']?.isSuccess, + isLoading: _testResults['error_timeout']?.isLoading ?? false, + result: _testResults['error_timeout']?.result, + error: _testResults['error_timeout']?.error, + onRun: () => _runTest('error_timeout', () async { + final error = JsError.timeout( + operation: 'eval', + timeoutMs: BigInt.from(5000), + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.memoryLimit()', + subtitle: 'Memory limit exceeded errors', + icon: Icons.memory, + isSuccess: _testResults['error_memory']?.isSuccess, + isLoading: _testResults['error_memory']?.isLoading ?? false, + result: _testResults['error_memory']?.result, + error: _testResults['error_memory']?.error, + onRun: () => _runTest('error_memory', () async { + final error = JsError.memoryLimit( + current: BigInt.from(150 * 1024 * 1024), + limit: BigInt.from(100 * 1024 * 1024), + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'JsError.syntax()', + subtitle: 'Syntax errors with location', + icon: Icons.code_off, + isSuccess: _testResults['error_syntax']?.isSuccess, + isLoading: _testResults['error_syntax']?.isLoading ?? false, + result: _testResults['error_syntax']?.result, + error: _testResults['error_syntax']?.error, + onRun: () => _runTest('error_syntax', () async { + const error = JsError.syntax( + line: 10, + column: 5, + message: 'Unexpected token "}"', + ); + return { + 'error': error.toString(), + 'code': error.code(), + 'isRecoverable': error.isRecoverable(), + }; + }), + ), + ApiTestCard( + title: 'Other Error Types', + subtitle: 'Test remaining error types', + icon: Icons.error, + isSuccess: _testResults['error_others']?.isSuccess, + isLoading: _testResults['error_others']?.isLoading ?? false, + result: _testResults['error_others']?.result, + error: _testResults['error_others']?.error, + onRun: () => _runTest('error_others', () async { + final errors = { + 'runtime': const JsError.runtime('Uncaught ReferenceError'), + 'generic': const JsError.generic('Unknown error occurred'), + 'engine': const JsError.engine('Engine not initialized'), + 'bridge': const JsError.bridge('Bridge communication failed'), + 'storage': const JsError.storage('Storage initialization failed'), + 'stackOverflow': + const JsError.stackOverflow('Maximum call stack exceeded'), + 'reference': const JsError.reference('x is not defined'), + 'type': const JsError.type('Cannot read property of undefined'), + 'cancelled': + const JsError.cancelled('Operation cancelled by user'), + }; + + final results = >{}; + for (final entry in errors.entries) { + results[entry.key] = { + 'error': entry.value.toString(), + 'code': entry.value.code(), + 'isRecoverable': entry.value.isRecoverable(), + }; + } + return results; + }), + ), + ], + ); + } + + Widget _buildRuntimeErrorTests() { + return Column( + children: [ + ApiTestCard( + title: 'ReferenceError', + subtitle: 'Access undefined variable', + icon: Icons.help_outline, + isSuccess: _testResults['runtime_reference']?.isSuccess, + isLoading: _testResults['runtime_reference']?.isLoading ?? false, + result: _testResults['runtime_reference']?.result, + error: _testResults['runtime_reference']?.error, + onRun: () => _runTest('runtime_reference', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code('undefinedVariable')); + return {'error': 'Expected error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ApiTestCard( + title: 'TypeError', + subtitle: 'Call non-function', + icon: Icons.do_not_disturb, + isSuccess: _testResults['runtime_type']?.isSuccess, + isLoading: _testResults['runtime_type']?.isLoading ?? false, + result: _testResults['runtime_type']?.result, + error: _testResults['runtime_type']?.error, + onRun: () => _runTest('runtime_type', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code('null.foo()')); + return {'error': 'Expected error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ApiTestCard( + title: 'Promise Rejection', + subtitle: 'Unhandled promise rejection', + icon: Icons.cancel, + isSuccess: _testResults['runtime_promise']?.isSuccess, + isLoading: _testResults['runtime_promise']?.isLoading ?? false, + result: _testResults['runtime_promise']?.result, + error: _testResults['runtime_promise']?.error, + onRun: () => _runTest('runtime_promise', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code(''' + (async () => { + throw new Error("Intentional rejection"); + })() + ''')); + return {'error': 'Expected error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ApiTestCard( + title: 'Custom Error Throw', + subtitle: 'Throw custom error object', + icon: Icons.sports_handball, + isSuccess: _testResults['runtime_custom']?.isSuccess, + isLoading: _testResults['runtime_custom']?.isLoading ?? false, + result: _testResults['runtime_custom']?.result, + error: _testResults['runtime_custom']?.error, + onRun: () => _runTest('runtime_custom', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code(''' + class CustomError extends Error { + constructor(message, code) { + super(message); + this.code = code; + } + } + throw new CustomError("Something went wrong", 500); + ''')); + return {'error': 'Expected error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ], + ); + } + + Widget _buildSyntaxErrorTests() { + return Column( + children: [ + ApiTestCard( + title: 'Missing Bracket', + subtitle: 'Syntax error: missing closing bracket', + icon: Icons.code_off, + isSuccess: _testResults['syntax_bracket']?.isSuccess, + isLoading: _testResults['syntax_bracket']?.isLoading ?? false, + result: _testResults['syntax_bracket']?.result, + error: _testResults['syntax_bracket']?.error, + onRun: () => _runTest('syntax_bracket', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code('function test( { }')); + return {'error': 'Expected syntax error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ApiTestCard( + title: 'Unexpected Token', + subtitle: 'Syntax error: unexpected token', + icon: Icons.error_outline, + isSuccess: _testResults['syntax_token']?.isSuccess, + isLoading: _testResults['syntax_token']?.isLoading ?? false, + result: _testResults['syntax_token']?.result, + error: _testResults['syntax_token']?.error, + onRun: () => _runTest('syntax_token', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code('let x = @@@')); + return {'error': 'Expected syntax error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ApiTestCard( + title: 'Invalid JSON', + subtitle: 'JSON parse error', + icon: Icons.data_object, + isSuccess: _testResults['syntax_json']?.isSuccess, + isLoading: _testResults['syntax_json']?.isLoading ?? false, + result: _testResults['syntax_json']?.result, + error: _testResults['syntax_json']?.error, + onRun: () => _runTest('syntax_json', () async { + if (_engine == null) throw 'Engine not initialized'; + try { + await _engine!.eval(JsCode.code('JSON.parse("{invalid}")')); + return {'error': 'Expected error was not thrown'}; + } catch (e) { + return { + 'caught': true, + 'errorType': e.runtimeType.toString(), + 'message': e.toString(), + }; + } + }), + ), + ], + ); + } + + Widget _buildResultTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsResult.ok()', + subtitle: 'Test successful result', + icon: Icons.check_circle, + isSuccess: _testResults['result_ok']?.isSuccess, + isLoading: _testResults['result_ok']?.isLoading ?? false, + result: _testResults['result_ok']?.result, + error: _testResults['result_ok']?.error, + onRun: () => _runTest('result_ok', () async { + const result = JsResult.ok(JsValue.string('Success!')); + return { + 'isOk': result.isOk, + 'isErr': result.isErr, + 'value': result.ok.value, + }; + }), + ), + ApiTestCard( + title: 'JsResult.err()', + subtitle: 'Test error result', + icon: Icons.error, + isSuccess: _testResults['result_err']?.isSuccess, + isLoading: _testResults['result_err']?.isLoading ?? false, + result: _testResults['result_err']?.result, + error: _testResults['result_err']?.error, + onRun: () => _runTest('result_err', () async { + const result = + JsResult.err(JsError.generic('Something went wrong')); + return { + 'isOk': result.isOk, + 'isErr': result.isErr, + 'error': result.err.toString(), + 'errorCode': result.err.code(), + }; + }), + ), + ApiTestCard( + title: 'Context eval() Result', + subtitle: 'Test actual context evaluation result', + icon: Icons.science, + isSuccess: _testResults['result_context']?.isSuccess, + isLoading: _testResults['result_context']?.isLoading ?? false, + result: _testResults['result_context']?.result, + error: _testResults['result_context']?.error, + onRun: () => _runTest('result_context', () async { + if (_context == null) throw 'Context not initialized'; + + // Test successful eval + final successResult = await _context!.eval(code: '1 + 2 + 3'); + + // Test error eval + final errorResult = await _context!.eval(code: 'undefinedVar'); + + return { + 'success': { + 'isOk': successResult.isOk, + 'value': successResult.isOk ? successResult.ok.value : null, + }, + 'error': { + 'isErr': errorResult.isErr, + 'error': errorResult.isErr ? errorResult.err.toString() : null, + }, + }; + }), + ), + ], + ); + } +} + +class _TestResult { + final bool isLoading; + final bool? isSuccess; + final dynamic result; + final String? error; + + _TestResult({ + this.isLoading = false, + this.isSuccess, + this.result, + this.error, + }); +} diff --git a/example/lib/screens/runtime_api_screen.dart b/example/lib/screens/runtime_api_screen.dart new file mode 100644 index 0000000..0a6a860 --- /dev/null +++ b/example/lib/screens/runtime_api_screen.dart @@ -0,0 +1,446 @@ +import 'package:fjs/fjs.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Screen to test all JsRuntime APIs +class RuntimeApiScreen extends StatefulWidget { + const RuntimeApiScreen({super.key}); + + @override + State createState() => _RuntimeApiScreenState(); +} + +class _RuntimeApiScreenState extends State { + JsAsyncRuntime? _runtime; + JsAsyncContext? _context; + JsEngine? _engine; + bool _isInitialized = false; + bool _isLoading = false; + + // Test results + final Map _testResults = {}; + + @override + void initState() { + super.initState(); + _initializeRuntime(); + } + + Future _initializeRuntime() async { + setState(() => _isLoading = true); + try { + _runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + _context = await JsAsyncContext.from(rt: _runtime!); + _engine = JsEngine(_context!); + await _engine!.init(); + setState(() => _isInitialized = true); + } catch (e) { + if (kDebugMode) print('Failed to initialize runtime: $e'); + } finally { + setState(() => _isLoading = false); + } + } + + Future _runTest(String testId, Future Function() test) async { + setState(() { + _testResults[testId] = _TestResult(isLoading: true); + }); + try { + final result = await test(); + setState(() { + _testResults[testId] = _TestResult( + isSuccess: true, + result: result, + ); + }); + } catch (e) { + setState(() { + _testResults[testId] = _TestResult( + isSuccess: false, + error: e.toString(), + ); + }); + } + } + + @override + void dispose() { + _engine?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Runtime API Tests'), + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () async { + await _engine?.dispose(); + setState(() { + _isInitialized = false; + _testResults.clear(); + }); + await _initializeRuntime(); + }, + tooltip: 'Reinitialize Runtime', + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : SingleChildScrollView( + child: Column( + children: [ + // Status bar + _buildStatusBar(), + + // Runtime Creation Tests + const ApiTestSection( + title: 'Runtime Creation', + description: 'Test runtime initialization methods', + icon: Icons.build_circle, + ), + _buildRuntimeCreationTests(), + + // Memory Management Tests + const ApiTestSection( + title: 'Memory Management', + description: 'Test memory-related APIs', + icon: Icons.memory, + ), + _buildMemoryTests(), + + // Job Management Tests + const ApiTestSection( + title: 'Job Management', + description: 'Test pending job APIs', + icon: Icons.work, + ), + _buildJobTests(), + + // Configuration Tests + const ApiTestSection( + title: 'Runtime Configuration', + description: 'Test runtime configuration methods', + icon: Icons.settings, + ), + _buildConfigTests(), + + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildStatusBar() { + return Container( + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: _isInitialized ? Colors.green.shade50 : Colors.orange.shade50, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: + _isInitialized ? Colors.green.shade200 : Colors.orange.shade200, + ), + ), + child: Row( + children: [ + Icon( + _isInitialized ? Icons.check_circle : Icons.warning, + color: _isInitialized ? Colors.green : Colors.orange, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _isInitialized ? 'Runtime Initialized' : 'Runtime Not Ready', + style: TextStyle( + fontWeight: FontWeight.w600, + color: _isInitialized + ? Colors.green.shade700 + : Colors.orange.shade700, + ), + ), + Text( + _isInitialized + ? 'All APIs are ready for testing' + : 'Waiting for runtime initialization...', + style: TextStyle( + fontSize: 12, + color: _isInitialized + ? Colors.green.shade600 + : Colors.orange.shade600, + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _buildRuntimeCreationTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsAsyncRuntime()', + subtitle: 'Create runtime with default configuration', + icon: Icons.add_circle, + isSuccess: _testResults['runtime_default']?.isSuccess, + isLoading: _testResults['runtime_default']?.isLoading ?? false, + result: _testResults['runtime_default']?.result, + error: _testResults['runtime_default']?.error, + onRun: () => _runTest('runtime_default', () async { + final rt = JsAsyncRuntime(); + return 'JsAsyncRuntime created: ${rt.hashCode}'; + }), + ), + ApiTestCard( + title: 'JsAsyncRuntime.withOptions()', + subtitle: 'Create runtime with custom builtin modules', + icon: Icons.tune, + isSuccess: _testResults['runtime_options']?.isSuccess, + isLoading: _testResults['runtime_options']?.isLoading ?? false, + result: _testResults['runtime_options']?.result, + error: _testResults['runtime_options']?.error, + onRun: () => _runTest('runtime_options', () async { + final rt = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + return 'JsAsyncRuntime.withOptions() created: ${rt.hashCode}'; + }), + ), + ApiTestCard( + title: 'JsBuiltinOptions variants', + subtitle: 'Test all builtin option presets', + icon: Icons.widgets, + isSuccess: _testResults['builtin_variants']?.isSuccess, + isLoading: _testResults['builtin_variants']?.isLoading ?? false, + result: _testResults['builtin_variants']?.result, + error: _testResults['builtin_variants']?.error, + onRun: () => _runTest('builtin_variants', () async { + return { + 'all': JsBuiltinOptions.all().toString(), + 'none': JsBuiltinOptions.none().toString(), + 'essential': JsBuiltinOptions.essential().toString(), + 'web': JsBuiltinOptions.web().toString(), + 'node': JsBuiltinOptions.node().toString(), + }; + }), + ), + ApiTestCard( + title: 'JsAsyncContext.from()', + subtitle: 'Create context from runtime', + icon: Icons.layers, + isSuccess: _testResults['context_create']?.isSuccess, + isLoading: _testResults['context_create']?.isLoading ?? false, + result: _testResults['context_create']?.result, + error: _testResults['context_create']?.error, + onRun: () => _runTest('context_create', () async { + final rt = JsAsyncRuntime(); + final ctx = await JsAsyncContext.from(rt: rt); + return 'JsAsyncContext (${ctx.hashCode}) created from runtime (${rt.hashCode})'; + }), + ), + ], + ); + } + + Widget _buildMemoryTests() { + return Column( + children: [ + ApiTestCard( + title: 'memoryUsage()', + subtitle: 'Get current memory usage statistics', + icon: Icons.analytics, + isSuccess: _testResults['memory_usage']?.isSuccess, + isLoading: _testResults['memory_usage']?.isLoading ?? false, + result: _testResults['memory_usage']?.result, + error: _testResults['memory_usage']?.error, + onRun: () => _runTest('memory_usage', () async { + if (_runtime == null) throw 'Runtime not initialized'; + final usage = await _runtime!.memoryUsage(); + return { + 'summary': usage.summary(), + 'totalMemory': usage.totalMemory.toString(), + 'totalAllocations': usage.totalAllocations.toString(), + 'mallocSize': usage.mallocSize.toString(), + 'mallocCount': usage.mallocCount.toString(), + 'objCount': usage.objCount.toString(), + 'objSize': usage.objSize.toString(), + 'strCount': usage.strCount.toString(), + 'strSize': usage.strSize.toString(), + 'arrayCount': usage.arrayCount.toString(), + 'atomCount': usage.atomCount.toString(), + 'atomSize': usage.atomSize.toString(), + 'jsFuncCount': usage.jsFuncCount.toString(), + 'jsFuncSize': usage.jsFuncSize.toString(), + 'cFuncCount': usage.cFuncCount.toString(), + 'propCount': usage.propCount.toString(), + 'propSize': usage.propSize.toString(), + 'shapeCount': usage.shapeCount.toString(), + 'shapeSize': usage.shapeSize.toString(), + 'fastArrayCount': usage.fastArrayCount.toString(), + 'fastArrayElements': usage.fastArrayElements.toString(), + 'binaryObjectCount': usage.binaryObjectCount.toString(), + 'binaryObjectSize': usage.binaryObjectSize.toString(), + }; + }), + ), + ApiTestCard( + title: 'runGc()', + subtitle: 'Force garbage collection', + icon: Icons.delete_sweep, + isSuccess: _testResults['run_gc']?.isSuccess, + isLoading: _testResults['run_gc']?.isLoading ?? false, + result: _testResults['run_gc']?.result, + error: _testResults['run_gc']?.error, + onRun: () => _runTest('run_gc', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime!.runGc(); + return 'Garbage collection completed'; + }), + ), + ApiTestCard( + title: 'setMemoryLimit()', + subtitle: 'Set memory limit (100MB)', + icon: Icons.speed, + isSuccess: _testResults['set_memory_limit']?.isSuccess, + isLoading: _testResults['set_memory_limit']?.isLoading ?? false, + result: _testResults['set_memory_limit']?.result, + error: _testResults['set_memory_limit']?.error, + onRun: () => _runTest('set_memory_limit', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime! + .setMemoryLimit(limit: BigInt.from(100 * 1024 * 1024)); + return 'Memory limit set to 100MB'; + }), + ), + ApiTestCard( + title: 'setGcThreshold()', + subtitle: 'Set GC threshold (1MB)', + icon: Icons.tune, + isSuccess: _testResults['set_gc_threshold']?.isSuccess, + isLoading: _testResults['set_gc_threshold']?.isLoading ?? false, + result: _testResults['set_gc_threshold']?.result, + error: _testResults['set_gc_threshold']?.error, + onRun: () => _runTest('set_gc_threshold', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime!.setGcThreshold(threshold: BigInt.from(1024 * 1024)); + return 'GC threshold set to 1MB'; + }), + ), + ], + ); + } + + Widget _buildJobTests() { + return Column( + children: [ + ApiTestCard( + title: 'isJobPending()', + subtitle: 'Check if there are pending jobs', + icon: Icons.pending_actions, + isSuccess: _testResults['is_job_pending']?.isSuccess, + isLoading: _testResults['is_job_pending']?.isLoading ?? false, + result: _testResults['is_job_pending']?.result, + error: _testResults['is_job_pending']?.error, + onRun: () => _runTest('is_job_pending', () async { + if (_runtime == null) throw 'Runtime not initialized'; + final isPending = await _runtime!.isJobPending(); + return {'isJobPending': isPending}; + }), + ), + ApiTestCard( + title: 'executePendingJob()', + subtitle: 'Execute a pending job', + icon: Icons.play_circle, + isSuccess: _testResults['execute_pending_job']?.isSuccess, + isLoading: _testResults['execute_pending_job']?.isLoading ?? false, + result: _testResults['execute_pending_job']?.result, + error: _testResults['execute_pending_job']?.error, + onRun: () => _runTest('execute_pending_job', () async { + if (_runtime == null) throw 'Runtime not initialized'; + final executed = await _runtime!.executePendingJob(); + return {'jobExecuted': executed}; + }), + ), + ApiTestCard( + title: 'idle()', + subtitle: 'Put runtime into idle state', + icon: Icons.pause_circle, + isSuccess: _testResults['idle']?.isSuccess, + isLoading: _testResults['idle']?.isLoading ?? false, + result: _testResults['idle']?.result, + error: _testResults['idle']?.error, + onRun: () => _runTest('idle', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime!.idle(); + return 'Runtime set to idle state'; + }), + ), + ], + ); + } + + Widget _buildConfigTests() { + return Column( + children: [ + ApiTestCard( + title: 'setInfo()', + subtitle: 'Set runtime info string', + icon: Icons.info, + isSuccess: _testResults['set_info']?.isSuccess, + isLoading: _testResults['set_info']?.isLoading ?? false, + result: _testResults['set_info']?.result, + error: _testResults['set_info']?.error, + onRun: () => _runTest('set_info', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime!.setInfo(info: 'FJS Example App Runtime'); + return 'Runtime info set successfully'; + }), + ), + ApiTestCard( + title: 'setMaxStackSize()', + subtitle: 'Set maximum stack size (256KB)', + icon: Icons.stacked_bar_chart, + isSuccess: _testResults['set_max_stack_size']?.isSuccess, + isLoading: _testResults['set_max_stack_size']?.isLoading ?? false, + result: _testResults['set_max_stack_size']?.result, + error: _testResults['set_max_stack_size']?.error, + onRun: () => _runTest('set_max_stack_size', () async { + if (_runtime == null) throw 'Runtime not initialized'; + await _runtime!.setMaxStackSize(limit: BigInt.from(256 * 1024)); + return 'Max stack size set to 256KB'; + }), + ), + ], + ); + } +} + +class _TestResult { + final bool isLoading; + final bool? isSuccess; + final dynamic result; + final String? error; + + _TestResult({ + this.isLoading = false, + this.isSuccess, + this.result, + this.error, + }); +} diff --git a/example/lib/screens/source_api_screen.dart b/example/lib/screens/source_api_screen.dart new file mode 100644 index 0000000..b669227 --- /dev/null +++ b/example/lib/screens/source_api_screen.dart @@ -0,0 +1,579 @@ +import 'package:fjs/fjs.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Screen to test JsCode and JsModule source APIs +class SourceApiScreen extends StatefulWidget { + const SourceApiScreen({super.key}); + + @override + State createState() => _SourceApiScreenState(); +} + +class _SourceApiScreenState extends State { + JsAsyncRuntime? _runtime; + JsAsyncContext? _context; + JsEngine? _engine; + // ignore: unused_field - used for internal state tracking + bool _isInitialized = false; + bool _isLoading = false; + + final Map _testResults = {}; + + @override + void initState() { + super.initState(); + _initializeEngine(); + } + + Future _initializeEngine() async { + setState(() => _isLoading = true); + try { + _runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + _context = await JsAsyncContext.from(rt: _runtime!); + _engine = JsEngine(_context!); + await _engine!.init(); + setState(() => _isInitialized = true); + } catch (e) { + if (kDebugMode) print('Failed to initialize engine: $e'); + } finally { + setState(() => _isLoading = false); + } + } + + Future _runTest(String testId, Future Function() test) async { + setState(() { + _testResults[testId] = _TestResult(isLoading: true); + }); + try { + final result = await test(); + setState(() { + _testResults[testId] = _TestResult( + isSuccess: true, + result: result, + ); + }); + } catch (e) { + setState(() { + _testResults[testId] = _TestResult( + isSuccess: false, + error: e.toString(), + ); + }); + } + } + + @override + void dispose() { + _engine?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Source API Tests'), + actions: [ + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () async { + await _engine?.dispose(); + setState(() { + _isInitialized = false; + _testResults.clear(); + }); + await _initializeEngine(); + }, + tooltip: 'Reinitialize', + ), + ], + ), + body: _isLoading + ? const Center(child: CircularProgressIndicator()) + : SingleChildScrollView( + child: Column( + children: [ + // JsCode + const ApiTestSection( + title: 'JsCode', + description: 'Test JavaScript code source types', + icon: Icons.code, + ), + _buildJsCodeTests(), + + // JsModule + const ApiTestSection( + title: 'JsModule', + description: 'Test module creation methods', + icon: Icons.view_module, + ), + _buildJsModuleTests(), + + // JsEvalOptions + const ApiTestSection( + title: 'JsEvalOptions', + description: 'Test evaluation options', + icon: Icons.tune, + ), + _buildEvalOptionsTests(), + + // JsBuiltinOptions + const ApiTestSection( + title: 'JsBuiltinOptions', + description: 'Test builtin module configurations', + icon: Icons.widgets, + ), + _buildBuiltinOptionsTests(), + + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildJsCodeTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsCode.code()', + subtitle: 'Create code from inline string', + icon: Icons.text_snippet, + isSuccess: _testResults['code_inline']?.isSuccess, + isLoading: _testResults['code_inline']?.isLoading ?? false, + result: _testResults['code_inline']?.result, + error: _testResults['code_inline']?.error, + onRun: () => _runTest('code_inline', () async { + const code = JsCode.code('const x = 42; x * 2'); + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval(code); + return { + 'isCode': code.isCode(), + 'isPath': code.isPath(), + 'isBytes': code.isBytes(), + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'JsCode.bytes()', + subtitle: 'Create code from bytes', + icon: Icons.data_array, + isSuccess: _testResults['code_bytes']?.isSuccess, + isLoading: _testResults['code_bytes']?.isLoading ?? false, + result: _testResults['code_bytes']?.result, + error: _testResults['code_bytes']?.error, + onRun: () => _runTest('code_bytes', () async { + final codeString = 'const greeting = "Hello from bytes!"; greeting'; + final bytes = Uint8List.fromList(codeString.codeUnits); + final code = JsCode.bytes(bytes); + + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval(code); + return { + 'isCode': code.isCode(), + 'isPath': code.isPath(), + 'isBytes': code.isBytes(), + 'bytesLength': bytes.length, + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'JsCode type checks', + subtitle: 'Test isCode(), isPath(), isBytes()', + icon: Icons.check_box, + isSuccess: _testResults['code_type_checks']?.isSuccess, + isLoading: _testResults['code_type_checks']?.isLoading ?? false, + result: _testResults['code_type_checks']?.result, + error: _testResults['code_type_checks']?.error, + onRun: () => _runTest('code_type_checks', () async { + const codeVariant = JsCode.code('1 + 1'); + const pathVariant = JsCode.path('/path/to/file.js'); + final bytesVariant = JsCode.bytes(Uint8List.fromList([49, 43, 49])); + + return { + 'codeVariant': { + 'isCode': codeVariant.isCode(), + 'isPath': codeVariant.isPath(), + 'isBytes': codeVariant.isBytes(), + }, + 'pathVariant': { + 'isCode': pathVariant.isCode(), + 'isPath': pathVariant.isPath(), + 'isBytes': pathVariant.isBytes(), + }, + 'bytesVariant': { + 'isCode': bytesVariant.isCode(), + 'isPath': bytesVariant.isPath(), + 'isBytes': bytesVariant.isBytes(), + }, + }; + }), + ), + ], + ); + } + + Widget _buildJsModuleTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsModule()', + subtitle: 'Create module with name and source', + icon: Icons.add_box, + isSuccess: _testResults['module_new']?.isSuccess, + isLoading: _testResults['module_new']?.isLoading ?? false, + result: _testResults['module_new']?.result, + error: _testResults['module_new']?.error, + onRun: () => _runTest('module_new', () async { + final module = JsModule( + name: 'test-module', + source: JsCode.code('export const value = 42;'), + ); + if (_engine == null) throw 'Engine not initialized'; + await _engine!.declareNewModule(module); + final isDeclared = await _engine!.isModuleDeclared('test-module'); + return { + 'moduleName': module.name, + 'isDeclared': isDeclared, + }; + }), + ), + ApiTestCard( + title: 'JsModule.fromCode()', + subtitle: 'Create module from code string', + icon: Icons.text_snippet, + isSuccess: _testResults['module_from_code']?.isSuccess, + isLoading: _testResults['module_from_code']?.isLoading ?? false, + result: _testResults['module_from_code']?.result, + error: _testResults['module_from_code']?.error, + onRun: () => _runTest('module_from_code', () async { + final module = JsModule.fromCode( + module: 'code-module', + code: ''' + export function greet(name) { + return `Hello, \${name}!`; + } + ''', + ); + if (_engine == null) throw 'Engine not initialized'; + await _engine!.declareNewModule(module); + final result = await _engine!.eval(JsCode.code(''' + (async () => { + const { greet } = await import('code-module'); + return greet('FJS'); + })() + ''')); + return { + 'moduleName': module.name, + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'JsModule.fromBytes()', + subtitle: 'Create module from bytes', + icon: Icons.data_array, + isSuccess: _testResults['module_from_bytes']?.isSuccess, + isLoading: _testResults['module_from_bytes']?.isLoading ?? false, + result: _testResults['module_from_bytes']?.result, + error: _testResults['module_from_bytes']?.error, + onRun: () => _runTest('module_from_bytes', () async { + final codeBytes = 'export const PI = 3.14159;'.codeUnits; + final module = JsModule.fromBytes( + module: 'bytes-module', + bytes: codeBytes, + ); + if (_engine == null) throw 'Engine not initialized'; + await _engine!.declareNewModule(module); + final result = await _engine!.eval(JsCode.code(''' + (async () => { + const { PI } = await import('bytes-module'); + return PI; + })() + ''')); + return { + 'moduleName': module.name, + 'bytesLength': codeBytes.length, + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'Module with Dependencies', + subtitle: 'Test modules importing other modules', + icon: Icons.account_tree, + isSuccess: _testResults['module_deps']?.isSuccess, + isLoading: _testResults['module_deps']?.isLoading ?? false, + result: _testResults['module_deps']?.result, + error: _testResults['module_deps']?.error, + onRun: () => _runTest('module_deps', () async { + if (_engine == null) throw 'Engine not initialized'; + + // Clear existing modules + await _engine!.clearNewModules(); + + // Create base module + await _engine!.declareNewModule(JsModule.fromCode( + module: 'math-base', + code: ''' + export const PI = 3.14159; + export function square(x) { return x * x; } + ''', + )); + + // Create dependent module + await _engine!.declareNewModule(JsModule.fromCode( + module: 'math-advanced', + code: ''' + import { PI, square } from 'math-base'; + export function circleArea(r) { return PI * square(r); } + export function circumference(r) { return 2 * PI * r; } + ''', + )); + + // Use the dependent module + final result = await _engine!.eval(JsCode.code(''' + (async () => { + const { circleArea, circumference } = await import('math-advanced'); + return { + area: circleArea(5), + circumference: circumference(5), + }; + })() + ''')); + + return result.value; + }), + ), + ], + ); + } + + Widget _buildEvalOptionsTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsEvalOptions.defaults()', + subtitle: 'Default evaluation options', + icon: Icons.settings, + isSuccess: _testResults['options_defaults']?.isSuccess, + isLoading: _testResults['options_defaults']?.isLoading ?? false, + result: _testResults['options_defaults']?.result, + error: _testResults['options_defaults']?.error, + onRun: () => _runTest('options_defaults', () async { + final options = JsEvalOptions.defaults(); + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code('var defaultTest = 100; defaultTest'), + options: options, + ); + return { + 'options': options.toString(), + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'JsEvalOptions.module()', + subtitle: 'Module evaluation options', + icon: Icons.view_module, + isSuccess: _testResults['options_module']?.isSuccess, + isLoading: _testResults['options_module']?.isLoading ?? false, + result: _testResults['options_module']?.result, + error: _testResults['options_module']?.error, + onRun: () => _runTest('options_module', () async { + final options = JsEvalOptions.module(); + return { + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsEvalOptions.withPromise()', + subtitle: 'Promise-enabled evaluation options', + icon: Icons.pending, + isSuccess: _testResults['options_promise']?.isSuccess, + isLoading: _testResults['options_promise']?.isLoading ?? false, + result: _testResults['options_promise']?.result, + error: _testResults['options_promise']?.error, + onRun: () => _runTest('options_promise', () async { + final options = JsEvalOptions.withPromise(); + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code('Promise.resolve("Async Success")'), + options: options, + ); + return { + 'options': options.toString(), + 'result': result.value, + }; + }), + ), + ApiTestCard( + title: 'JsEvalOptions()', + subtitle: 'Custom evaluation options', + icon: Icons.tune, + isSuccess: _testResults['options_custom']?.isSuccess, + isLoading: _testResults['options_custom']?.isLoading ?? false, + result: _testResults['options_custom']?.result, + error: _testResults['options_custom']?.error, + onRun: () => _runTest('options_custom', () async { + final options = JsEvalOptions( + global: true, + strict: true, + backtraceBarrier: false, + promise: true, + ); + if (_engine == null) throw 'Engine not initialized'; + final result = await _engine!.eval( + JsCode.code('"use strict"; const strictVar = 42; strictVar'), + options: options, + ); + return { + 'global': true, + 'strict': true, + 'backtraceBarrier': false, + 'promise': true, + 'result': result.value, + }; + }), + ), + ], + ); + } + + Widget _buildBuiltinOptionsTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsBuiltinOptions.all()', + subtitle: 'All modules enabled', + icon: Icons.select_all, + isSuccess: _testResults['builtin_all']?.isSuccess, + isLoading: _testResults['builtin_all']?.isLoading ?? false, + result: _testResults['builtin_all']?.result, + error: _testResults['builtin_all']?.error, + onRun: () => _runTest('builtin_all', () async { + final options = JsBuiltinOptions.all(); + return { + 'description': 'All modules enabled', + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsBuiltinOptions.none()', + subtitle: 'No modules enabled', + icon: Icons.block, + isSuccess: _testResults['builtin_none']?.isSuccess, + isLoading: _testResults['builtin_none']?.isLoading ?? false, + result: _testResults['builtin_none']?.result, + error: _testResults['builtin_none']?.error, + onRun: () => _runTest('builtin_none', () async { + final options = JsBuiltinOptions.none(); + return { + 'description': 'No modules enabled', + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsBuiltinOptions.essential()', + subtitle: 'Essential modules: console, timers, buffer, util, json', + icon: Icons.star, + isSuccess: _testResults['builtin_essential']?.isSuccess, + isLoading: _testResults['builtin_essential']?.isLoading ?? false, + result: _testResults['builtin_essential']?.result, + error: _testResults['builtin_essential']?.error, + onRun: () => _runTest('builtin_essential', () async { + final options = JsBuiltinOptions.essential(); + return { + 'description': + 'Essential modules: console, timers, buffer, util, json', + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsBuiltinOptions.web()', + subtitle: 'Web-like modules: console, timers, fetch, url, crypto', + icon: Icons.web, + isSuccess: _testResults['builtin_web']?.isSuccess, + isLoading: _testResults['builtin_web']?.isLoading ?? false, + result: _testResults['builtin_web']?.result, + error: _testResults['builtin_web']?.error, + onRun: () => _runTest('builtin_web', () async { + final options = JsBuiltinOptions.web(); + return { + 'description': + 'Web-like modules: console, timers, fetch, url, crypto', + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsBuiltinOptions.node()', + subtitle: 'Node.js-like modules', + icon: Icons.developer_mode, + isSuccess: _testResults['builtin_node']?.isSuccess, + isLoading: _testResults['builtin_node']?.isLoading ?? false, + result: _testResults['builtin_node']?.result, + error: _testResults['builtin_node']?.error, + onRun: () => _runTest('builtin_node', () async { + final options = JsBuiltinOptions.node(); + return { + 'description': + 'Node.js-like modules (most modules except OS-specific)', + 'options': options.toString(), + }; + }), + ), + ApiTestCard( + title: 'Custom JsBuiltinOptions', + subtitle: 'Selective module configuration', + icon: Icons.tune, + isSuccess: _testResults['builtin_custom']?.isSuccess, + isLoading: _testResults['builtin_custom']?.isLoading ?? false, + result: _testResults['builtin_custom']?.result, + error: _testResults['builtin_custom']?.error, + onRun: () => _runTest('builtin_custom', () async { + // Example of selective module configuration + return { + 'console': true, + 'timers': true, + 'crypto': true, + 'buffer': true, + 'url': true, + 'json': true, + 'fs': false, + 'path': false, + 'os': false, + 'process': false, + }; + }), + ), + ], + ); + } +} + +class _TestResult { + final bool isLoading; + final bool? isSuccess; + final dynamic result; + final String? error; + + _TestResult({ + this.isLoading = false, + this.isSuccess, + this.result, + this.error, + }); +} diff --git a/example/lib/screens/value_api_screen.dart b/example/lib/screens/value_api_screen.dart new file mode 100644 index 0000000..219f339 --- /dev/null +++ b/example/lib/screens/value_api_screen.dart @@ -0,0 +1,565 @@ +import 'dart:typed_data'; + +import 'package:fjs/fjs.dart'; +import 'package:flutter/material.dart'; + +import '../widgets/widgets.dart'; + +/// Screen to test all JsValue types and conversions +class ValueApiScreen extends StatefulWidget { + const ValueApiScreen({super.key}); + + @override + State createState() => _ValueApiScreenState(); +} + +class _ValueApiScreenState extends State { + final Map _testResults = {}; + + Future _runTest(String testId, dynamic Function() test) async { + setState(() { + _testResults[testId] = _TestResult(isLoading: true); + }); + try { + final result = test(); + setState(() { + _testResults[testId] = _TestResult( + isSuccess: true, + result: result, + ); + }); + } catch (e) { + setState(() { + _testResults[testId] = _TestResult( + isSuccess: false, + error: e.toString(), + ); + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('JsValue API Tests'), + actions: [ + IconButton( + icon: const Icon(Icons.clear_all), + onPressed: () => setState(() => _testResults.clear()), + tooltip: 'Clear Results', + ), + ], + ), + body: SingleChildScrollView( + child: Column( + children: [ + // Primitive Types + const ApiTestSection( + title: 'Primitive Types', + description: 'Test basic JavaScript value types', + icon: Icons.code, + ), + _buildPrimitiveTests(), + + // Collection Types + const ApiTestSection( + title: 'Collection Types', + description: 'Test array and object types', + icon: Icons.folder, + ), + _buildCollectionTests(), + + // Special Types + const ApiTestSection( + title: 'Special Types', + description: 'Test Date, Symbol, Function types', + icon: Icons.star, + ), + _buildSpecialTests(), + + // Type Checking + const ApiTestSection( + title: 'Type Checking Methods', + description: 'Test type checking APIs', + icon: Icons.check_circle, + ), + _buildTypeCheckTests(), + + // Value Conversion + const ApiTestSection( + title: 'Value Conversion', + description: 'Test Dart to JsValue conversion', + icon: Icons.swap_horiz, + ), + _buildConversionTests(), + + const SizedBox(height: 32), + ], + ), + ), + ); + } + + Widget _buildPrimitiveTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsValue.none()', + subtitle: 'Represents null/undefined', + icon: Icons.block, + isSuccess: _testResults['none']?.isSuccess, + isLoading: _testResults['none']?.isLoading ?? false, + result: _testResults['none']?.result, + error: _testResults['none']?.error, + onRun: () => _runTest('none', () { + const value = JsValue.none(); + return { + 'value': value.value, + 'isNone': value.isNone(), + 'isPrimitive': value.isPrimitive(), + 'typeName': value.typeName(), + }; + }), + ), + ApiTestCard( + title: 'JsValue.boolean()', + subtitle: 'Boolean value (true/false)', + icon: Icons.toggle_on, + isSuccess: _testResults['boolean']?.isSuccess, + isLoading: _testResults['boolean']?.isLoading ?? false, + result: _testResults['boolean']?.result, + error: _testResults['boolean']?.error, + onRun: () => _runTest('boolean', () { + const valueTrue = JsValue.boolean(true); + const valueFalse = JsValue.boolean(false); + return { + 'true': { + 'value': valueTrue.value, + 'isBoolean': valueTrue.isBoolean(), + 'asBoolean': valueTrue.asBoolean, + 'typeName': valueTrue.typeName(), + }, + 'false': { + 'value': valueFalse.value, + 'isBoolean': valueFalse.isBoolean(), + 'asBoolean': valueFalse.asBoolean, + 'typeName': valueFalse.typeName(), + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.integer()', + subtitle: '64-bit integer value', + icon: Icons.numbers, + isSuccess: _testResults['integer']?.isSuccess, + isLoading: _testResults['integer']?.isLoading ?? false, + result: _testResults['integer']?.result, + error: _testResults['integer']?.error, + onRun: () => _runTest('integer', () { + const value = JsValue.integer(42); + const negative = JsValue.integer(-100); + const large = JsValue.integer(9007199254740991); // Max safe integer + return { + 'positive': { + 'value': value.value, + 'asInteger': value.asInteger, + 'asNum': value.asNum, + 'isNumber': value.isNumber(), + 'typeName': value.typeName(), + }, + 'negative': { + 'value': negative.value, + 'asInteger': negative.asInteger, + }, + 'maxSafeInteger': { + 'value': large.value, + 'asInteger': large.asInteger, + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.float()', + subtitle: 'Floating-point number', + icon: Icons.percent, + isSuccess: _testResults['float']?.isSuccess, + isLoading: _testResults['float']?.isLoading ?? false, + result: _testResults['float']?.result, + error: _testResults['float']?.error, + onRun: () => _runTest('float', () { + const value = JsValue.float(3.14159); + const negative = JsValue.float(-2.5); + const infinity = JsValue.float(double.infinity); + return { + 'pi': { + 'value': value.value, + 'asFloat': value.asFloat, + 'asNum': value.asNum, + 'isNumber': value.isNumber(), + 'typeName': value.typeName(), + }, + 'negative': { + 'value': negative.value, + 'asFloat': negative.asFloat, + }, + 'infinity': { + 'value': infinity.value, + 'asFloat': infinity.asFloat, + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.bigint()', + subtitle: 'BigInt value (stored as string)', + icon: Icons.blur_linear, + isSuccess: _testResults['bigint']?.isSuccess, + isLoading: _testResults['bigint']?.isLoading ?? false, + result: _testResults['bigint']?.result, + error: _testResults['bigint']?.error, + onRun: () => _runTest('bigint', () { + const value = JsValue.bigint('9007199254740992'); // Beyond max safe + final dartBigInt = BigInt.parse('123456789012345678901234567890'); + return { + 'beyondMaxSafe': { + 'value': value.value.toString(), + 'asBigint': value.asBigint, + 'isNumber': value.isNumber(), + 'typeName': value.typeName(), + }, + 'largeBigInt': dartBigInt.toString(), + }; + }), + ), + ApiTestCard( + title: 'JsValue.string()', + subtitle: 'String value', + icon: Icons.text_fields, + isSuccess: _testResults['string']?.isSuccess, + isLoading: _testResults['string']?.isLoading ?? false, + result: _testResults['string']?.result, + error: _testResults['string']?.error, + onRun: () => _runTest('string', () { + const value = JsValue.string('Hello, FJS!'); + const empty = JsValue.string(''); + const unicode = JsValue.string('你好世界 🌍'); + return { + 'normal': { + 'value': value.value, + 'asString': value.asString, + 'isString': value.isString(), + 'typeName': value.typeName(), + }, + 'empty': { + 'value': empty.value, + 'asString': empty.asString, + }, + 'unicode': { + 'value': unicode.value, + 'asString': unicode.asString, + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.bytes()', + subtitle: 'Binary data (Uint8List)', + icon: Icons.data_array, + isSuccess: _testResults['bytes']?.isSuccess, + isLoading: _testResults['bytes']?.isLoading ?? false, + result: _testResults['bytes']?.result, + error: _testResults['bytes']?.error, + onRun: () => _runTest('bytes', () { + final data = Uint8List.fromList([0, 1, 2, 255, 128, 64]); + final value = JsValue.bytes(data); + return { + 'value': value.asBytes?.toList(), + 'isBytes': value.isBytes(), + 'typeName': value.typeName(), + 'length': value.asBytes?.length, + }; + }), + ), + ], + ); + } + + Widget _buildCollectionTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsValue.array()', + subtitle: 'JavaScript array', + icon: Icons.list, + isSuccess: _testResults['array']?.isSuccess, + isLoading: _testResults['array']?.isLoading ?? false, + result: _testResults['array']?.result, + error: _testResults['array']?.error, + onRun: () => _runTest('array', () { + const value = JsValue.array([ + JsValue.integer(1), + JsValue.string('two'), + JsValue.boolean(true), + JsValue.float(4.0), + ]); + const nested = JsValue.array([ + JsValue.array([ + JsValue.integer(1), + JsValue.integer(2), + ]), + JsValue.array([ + JsValue.integer(3), + JsValue.integer(4), + ]), + ]); + return { + 'simple': { + 'value': value.value, + 'isArray': value.isArray(), + 'typeName': value.typeName(), + }, + 'nested': { + 'value': nested.value, + 'isArray': nested.isArray(), + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.object()', + subtitle: 'JavaScript object', + icon: Icons.data_object, + isSuccess: _testResults['object']?.isSuccess, + isLoading: _testResults['object']?.isLoading ?? false, + result: _testResults['object']?.result, + error: _testResults['object']?.error, + onRun: () => _runTest('object', () { + const value = JsValue.object({ + 'name': JsValue.string('John'), + 'age': JsValue.integer(30), + 'active': JsValue.boolean(true), + }); + const nested = JsValue.object({ + 'user': JsValue.object({ + 'name': JsValue.string('Jane'), + 'email': JsValue.string('jane@example.com'), + }), + 'scores': JsValue.array([ + JsValue.integer(85), + JsValue.integer(92), + JsValue.integer(78), + ]), + }); + return { + 'simple': { + 'value': value.value, + 'isObject': value.isObject(), + 'typeName': value.typeName(), + }, + 'nested': { + 'value': nested.value, + 'isObject': nested.isObject(), + }, + }; + }), + ), + ], + ); + } + + Widget _buildSpecialTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsValue.date()', + subtitle: 'JavaScript Date object', + icon: Icons.calendar_today, + isSuccess: _testResults['date']?.isSuccess, + isLoading: _testResults['date']?.isLoading ?? false, + result: _testResults['date']?.result, + error: _testResults['date']?.error, + onRun: () => _runTest('date', () { + final now = DateTime.now(); + final value = JsValue.date(now.millisecondsSinceEpoch); + final epoch = const JsValue.date(0); + return { + 'now': { + 'value': value.value.toString(), + 'isDate': value.isDate(), + 'typeName': value.typeName(), + }, + 'epoch': { + 'value': epoch.value.toString(), + 'isDate': epoch.isDate(), + }, + }; + }), + ), + ApiTestCard( + title: 'JsValue.symbol()', + subtitle: 'JavaScript Symbol', + icon: Icons.tag, + isSuccess: _testResults['symbol']?.isSuccess, + isLoading: _testResults['symbol']?.isLoading ?? false, + result: _testResults['symbol']?.result, + error: _testResults['symbol']?.error, + onRun: () => _runTest('symbol', () { + const value = JsValue.symbol('mySymbol'); + return { + 'value': value.value, + 'typeName': value.typeName(), + }; + }), + ), + ApiTestCard( + title: 'JsValue.function()', + subtitle: 'JavaScript Function reference', + icon: Icons.functions, + isSuccess: _testResults['function']?.isSuccess, + isLoading: _testResults['function']?.isLoading ?? false, + result: _testResults['function']?.result, + error: _testResults['function']?.error, + onRun: () => _runTest('function', () { + const value = JsValue.function('myFunction'); + return { + 'value': value.value, + 'typeName': value.typeName(), + }; + }), + ), + ], + ); + } + + Widget _buildTypeCheckTests() { + return Column( + children: [ + ApiTestCard( + title: 'Type Checking Methods', + subtitle: 'Test all is*() methods', + icon: Icons.check_box, + isSuccess: _testResults['type_checks']?.isSuccess, + isLoading: _testResults['type_checks']?.isLoading ?? false, + result: _testResults['type_checks']?.result, + error: _testResults['type_checks']?.error, + onRun: () => _runTest('type_checks', () { + const values = { + 'none': JsValue.none(), + 'boolean': JsValue.boolean(true), + 'integer': JsValue.integer(42), + 'float': JsValue.float(3.14), + 'bigint': JsValue.bigint('12345'), + 'string': JsValue.string('hello'), + 'array': JsValue.array([JsValue.integer(1)]), + 'object': JsValue.object({'key': JsValue.string('value')}), + }; + + final results = >{}; + for (final entry in values.entries) { + final v = entry.value; + results[entry.key] = { + 'isNone': v.isNone(), + 'isBoolean': v.isBoolean(), + 'isNumber': v.isNumber(), + 'isString': v.isString(), + 'isBytes': v.isBytes(), + 'isArray': v.isArray(), + 'isObject': v.isObject(), + 'isDate': v.isDate(), + 'isPrimitive': v.isPrimitive(), + 'typeName': v.typeName(), + }; + } + return results; + }), + ), + ], + ); + } + + Widget _buildConversionTests() { + return Column( + children: [ + ApiTestCard( + title: 'JsValue.from()', + subtitle: 'Convert Dart values to JsValue', + icon: Icons.transform, + isSuccess: _testResults['from_dart']?.isSuccess, + isLoading: _testResults['from_dart']?.isLoading ?? false, + result: _testResults['from_dart']?.result, + error: _testResults['from_dart']?.error, + onRun: () => _runTest('from_dart', () { + final testCases = { + 'null': null, + 'bool': true, + 'int': 42, + 'double': 3.14, + 'String': 'hello', + 'List': [1, 2, 3], + 'Map': {'a': 1, 'b': 2}, + 'Uint8List': Uint8List.fromList([1, 2, 3]), + 'BigInt': BigInt.parse('12345678901234567890'), + }; + + final results = {}; + for (final entry in testCases.entries) { + final jsValue = JsValue.from(entry.value); + results[entry.key] = { + 'input': entry.value.toString(), + 'jsValue': jsValue.toString(), + 'typeName': jsValue.typeName(), + 'outputValue': jsValue.value?.toString(), + }; + } + return results; + }), + ), + ApiTestCard( + title: 'Safe Casting Methods', + subtitle: 'Test as* getters', + icon: Icons.cast, + isSuccess: _testResults['safe_cast']?.isSuccess, + isLoading: _testResults['safe_cast']?.isLoading ?? false, + result: _testResults['safe_cast']?.result, + error: _testResults['safe_cast']?.error, + onRun: () => _runTest('safe_cast', () { + const intValue = JsValue.integer(42); + const strValue = JsValue.string('hello'); + return { + 'intValue': { + 'asBoolean': intValue.asBoolean, + 'asInteger': intValue.asInteger, + 'asFloat': intValue.asFloat, + 'asString': intValue.asString, + 'asNum': intValue.asNum, + }, + 'strValue': { + 'asBoolean': strValue.asBoolean, + 'asInteger': strValue.asInteger, + 'asFloat': strValue.asFloat, + 'asString': strValue.asString, + 'asNum': strValue.asNum, + }, + }; + }), + ), + ], + ); + } +} + +class _TestResult { + final bool isLoading; + final bool? isSuccess; + final dynamic result; + final String? error; + + _TestResult({ + this.isLoading = false, + this.isSuccess, + this.result, + this.error, + }); +} diff --git a/example/lib/test_js_examples.dart b/example/lib/test_js_examples.dart deleted file mode 100644 index b0a143b..0000000 --- a/example/lib/test_js_examples.dart +++ /dev/null @@ -1,77 +0,0 @@ -import 'package:flutter/services.dart'; -import '../services/js_examples_service.dart'; - -/// Test utility to verify all JS examples can be loaded -class JsExamplesTestRunner { - static Future> testAllExamples() async { - final results = { - 'totalFiles': 0, - 'loadedFiles': 0, - 'failedFiles': 0, - 'errors': {}, - 'categories': >{}, - }; - - try { - // Test all examples - for (final example in JsExamplesService.examples) { - results['totalFiles'] = (results['totalFiles'] as int) + 1; - - try { - final code = await rootBundle.loadString('assets/examples/${example.fileName}'); - if (code.isNotEmpty) { - results['loadedFiles'] = (results['loadedFiles'] as int) + 1; - } else { - results['failedFiles'] = (results['failedFiles'] as int) + 1; - results['errors'][example.fileName] = 'Empty file'; - } - - // Track by category - final category = example.category.displayName; - if (!results['categories'].containsKey(category)) { - results['categories'][category] = { - 'total': 0, - 'loaded': 0, - 'failed': 0, - }; - } - results['categories'][category]['total']++; - results['categories'][category]['loaded']++; - - } catch (e) { - results['failedFiles'] = (results['failedFiles'] as int) + 1; - results['errors'][example.fileName] = e.toString(); - - // Track by category - final category = example.category.displayName; - if (!results['categories'].containsKey(category)) { - results['categories'][category] = { - 'total': 0, - 'loaded': 0, - 'failed': 0, - }; - } - results['categories'][category]['total']++; - results['categories'][category]['failed']++; - } - } - - // Calculate success rate - results['successRate'] = results['totalFiles'] > 0 - ? ((results['loadedFiles'] as int) / (results['totalFiles'] as int) * 100).toStringAsFixed(1) - : '0.0'; - - } catch (e) { - results['testError'] = e.toString(); - } - - return results; - } - - /// Get list of all JS files in assets/examples that are not in the service - static Future> getUntrackedFiles() async { - // This would need to be implemented by scanning the assets directory - // For now, return empty list as we've manually added all files - return []; - } -} diff --git a/example/lib/test_load_verification.dart b/example/lib/test_load_verification.dart deleted file mode 100644 index 6a4e817..0000000 --- a/example/lib/test_load_verification.dart +++ /dev/null @@ -1,43 +0,0 @@ -import 'package:flutter/services.dart'; -import 'package:flutter/foundation.dart'; -import '../services/js_examples_service.dart'; - -/// Quick verification that key JS files can be loaded -Future> verifyKeyFiles() async { - final keyFiles = [ - 'hello_world.js', - 'math_operations.js', - 'test_all_modules.js', - 'script_mode_examples.js', - 'module_mode_examples.js', - 'test_zlib.js', - 'crypto_example.js', - 'events_example.js', - ]; - - final results = {}; - - for (final file in keyFiles) { - try { - final content = await rootBundle.loadString('assets/examples/$file'); - results[file] = content.isNotEmpty; - if (kDebugMode) { - print('✅ $file: ${content.length} characters'); - } - } catch (e) { - results[file] = false; - if (kDebugMode) { - print('❌ $file: $e'); - } - } - } - - return results; -} - -/// Count total JS files in assets -Future countJsFiles() async { - // Since we can't directly list assets, we'll count from our service - final allFiles = JsExamplesService.examples.map((e) => e.fileName).toSet(); - return allFiles.length; -} diff --git a/example/lib/widgets/api_test_card.dart b/example/lib/widgets/api_test_card.dart new file mode 100644 index 0000000..d1d0299 --- /dev/null +++ b/example/lib/widgets/api_test_card.dart @@ -0,0 +1,295 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Reusable card widget for API test results +class ApiTestCard extends StatelessWidget { + final String title; + final String? subtitle; + final IconData icon; + final bool? isSuccess; + final dynamic result; + final String? error; + final bool isLoading; + final VoidCallback? onRun; + final Widget? trailing; + final Widget? expandedContent; + + const ApiTestCard({ + super.key, + required this.title, + this.subtitle, + required this.icon, + this.isSuccess, + this.result, + this.error, + this.isLoading = false, + this.onRun, + this.trailing, + this.expandedContent, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + Color getStatusColor() { + if (isLoading) return colorScheme.primary; + if (isSuccess == null) return colorScheme.outline; + return isSuccess! ? Colors.green : Colors.red; + } + + IconData getStatusIcon() { + if (isLoading) return Icons.hourglass_empty; + if (isSuccess == null) return Icons.help_outline; + return isSuccess! ? Icons.check_circle : Icons.error; + } + + return Card( + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: ExpansionTile( + leading: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: getStatusColor().withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(icon, color: getStatusColor()), + ), + title: Text( + title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + subtitle: subtitle != null + ? Text( + subtitle!, + style: theme.textTheme.bodySmall?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + ) + : null, + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isLoading) + const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + else if (isSuccess != null) + Icon(getStatusIcon(), color: getStatusColor()), + if (trailing != null) ...[ + const SizedBox(width: 8), + trailing!, + ], + if (onRun != null) ...[ + const SizedBox(width: 8), + IconButton( + icon: const Icon(Icons.play_arrow), + onPressed: isLoading ? null : onRun, + tooltip: 'Run Test', + ), + ], + ], + ), + children: [ + if (expandedContent != null) expandedContent!, + if (result != null || error != null) + _ResultSection( + result: result, + error: error, + isSuccess: isSuccess, + ), + ], + ), + ); + } +} + +class _ResultSection extends StatelessWidget { + final dynamic result; + final String? error; + final bool? isSuccess; + + const _ResultSection({ + this.result, + this.error, + this.isSuccess, + }); + + @override + Widget build(BuildContext context) { + // ignore: unused_local_variable - may be used in future + final _ = Theme.of(context); + + String formatResult(dynamic value) { + if (value == null) return 'null'; + if (value is String) return value; + try { + return const JsonEncoder.withIndent(' ').convert(value); + } catch (e) { + return value.toString(); + } + } + + final displayText = error ?? formatResult(result); + final hasError = error != null || isSuccess == false; + + return Container( + width: double.infinity, + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: hasError ? Colors.red.shade50 : Colors.green.shade50, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: hasError ? Colors.red.shade200 : Colors.green.shade200, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + hasError ? 'Error:' : 'Result:', + style: TextStyle( + fontWeight: FontWeight.w600, + color: hasError ? Colors.red.shade700 : Colors.green.shade700, + fontSize: 12, + ), + ), + const Spacer(), + IconButton( + icon: const Icon(Icons.copy, size: 16), + onPressed: () { + Clipboard.setData(ClipboardData(text: displayText)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Copied to clipboard'), + duration: Duration(seconds: 1), + ), + ); + }, + tooltip: 'Copy', + constraints: const BoxConstraints(), + padding: EdgeInsets.zero, + iconSize: 16, + ), + ], + ), + const SizedBox(height: 8), + SelectableText( + displayText, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 12, + color: hasError ? Colors.red.shade800 : Colors.green.shade800, + ), + ), + ], + ), + ); + } +} + +/// A section header for grouping tests +class ApiTestSection extends StatelessWidget { + final String title; + final String? description; + final IconData? icon; + + const ApiTestSection({ + super.key, + required this.title, + this.description, + this.icon, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), + child: Row( + children: [ + if (icon != null) ...[ + Icon(icon, color: theme.colorScheme.primary, size: 20), + const SizedBox(width: 8), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + if (description != null) + Text( + description!, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +/// A simple status indicator widget +class StatusIndicator extends StatelessWidget { + final bool? status; + final String? label; + + const StatusIndicator({ + super.key, + this.status, + this.label, + }); + + @override + Widget build(BuildContext context) { + final color = status == null + ? Colors.grey + : status! + ? Colors.green + : Colors.red; + final icon = status == null + ? Icons.help_outline + : status! + ? Icons.check_circle + : Icons.error; + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, color: color, size: 16), + if (label != null) ...[ + const SizedBox(width: 4), + Text( + label!, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ], + ], + ); + } +} diff --git a/example/lib/widgets/code_editor_widget.dart b/example/lib/widgets/code_editor_widget.dart new file mode 100644 index 0000000..9a53b5b --- /dev/null +++ b/example/lib/widgets/code_editor_widget.dart @@ -0,0 +1,277 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// A code editor widget with syntax highlighting preview +class CodeEditorWidget extends StatefulWidget { + final TextEditingController controller; + final String hintText; + final bool readOnly; + final double? height; + final VoidCallback? onExecute; + final bool isLoading; + + const CodeEditorWidget({ + super.key, + required this.controller, + this.hintText = '// Enter code here...', + this.readOnly = false, + this.height, + this.onExecute, + this.isLoading = false, + }); + + @override + State createState() => _CodeEditorWidgetState(); +} + +class _CodeEditorWidgetState extends State { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + return Container( + height: widget.height, + decoration: BoxDecoration( + color: isDark ? Colors.grey.shade900 : Colors.grey.shade100, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: theme.colorScheme.outline.withValues(alpha: 0.3), + ), + ), + child: Column( + children: [ + // Toolbar + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: const BorderRadius.vertical(top: Radius.circular(11)), + ), + child: Row( + children: [ + Icon( + Icons.code, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Text( + 'JavaScript', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const Spacer(), + // Copy button + IconButton( + icon: const Icon(Icons.copy, size: 18), + onPressed: () { + Clipboard.setData( + ClipboardData(text: widget.controller.text), + ); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Code copied to clipboard'), + duration: Duration(seconds: 1), + ), + ); + }, + tooltip: 'Copy Code', + constraints: const BoxConstraints(), + padding: const EdgeInsets.all(8), + iconSize: 18, + ), + // Clear button + if (!widget.readOnly) + IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () => widget.controller.clear(), + tooltip: 'Clear', + constraints: const BoxConstraints(), + padding: const EdgeInsets.all(8), + iconSize: 18, + ), + // Execute button + if (widget.onExecute != null) + IconButton( + icon: widget.isLoading + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.play_arrow, size: 18), + onPressed: widget.isLoading ? null : widget.onExecute, + tooltip: 'Execute', + constraints: const BoxConstraints(), + padding: const EdgeInsets.all(8), + iconSize: 18, + ), + ], + ), + ), + // Editor + Expanded( + child: TextField( + controller: widget.controller, + maxLines: null, + expands: true, + readOnly: widget.readOnly, + style: TextStyle( + fontFamily: 'monospace', + fontSize: 14, + color: isDark ? Colors.green.shade300 : Colors.grey.shade800, + ), + decoration: InputDecoration( + border: InputBorder.none, + contentPadding: const EdgeInsets.all(16), + hintText: widget.hintText, + hintStyle: TextStyle( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + ), + ), + ), + ), + ], + ), + ); + } +} + +/// A result display widget +class ResultDisplayWidget extends StatelessWidget { + final String? result; + final String? error; + final bool isLoading; + final double? height; + + const ResultDisplayWidget({ + super.key, + this.result, + this.error, + this.isLoading = false, + this.height, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final hasError = error != null; + final hasContent = result != null || error != null; + + return Container( + height: height, + decoration: BoxDecoration( + color: hasError + ? Colors.red.shade50 + : hasContent + ? Colors.green.shade50 + : theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: hasError + ? Colors.red.shade200 + : hasContent + ? Colors.green.shade200 + : theme.colorScheme.outline.withValues(alpha: 0.3), + ), + ), + child: Column( + children: [ + // Header + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: hasError + ? Colors.red.shade100 + : hasContent + ? Colors.green.shade100 + : theme.colorScheme.surfaceContainerHighest, + borderRadius: const BorderRadius.vertical(top: Radius.circular(11)), + ), + child: Row( + children: [ + Icon( + hasError + ? Icons.error_outline + : hasContent + ? Icons.check_circle_outline + : Icons.output, + size: 16, + color: hasError + ? Colors.red.shade700 + : hasContent + ? Colors.green.shade700 + : theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Text( + hasError ? 'Error' : 'Result', + style: theme.textTheme.bodySmall?.copyWith( + color: hasError + ? Colors.red.shade700 + : hasContent + ? Colors.green.shade700 + : theme.colorScheme.onSurfaceVariant, + fontWeight: FontWeight.w500, + ), + ), + const Spacer(), + if (isLoading) + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + if (hasContent) + IconButton( + icon: const Icon(Icons.copy, size: 16), + onPressed: () { + Clipboard.setData( + ClipboardData(text: error ?? result ?? ''), + ); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Result copied to clipboard'), + duration: Duration(seconds: 1), + ), + ); + }, + tooltip: 'Copy Result', + constraints: const BoxConstraints(), + padding: const EdgeInsets.all(8), + iconSize: 16, + ), + ], + ), + ), + // Content + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: hasContent + ? SelectableText( + error ?? result ?? '', + style: TextStyle( + fontFamily: 'monospace', + fontSize: 13, + color: hasError + ? Colors.red.shade800 + : Colors.green.shade800, + ), + ) + : Text( + 'Result will appear here...', + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + fontStyle: FontStyle.italic, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/example/lib/widgets/responsive_layout.dart b/example/lib/widgets/responsive_layout.dart new file mode 100644 index 0000000..ac3c41c --- /dev/null +++ b/example/lib/widgets/responsive_layout.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; + +/// Responsive layout helper widget +class ResponsiveLayout extends StatelessWidget { + final Widget mobile; + final Widget? tablet; + final Widget? desktop; + final double mobileBreakpoint; + final double tabletBreakpoint; + + const ResponsiveLayout({ + super.key, + required this.mobile, + this.tablet, + this.desktop, + this.mobileBreakpoint = 600, + this.tabletBreakpoint = 1200, + }); + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth >= tabletBreakpoint && desktop != null) { + return desktop!; + } else if (constraints.maxWidth >= mobileBreakpoint && tablet != null) { + return tablet!; + } + return mobile; + }, + ); + } + + static bool isMobile(BuildContext context) { + return MediaQuery.of(context).size.width < 600; + } + + static bool isTablet(BuildContext context) { + final width = MediaQuery.of(context).size.width; + return width >= 600 && width < 1200; + } + + static bool isDesktop(BuildContext context) { + return MediaQuery.of(context).size.width >= 1200; + } + + static double horizontalPadding(BuildContext context) { + if (isDesktop(context)) return 32; + if (isTablet(context)) return 24; + return 16; + } + + static double verticalPadding(BuildContext context) { + if (isDesktop(context)) return 24; + if (isTablet(context)) return 20; + return 16; + } + + static int gridCrossAxisCount(BuildContext context) { + if (isDesktop(context)) return 3; + if (isTablet(context)) return 2; + return 1; + } +} + +/// Constrained content wrapper for consistent width across screens +class ConstrainedContent extends StatelessWidget { + final Widget child; + final double maxWidth; + final EdgeInsetsGeometry? padding; + + const ConstrainedContent({ + super.key, + required this.child, + this.maxWidth = 1400, + this.padding, + }); + + @override + Widget build(BuildContext context) { + return Center( + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: padding != null + ? Padding(padding: padding!, child: child) + : child, + ), + ); + } +} diff --git a/example/lib/widgets/widgets.dart b/example/lib/widgets/widgets.dart new file mode 100644 index 0000000..4227446 --- /dev/null +++ b/example/lib/widgets/widgets.dart @@ -0,0 +1,3 @@ +export 'api_test_card.dart'; +export 'code_editor_widget.dart'; +export 'responsive_layout.dart'; diff --git a/example/pubspec.lock b/example/pubspec.lock index fdf76c8..677e0fd 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -322,10 +322,10 @@ packages: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.17.0" mocktail: dependency: transitive description: @@ -551,10 +551,10 @@ packages: dependency: transitive description: name: test_api - sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 url: "https://pub.dev" source: hosted - version: "0.7.6" + version: "0.7.7" tuple: dependency: transitive description: diff --git a/lib/fjs.dart b/lib/fjs.dart index ad140d1..1414f4a 100644 --- a/lib/fjs.dart +++ b/lib/fjs.dart @@ -72,8 +72,17 @@ library; export 'src/engine.dart'; // JavaScript API with high-level abstractions -export 'src/frb/api/js.dart' - hide JsEngineCore, JsAction, JsActionResult, JsCallback, JsCallbackResult; +export 'src/frb/api/engine.dart' + hide JsActionResult, JsCallback, JsCallbackResult; + +// Error handling +export 'src/frb/api/error.dart'; + +// Runtime and context +export 'src/frb/api/runtime.dart'; + +// Source code and modules +export 'src/frb/api/source.dart'; // Value conversion and type handling export 'src/frb/api/value.dart'; diff --git a/lib/src/engine.dart b/lib/src/engine.dart index 5f12908..ab860a2 100644 --- a/lib/src/engine.dart +++ b/lib/src/engine.dart @@ -1,51 +1,52 @@ -/// JavaScript Engine for Flutter -/// -/// This file provides the high-level [JsEngine] class that offers a simplified -/// and user-friendly interface for executing JavaScript code within Flutter applications. -/// The engine manages the underlying JavaScript runtime, context, and provides -/// convenient methods for code evaluation, module management, and bridge communication. -/// -/// ## Key Features -/// -/// - **Simplified API**: High-level interface that abstracts away low-level details -/// - **Async/Await Support**: First-class support for asynchronous JavaScript operations -/// - **Module Management**: Easy dynamic loading and execution of JavaScript modules -/// - **Error Handling**: Comprehensive error propagation and reporting -/// - **Bridge Communication**: Bidirectional communication between Dart and JavaScript -/// - **Resource Management**: Automatic cleanup and disposal of engine resources -/// -/// ## Example Usage -/// -/// ```dart -/// // Create a runtime and context -/// final runtime = await JsAsyncRuntime.withOptions( -/// builtin: JsBuiltinOptions.all(), -/// ); -/// final context = await JsAsyncContext.from(runtime); -/// -/// // Create and initialize the engine -/// final engine = JsEngine(context); -/// await engine.init( -/// bridgeCall: (value) async { -/// print('Bridge call: ${value.value}'); -/// return JsValue.string('Response from Dart'); -/// }, -/// ); -/// -/// // Execute JavaScript code -/// final result = await engine.eval( -/// JsCode.code('2 + 2'), -/// ); -/// print('Result: ${result.value}'); // 4 -/// -/// // Dispose the engine when done -/// await engine.dispose(); -/// ``` +// JavaScript Engine for Flutter +// +// This file provides the high-level [JsEngine] class that offers a simplified +// and user-friendly interface for executing JavaScript code within Flutter applications. +// The engine manages the underlying JavaScript runtime, context, and provides +// convenient methods for code evaluation, module management, and bridge communication. +// +// ## Key Features +// +// - **Simplified API**: High-level interface that abstracts away low-level details +// - **Async/Await Support**: First-class support for asynchronous JavaScript operations +// - **Module Management**: Easy dynamic loading and execution of JavaScript modules +// - **Error Handling**: Comprehensive error propagation and reporting +// - **Bridge Communication**: Bidirectional communication between Dart and JavaScript +// - **Resource Management**: Automatic cleanup and disposal of engine resources +// +// ## Example Usage +// +// ```dart +// // Create a runtime and context +// final runtime = await JsAsyncRuntime.withOptions( +// builtin: JsBuiltinOptions.all(), +// ); +// final context = await JsAsyncContext.from(runtime); +// +// // Create and initialize the engine +// final engine = JsEngine(context); +// await engine.init( +// bridgeCall: (value) async { +// print('Bridge call: ${value.value}'); +// return JsValue.string('Response from Dart'); +// }, +// ); +// +// // Execute JavaScript code +// final result = await engine.eval( +// JsCode.code('2 + 2'), +// ); +// print('Result: ${result.value}'); // 4 +// +// // Dispose the engine when done +// await engine.dispose(); +// ``` import 'dart:async'; import '../fjs.dart'; -import 'frb/api/js.dart'; +import 'frb/api/engine.dart'; +import 'frb/api/value.dart'; /// High-level JavaScript engine for Flutter applications. /// @@ -141,9 +142,9 @@ class JsEngine { /// ```dart /// final engine = JsEngine(context); /// await engine.init(); - /// + /// /// // Use the engine... - /// + /// /// // Clean up when done /// await engine.dispose(); /// ``` @@ -546,12 +547,10 @@ class JsEngine { JsAction.getDeclaredModules(id: nextId), timeout: timeout, ); - + // Convert JsValue to List if (result.value is List) { - return (result.value as List) - .map((item) => item.toString()) - .toList(); + return (result.value as List).map((item) => item.toString()).toList(); } else { throw JsError.engine('Unexpected result type: expected List'); } @@ -590,7 +589,7 @@ class JsEngine { JsAction.isModuleDeclared(id: nextId, moduleName: moduleName), timeout: timeout, ); - + // Convert JsValue to bool if (result.value is bool) { return result.value as bool; diff --git a/lib/src/frb/api/engine.dart b/lib/src/frb/api/engine.dart new file mode 100644 index 0000000..9118f1c --- /dev/null +++ b/lib/src/frb/api/engine.dart @@ -0,0 +1,140 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.11.1. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; +import 'error.dart'; +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; +import 'package:freezed_annotation/freezed_annotation.dart' hide protected; +import 'runtime.dart'; +import 'source.dart'; +import 'value.dart'; +part 'engine.freezed.dart'; + +// These functions are ignored because they are not marked as `pub`: `declare_module`, `handle_action`, `new_bridge_call`, `register_fjs` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `clone`, `clone`, `clone`, `fmt`, `fmt`, `fmt`, `fmt` + +// Rust type: RustOpaqueMoi> +abstract class JsEngineCore implements RustOpaqueInterface { + /// Returns the context. + JsAsyncContext get context; + + /// Disposes the engine. + @override + Future dispose(); + + /// Returns whether the engine is disposed. + bool get disposed; + + /// Executes an action. + Future exec({required JsAction action}); + + /// Creates a new engine core. + factory JsEngineCore({required JsAsyncContext context}) => + LibFjs.instance.api.crateApiEngineJsEngineCoreNew(context: context); + + /// Returns whether the engine is running. + bool get running; + + /// Starts the engine event loop. + Future start( + {required FutureOr Function(JsCallback) bridge}); +} + +@freezed +sealed class JsAction with _$JsAction { + const JsAction._(); + + /// Evaluate JavaScript code. + const factory JsAction.eval({ + required int id, + required JsCode source, + JsEvalOptions? options, + }) = JsAction_Eval; + + /// Declare a new module. + const factory JsAction.declareNewModule({ + required int id, + required JsModule module, + }) = JsAction_DeclareNewModule; + + /// Declare multiple modules. + const factory JsAction.declareNewModules({ + required int id, + required List modules, + }) = JsAction_DeclareNewModules; + + /// Clear all dynamic modules. + const factory JsAction.clearNewModules({ + required int id, + }) = JsAction_ClearNewModules; + + /// Evaluate a module. + const factory JsAction.evaluateModule({ + required int id, + required JsModule module, + }) = JsAction_EvaluateModule; + + /// Get all declared module names. + const factory JsAction.getDeclaredModules({ + required int id, + }) = JsAction_GetDeclaredModules; + + /// Check if a module is declared. + const factory JsAction.isModuleDeclared({ + required int id, + required String moduleName, + }) = JsAction_IsModuleDeclared; + + /// Call a function in a module. + const factory JsAction.callFunction({ + required int id, + required String module, + required String method, + List? params, + }) = JsAction_CallFunction; +} + +/// Result of a JavaScript action execution. +@freezed +sealed class JsActionResult with _$JsActionResult { + const factory JsActionResult({ + required int id, + required JsResult result, + }) = _JsActionResult; +} + +@freezed +sealed class JsCallback with _$JsCallback { + const JsCallback._(); + + /// Engine has been initialized. + const factory JsCallback.initialized() = JsCallback_Initialized; + + /// Action execution result. + const factory JsCallback.handler( + JsActionResult field0, + ) = JsCallback_Handler; + + /// Bridge call from JavaScript. + const factory JsCallback.bridge( + JsValue field0, + ) = JsCallback_Bridge; +} + +@freezed +sealed class JsCallbackResult with _$JsCallbackResult { + const JsCallbackResult._(); + + /// Initialization acknowledged. + const factory JsCallbackResult.initialized() = JsCallbackResult_Initialized; + + /// Handler acknowledged. + const factory JsCallbackResult.handler() = JsCallbackResult_Handler; + + /// Bridge call result. + const factory JsCallbackResult.bridge( + JsResult field0, + ) = JsCallbackResult_Bridge; +} diff --git a/lib/src/frb/api/engine.freezed.dart b/lib/src/frb/api/engine.freezed.dart new file mode 100644 index 0000000..4e2a4a6 --- /dev/null +++ b/lib/src/frb/api/engine.freezed.dart @@ -0,0 +1,2093 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'engine.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$JsAction { + int get id; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsActionCopyWith get copyWith => + _$JsActionCopyWithImpl(this as JsAction, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction && + (identical(other.id, id) || other.id == id)); + } + + @override + int get hashCode => Object.hash(runtimeType, id); + + @override + String toString() { + return 'JsAction(id: $id)'; + } +} + +/// @nodoc +abstract mixin class $JsActionCopyWith<$Res> { + factory $JsActionCopyWith(JsAction value, $Res Function(JsAction) _then) = + _$JsActionCopyWithImpl; + @useResult + $Res call({int id}); +} + +/// @nodoc +class _$JsActionCopyWithImpl<$Res> implements $JsActionCopyWith<$Res> { + _$JsActionCopyWithImpl(this._self, this._then); + + final JsAction _self; + final $Res Function(JsAction) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + }) { + return _then(_self.copyWith( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// Adds pattern-matching-related methods to [JsAction]. +extension JsActionPatterns on JsAction { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsAction_Eval value)? eval, + TResult Function(JsAction_DeclareNewModule value)? declareNewModule, + TResult Function(JsAction_DeclareNewModules value)? declareNewModules, + TResult Function(JsAction_ClearNewModules value)? clearNewModules, + TResult Function(JsAction_EvaluateModule value)? evaluateModule, + TResult Function(JsAction_GetDeclaredModules value)? getDeclaredModules, + TResult Function(JsAction_IsModuleDeclared value)? isModuleDeclared, + TResult Function(JsAction_CallFunction value)? callFunction, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsAction_Eval() when eval != null: + return eval(_that); + case JsAction_DeclareNewModule() when declareNewModule != null: + return declareNewModule(_that); + case JsAction_DeclareNewModules() when declareNewModules != null: + return declareNewModules(_that); + case JsAction_ClearNewModules() when clearNewModules != null: + return clearNewModules(_that); + case JsAction_EvaluateModule() when evaluateModule != null: + return evaluateModule(_that); + case JsAction_GetDeclaredModules() when getDeclaredModules != null: + return getDeclaredModules(_that); + case JsAction_IsModuleDeclared() when isModuleDeclared != null: + return isModuleDeclared(_that); + case JsAction_CallFunction() when callFunction != null: + return callFunction(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsAction_Eval value) eval, + required TResult Function(JsAction_DeclareNewModule value) declareNewModule, + required TResult Function(JsAction_DeclareNewModules value) + declareNewModules, + required TResult Function(JsAction_ClearNewModules value) clearNewModules, + required TResult Function(JsAction_EvaluateModule value) evaluateModule, + required TResult Function(JsAction_GetDeclaredModules value) + getDeclaredModules, + required TResult Function(JsAction_IsModuleDeclared value) isModuleDeclared, + required TResult Function(JsAction_CallFunction value) callFunction, + }) { + final _that = this; + switch (_that) { + case JsAction_Eval(): + return eval(_that); + case JsAction_DeclareNewModule(): + return declareNewModule(_that); + case JsAction_DeclareNewModules(): + return declareNewModules(_that); + case JsAction_ClearNewModules(): + return clearNewModules(_that); + case JsAction_EvaluateModule(): + return evaluateModule(_that); + case JsAction_GetDeclaredModules(): + return getDeclaredModules(_that); + case JsAction_IsModuleDeclared(): + return isModuleDeclared(_that); + case JsAction_CallFunction(): + return callFunction(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsAction_Eval value)? eval, + TResult? Function(JsAction_DeclareNewModule value)? declareNewModule, + TResult? Function(JsAction_DeclareNewModules value)? declareNewModules, + TResult? Function(JsAction_ClearNewModules value)? clearNewModules, + TResult? Function(JsAction_EvaluateModule value)? evaluateModule, + TResult? Function(JsAction_GetDeclaredModules value)? getDeclaredModules, + TResult? Function(JsAction_IsModuleDeclared value)? isModuleDeclared, + TResult? Function(JsAction_CallFunction value)? callFunction, + }) { + final _that = this; + switch (_that) { + case JsAction_Eval() when eval != null: + return eval(_that); + case JsAction_DeclareNewModule() when declareNewModule != null: + return declareNewModule(_that); + case JsAction_DeclareNewModules() when declareNewModules != null: + return declareNewModules(_that); + case JsAction_ClearNewModules() when clearNewModules != null: + return clearNewModules(_that); + case JsAction_EvaluateModule() when evaluateModule != null: + return evaluateModule(_that); + case JsAction_GetDeclaredModules() when getDeclaredModules != null: + return getDeclaredModules(_that); + case JsAction_IsModuleDeclared() when isModuleDeclared != null: + return isModuleDeclared(_that); + case JsAction_CallFunction() when callFunction != null: + return callFunction(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(int id, JsCode source, JsEvalOptions? options)? eval, + TResult Function(int id, JsModule module)? declareNewModule, + TResult Function(int id, List modules)? declareNewModules, + TResult Function(int id)? clearNewModules, + TResult Function(int id, JsModule module)? evaluateModule, + TResult Function(int id)? getDeclaredModules, + TResult Function(int id, String moduleName)? isModuleDeclared, + TResult Function( + int id, String module, String method, List? params)? + callFunction, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsAction_Eval() when eval != null: + return eval(_that.id, _that.source, _that.options); + case JsAction_DeclareNewModule() when declareNewModule != null: + return declareNewModule(_that.id, _that.module); + case JsAction_DeclareNewModules() when declareNewModules != null: + return declareNewModules(_that.id, _that.modules); + case JsAction_ClearNewModules() when clearNewModules != null: + return clearNewModules(_that.id); + case JsAction_EvaluateModule() when evaluateModule != null: + return evaluateModule(_that.id, _that.module); + case JsAction_GetDeclaredModules() when getDeclaredModules != null: + return getDeclaredModules(_that.id); + case JsAction_IsModuleDeclared() when isModuleDeclared != null: + return isModuleDeclared(_that.id, _that.moduleName); + case JsAction_CallFunction() when callFunction != null: + return callFunction(_that.id, _that.module, _that.method, _that.params); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(int id, JsCode source, JsEvalOptions? options) + eval, + required TResult Function(int id, JsModule module) declareNewModule, + required TResult Function(int id, List modules) declareNewModules, + required TResult Function(int id) clearNewModules, + required TResult Function(int id, JsModule module) evaluateModule, + required TResult Function(int id) getDeclaredModules, + required TResult Function(int id, String moduleName) isModuleDeclared, + required TResult Function( + int id, String module, String method, List? params) + callFunction, + }) { + final _that = this; + switch (_that) { + case JsAction_Eval(): + return eval(_that.id, _that.source, _that.options); + case JsAction_DeclareNewModule(): + return declareNewModule(_that.id, _that.module); + case JsAction_DeclareNewModules(): + return declareNewModules(_that.id, _that.modules); + case JsAction_ClearNewModules(): + return clearNewModules(_that.id); + case JsAction_EvaluateModule(): + return evaluateModule(_that.id, _that.module); + case JsAction_GetDeclaredModules(): + return getDeclaredModules(_that.id); + case JsAction_IsModuleDeclared(): + return isModuleDeclared(_that.id, _that.moduleName); + case JsAction_CallFunction(): + return callFunction(_that.id, _that.module, _that.method, _that.params); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(int id, JsCode source, JsEvalOptions? options)? eval, + TResult? Function(int id, JsModule module)? declareNewModule, + TResult? Function(int id, List modules)? declareNewModules, + TResult? Function(int id)? clearNewModules, + TResult? Function(int id, JsModule module)? evaluateModule, + TResult? Function(int id)? getDeclaredModules, + TResult? Function(int id, String moduleName)? isModuleDeclared, + TResult? Function( + int id, String module, String method, List? params)? + callFunction, + }) { + final _that = this; + switch (_that) { + case JsAction_Eval() when eval != null: + return eval(_that.id, _that.source, _that.options); + case JsAction_DeclareNewModule() when declareNewModule != null: + return declareNewModule(_that.id, _that.module); + case JsAction_DeclareNewModules() when declareNewModules != null: + return declareNewModules(_that.id, _that.modules); + case JsAction_ClearNewModules() when clearNewModules != null: + return clearNewModules(_that.id); + case JsAction_EvaluateModule() when evaluateModule != null: + return evaluateModule(_that.id, _that.module); + case JsAction_GetDeclaredModules() when getDeclaredModules != null: + return getDeclaredModules(_that.id); + case JsAction_IsModuleDeclared() when isModuleDeclared != null: + return isModuleDeclared(_that.id, _that.moduleName); + case JsAction_CallFunction() when callFunction != null: + return callFunction(_that.id, _that.module, _that.method, _that.params); + case _: + return null; + } + } +} + +/// @nodoc + +class JsAction_Eval extends JsAction { + const JsAction_Eval({required this.id, required this.source, this.options}) + : super._(); + + @override + final int id; + final JsCode source; + final JsEvalOptions? options; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_EvalCopyWith get copyWith => + _$JsAction_EvalCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_Eval && + (identical(other.id, id) || other.id == id) && + (identical(other.source, source) || other.source == source) && + (identical(other.options, options) || other.options == options)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, source, options); + + @override + String toString() { + return 'JsAction.eval(id: $id, source: $source, options: $options)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_EvalCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_EvalCopyWith( + JsAction_Eval value, $Res Function(JsAction_Eval) _then) = + _$JsAction_EvalCopyWithImpl; + @override + @useResult + $Res call({int id, JsCode source, JsEvalOptions? options}); + + $JsCodeCopyWith<$Res> get source; + $JsEvalOptionsCopyWith<$Res>? get options; +} + +/// @nodoc +class _$JsAction_EvalCopyWithImpl<$Res> + implements $JsAction_EvalCopyWith<$Res> { + _$JsAction_EvalCopyWithImpl(this._self, this._then); + + final JsAction_Eval _self; + final $Res Function(JsAction_Eval) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? source = null, + Object? options = freezed, + }) { + return _then(JsAction_Eval( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + source: null == source + ? _self.source + : source // ignore: cast_nullable_to_non_nullable + as JsCode, + options: freezed == options + ? _self.options + : options // ignore: cast_nullable_to_non_nullable + as JsEvalOptions?, + )); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsCodeCopyWith<$Res> get source { + return $JsCodeCopyWith<$Res>(_self.source, (value) { + return _then(_self.copyWith(source: value)); + }); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsEvalOptionsCopyWith<$Res>? get options { + if (_self.options == null) { + return null; + } + + return $JsEvalOptionsCopyWith<$Res>(_self.options!, (value) { + return _then(_self.copyWith(options: value)); + }); + } +} + +/// @nodoc + +class JsAction_DeclareNewModule extends JsAction { + const JsAction_DeclareNewModule({required this.id, required this.module}) + : super._(); + + @override + final int id; + final JsModule module; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_DeclareNewModuleCopyWith get copyWith => + _$JsAction_DeclareNewModuleCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_DeclareNewModule && + (identical(other.id, id) || other.id == id) && + (identical(other.module, module) || other.module == module)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, module); + + @override + String toString() { + return 'JsAction.declareNewModule(id: $id, module: $module)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_DeclareNewModuleCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_DeclareNewModuleCopyWith(JsAction_DeclareNewModule value, + $Res Function(JsAction_DeclareNewModule) _then) = + _$JsAction_DeclareNewModuleCopyWithImpl; + @override + @useResult + $Res call({int id, JsModule module}); + + $JsModuleCopyWith<$Res> get module; +} + +/// @nodoc +class _$JsAction_DeclareNewModuleCopyWithImpl<$Res> + implements $JsAction_DeclareNewModuleCopyWith<$Res> { + _$JsAction_DeclareNewModuleCopyWithImpl(this._self, this._then); + + final JsAction_DeclareNewModule _self; + final $Res Function(JsAction_DeclareNewModule) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? module = null, + }) { + return _then(JsAction_DeclareNewModule( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + module: null == module + ? _self.module + : module // ignore: cast_nullable_to_non_nullable + as JsModule, + )); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsModuleCopyWith<$Res> get module { + return $JsModuleCopyWith<$Res>(_self.module, (value) { + return _then(_self.copyWith(module: value)); + }); + } +} + +/// @nodoc + +class JsAction_DeclareNewModules extends JsAction { + const JsAction_DeclareNewModules( + {required this.id, required final List modules}) + : _modules = modules, + super._(); + + @override + final int id; + final List _modules; + List get modules { + if (_modules is EqualUnmodifiableListView) return _modules; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_modules); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_DeclareNewModulesCopyWith + get copyWith => + _$JsAction_DeclareNewModulesCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_DeclareNewModules && + (identical(other.id, id) || other.id == id) && + const DeepCollectionEquality().equals(other._modules, _modules)); + } + + @override + int get hashCode => Object.hash( + runtimeType, id, const DeepCollectionEquality().hash(_modules)); + + @override + String toString() { + return 'JsAction.declareNewModules(id: $id, modules: $modules)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_DeclareNewModulesCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_DeclareNewModulesCopyWith(JsAction_DeclareNewModules value, + $Res Function(JsAction_DeclareNewModules) _then) = + _$JsAction_DeclareNewModulesCopyWithImpl; + @override + @useResult + $Res call({int id, List modules}); +} + +/// @nodoc +class _$JsAction_DeclareNewModulesCopyWithImpl<$Res> + implements $JsAction_DeclareNewModulesCopyWith<$Res> { + _$JsAction_DeclareNewModulesCopyWithImpl(this._self, this._then); + + final JsAction_DeclareNewModules _self; + final $Res Function(JsAction_DeclareNewModules) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? modules = null, + }) { + return _then(JsAction_DeclareNewModules( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + modules: null == modules + ? _self._modules + : modules // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class JsAction_ClearNewModules extends JsAction { + const JsAction_ClearNewModules({required this.id}) : super._(); + + @override + final int id; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_ClearNewModulesCopyWith get copyWith => + _$JsAction_ClearNewModulesCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_ClearNewModules && + (identical(other.id, id) || other.id == id)); + } + + @override + int get hashCode => Object.hash(runtimeType, id); + + @override + String toString() { + return 'JsAction.clearNewModules(id: $id)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_ClearNewModulesCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_ClearNewModulesCopyWith(JsAction_ClearNewModules value, + $Res Function(JsAction_ClearNewModules) _then) = + _$JsAction_ClearNewModulesCopyWithImpl; + @override + @useResult + $Res call({int id}); +} + +/// @nodoc +class _$JsAction_ClearNewModulesCopyWithImpl<$Res> + implements $JsAction_ClearNewModulesCopyWith<$Res> { + _$JsAction_ClearNewModulesCopyWithImpl(this._self, this._then); + + final JsAction_ClearNewModules _self; + final $Res Function(JsAction_ClearNewModules) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + }) { + return _then(JsAction_ClearNewModules( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class JsAction_EvaluateModule extends JsAction { + const JsAction_EvaluateModule({required this.id, required this.module}) + : super._(); + + @override + final int id; + final JsModule module; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_EvaluateModuleCopyWith get copyWith => + _$JsAction_EvaluateModuleCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_EvaluateModule && + (identical(other.id, id) || other.id == id) && + (identical(other.module, module) || other.module == module)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, module); + + @override + String toString() { + return 'JsAction.evaluateModule(id: $id, module: $module)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_EvaluateModuleCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_EvaluateModuleCopyWith(JsAction_EvaluateModule value, + $Res Function(JsAction_EvaluateModule) _then) = + _$JsAction_EvaluateModuleCopyWithImpl; + @override + @useResult + $Res call({int id, JsModule module}); + + $JsModuleCopyWith<$Res> get module; +} + +/// @nodoc +class _$JsAction_EvaluateModuleCopyWithImpl<$Res> + implements $JsAction_EvaluateModuleCopyWith<$Res> { + _$JsAction_EvaluateModuleCopyWithImpl(this._self, this._then); + + final JsAction_EvaluateModule _self; + final $Res Function(JsAction_EvaluateModule) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? module = null, + }) { + return _then(JsAction_EvaluateModule( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + module: null == module + ? _self.module + : module // ignore: cast_nullable_to_non_nullable + as JsModule, + )); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsModuleCopyWith<$Res> get module { + return $JsModuleCopyWith<$Res>(_self.module, (value) { + return _then(_self.copyWith(module: value)); + }); + } +} + +/// @nodoc + +class JsAction_GetDeclaredModules extends JsAction { + const JsAction_GetDeclaredModules({required this.id}) : super._(); + + @override + final int id; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_GetDeclaredModulesCopyWith + get copyWith => _$JsAction_GetDeclaredModulesCopyWithImpl< + JsAction_GetDeclaredModules>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_GetDeclaredModules && + (identical(other.id, id) || other.id == id)); + } + + @override + int get hashCode => Object.hash(runtimeType, id); + + @override + String toString() { + return 'JsAction.getDeclaredModules(id: $id)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_GetDeclaredModulesCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_GetDeclaredModulesCopyWith( + JsAction_GetDeclaredModules value, + $Res Function(JsAction_GetDeclaredModules) _then) = + _$JsAction_GetDeclaredModulesCopyWithImpl; + @override + @useResult + $Res call({int id}); +} + +/// @nodoc +class _$JsAction_GetDeclaredModulesCopyWithImpl<$Res> + implements $JsAction_GetDeclaredModulesCopyWith<$Res> { + _$JsAction_GetDeclaredModulesCopyWithImpl(this._self, this._then); + + final JsAction_GetDeclaredModules _self; + final $Res Function(JsAction_GetDeclaredModules) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + }) { + return _then(JsAction_GetDeclaredModules( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class JsAction_IsModuleDeclared extends JsAction { + const JsAction_IsModuleDeclared({required this.id, required this.moduleName}) + : super._(); + + @override + final int id; + final String moduleName; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_IsModuleDeclaredCopyWith get copyWith => + _$JsAction_IsModuleDeclaredCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_IsModuleDeclared && + (identical(other.id, id) || other.id == id) && + (identical(other.moduleName, moduleName) || + other.moduleName == moduleName)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, moduleName); + + @override + String toString() { + return 'JsAction.isModuleDeclared(id: $id, moduleName: $moduleName)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_IsModuleDeclaredCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_IsModuleDeclaredCopyWith(JsAction_IsModuleDeclared value, + $Res Function(JsAction_IsModuleDeclared) _then) = + _$JsAction_IsModuleDeclaredCopyWithImpl; + @override + @useResult + $Res call({int id, String moduleName}); +} + +/// @nodoc +class _$JsAction_IsModuleDeclaredCopyWithImpl<$Res> + implements $JsAction_IsModuleDeclaredCopyWith<$Res> { + _$JsAction_IsModuleDeclaredCopyWithImpl(this._self, this._then); + + final JsAction_IsModuleDeclared _self; + final $Res Function(JsAction_IsModuleDeclared) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? moduleName = null, + }) { + return _then(JsAction_IsModuleDeclared( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + moduleName: null == moduleName + ? _self.moduleName + : moduleName // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsAction_CallFunction extends JsAction { + const JsAction_CallFunction( + {required this.id, + required this.module, + required this.method, + final List? params}) + : _params = params, + super._(); + + @override + final int id; + final String module; + final String method; + final List? _params; + List? get params { + final value = _params; + if (value == null) return null; + if (_params is EqualUnmodifiableListView) return _params; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsAction_CallFunctionCopyWith get copyWith => + _$JsAction_CallFunctionCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsAction_CallFunction && + (identical(other.id, id) || other.id == id) && + (identical(other.module, module) || other.module == module) && + (identical(other.method, method) || other.method == method) && + const DeepCollectionEquality().equals(other._params, _params)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, module, method, + const DeepCollectionEquality().hash(_params)); + + @override + String toString() { + return 'JsAction.callFunction(id: $id, module: $module, method: $method, params: $params)'; + } +} + +/// @nodoc +abstract mixin class $JsAction_CallFunctionCopyWith<$Res> + implements $JsActionCopyWith<$Res> { + factory $JsAction_CallFunctionCopyWith(JsAction_CallFunction value, + $Res Function(JsAction_CallFunction) _then) = + _$JsAction_CallFunctionCopyWithImpl; + @override + @useResult + $Res call({int id, String module, String method, List? params}); +} + +/// @nodoc +class _$JsAction_CallFunctionCopyWithImpl<$Res> + implements $JsAction_CallFunctionCopyWith<$Res> { + _$JsAction_CallFunctionCopyWithImpl(this._self, this._then); + + final JsAction_CallFunction _self; + final $Res Function(JsAction_CallFunction) _then; + + /// Create a copy of JsAction + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? module = null, + Object? method = null, + Object? params = freezed, + }) { + return _then(JsAction_CallFunction( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + module: null == module + ? _self.module + : module // ignore: cast_nullable_to_non_nullable + as String, + method: null == method + ? _self.method + : method // ignore: cast_nullable_to_non_nullable + as String, + params: freezed == params + ? _self._params + : params // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc +mixin _$JsActionResult { + int get id; + JsResult get result; + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsActionResultCopyWith get copyWith => + _$JsActionResultCopyWithImpl( + this as JsActionResult, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsActionResult && + (identical(other.id, id) || other.id == id) && + (identical(other.result, result) || other.result == result)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, result); + + @override + String toString() { + return 'JsActionResult(id: $id, result: $result)'; + } +} + +/// @nodoc +abstract mixin class $JsActionResultCopyWith<$Res> { + factory $JsActionResultCopyWith( + JsActionResult value, $Res Function(JsActionResult) _then) = + _$JsActionResultCopyWithImpl; + @useResult + $Res call({int id, JsResult result}); + + $JsResultCopyWith<$Res> get result; +} + +/// @nodoc +class _$JsActionResultCopyWithImpl<$Res> + implements $JsActionResultCopyWith<$Res> { + _$JsActionResultCopyWithImpl(this._self, this._then); + + final JsActionResult _self; + final $Res Function(JsActionResult) _then; + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? result = null, + }) { + return _then(_self.copyWith( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + result: null == result + ? _self.result + : result // ignore: cast_nullable_to_non_nullable + as JsResult, + )); + } + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsResultCopyWith<$Res> get result { + return $JsResultCopyWith<$Res>(_self.result, (value) { + return _then(_self.copyWith(result: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [JsActionResult]. +extension JsActionResultPatterns on JsActionResult { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_JsActionResult value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsActionResult() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_JsActionResult value) $default, + ) { + final _that = this; + switch (_that) { + case _JsActionResult(): + return $default(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_JsActionResult value)? $default, + ) { + final _that = this; + switch (_that) { + case _JsActionResult() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(int id, JsResult result)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsActionResult() when $default != null: + return $default(_that.id, _that.result); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(int id, JsResult result) $default, + ) { + final _that = this; + switch (_that) { + case _JsActionResult(): + return $default(_that.id, _that.result); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(int id, JsResult result)? $default, + ) { + final _that = this; + switch (_that) { + case _JsActionResult() when $default != null: + return $default(_that.id, _that.result); + case _: + return null; + } + } +} + +/// @nodoc + +class _JsActionResult implements JsActionResult { + const _JsActionResult({required this.id, required this.result}); + + @override + final int id; + @override + final JsResult result; + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$JsActionResultCopyWith<_JsActionResult> get copyWith => + __$JsActionResultCopyWithImpl<_JsActionResult>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _JsActionResult && + (identical(other.id, id) || other.id == id) && + (identical(other.result, result) || other.result == result)); + } + + @override + int get hashCode => Object.hash(runtimeType, id, result); + + @override + String toString() { + return 'JsActionResult(id: $id, result: $result)'; + } +} + +/// @nodoc +abstract mixin class _$JsActionResultCopyWith<$Res> + implements $JsActionResultCopyWith<$Res> { + factory _$JsActionResultCopyWith( + _JsActionResult value, $Res Function(_JsActionResult) _then) = + __$JsActionResultCopyWithImpl; + @override + @useResult + $Res call({int id, JsResult result}); + + @override + $JsResultCopyWith<$Res> get result; +} + +/// @nodoc +class __$JsActionResultCopyWithImpl<$Res> + implements _$JsActionResultCopyWith<$Res> { + __$JsActionResultCopyWithImpl(this._self, this._then); + + final _JsActionResult _self; + final $Res Function(_JsActionResult) _then; + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? result = null, + }) { + return _then(_JsActionResult( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as int, + result: null == result + ? _self.result + : result // ignore: cast_nullable_to_non_nullable + as JsResult, + )); + } + + /// Create a copy of JsActionResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsResultCopyWith<$Res> get result { + return $JsResultCopyWith<$Res>(_self.result, (value) { + return _then(_self.copyWith(result: value)); + }); + } +} + +/// @nodoc +mixin _$JsCallback { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is JsCallback); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'JsCallback()'; + } +} + +/// @nodoc +class $JsCallbackCopyWith<$Res> { + $JsCallbackCopyWith(JsCallback _, $Res Function(JsCallback) __); +} + +/// Adds pattern-matching-related methods to [JsCallback]. +extension JsCallbackPatterns on JsCallback { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsCallback_Initialized value)? initialized, + TResult Function(JsCallback_Handler value)? handler, + TResult Function(JsCallback_Bridge value)? bridge, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized() when initialized != null: + return initialized(_that); + case JsCallback_Handler() when handler != null: + return handler(_that); + case JsCallback_Bridge() when bridge != null: + return bridge(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsCallback_Initialized value) initialized, + required TResult Function(JsCallback_Handler value) handler, + required TResult Function(JsCallback_Bridge value) bridge, + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized(): + return initialized(_that); + case JsCallback_Handler(): + return handler(_that); + case JsCallback_Bridge(): + return bridge(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsCallback_Initialized value)? initialized, + TResult? Function(JsCallback_Handler value)? handler, + TResult? Function(JsCallback_Bridge value)? bridge, + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized() when initialized != null: + return initialized(_that); + case JsCallback_Handler() when handler != null: + return handler(_that); + case JsCallback_Bridge() when bridge != null: + return bridge(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initialized, + TResult Function(JsActionResult field0)? handler, + TResult Function(JsValue field0)? bridge, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized() when initialized != null: + return initialized(); + case JsCallback_Handler() when handler != null: + return handler(_that.field0); + case JsCallback_Bridge() when bridge != null: + return bridge(_that.field0); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function() initialized, + required TResult Function(JsActionResult field0) handler, + required TResult Function(JsValue field0) bridge, + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized(): + return initialized(); + case JsCallback_Handler(): + return handler(_that.field0); + case JsCallback_Bridge(): + return bridge(_that.field0); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initialized, + TResult? Function(JsActionResult field0)? handler, + TResult? Function(JsValue field0)? bridge, + }) { + final _that = this; + switch (_that) { + case JsCallback_Initialized() when initialized != null: + return initialized(); + case JsCallback_Handler() when handler != null: + return handler(_that.field0); + case JsCallback_Bridge() when bridge != null: + return bridge(_that.field0); + case _: + return null; + } + } +} + +/// @nodoc + +class JsCallback_Initialized extends JsCallback { + const JsCallback_Initialized() : super._(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is JsCallback_Initialized); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'JsCallback.initialized()'; + } +} + +/// @nodoc + +class JsCallback_Handler extends JsCallback { + const JsCallback_Handler(this.field0) : super._(); + + final JsActionResult field0; + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCallback_HandlerCopyWith get copyWith => + _$JsCallback_HandlerCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCallback_Handler && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsCallback.handler(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCallback_HandlerCopyWith<$Res> + implements $JsCallbackCopyWith<$Res> { + factory $JsCallback_HandlerCopyWith( + JsCallback_Handler value, $Res Function(JsCallback_Handler) _then) = + _$JsCallback_HandlerCopyWithImpl; + @useResult + $Res call({JsActionResult field0}); + + $JsActionResultCopyWith<$Res> get field0; +} + +/// @nodoc +class _$JsCallback_HandlerCopyWithImpl<$Res> + implements $JsCallback_HandlerCopyWith<$Res> { + _$JsCallback_HandlerCopyWithImpl(this._self, this._then); + + final JsCallback_Handler _self; + final $Res Function(JsCallback_Handler) _then; + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCallback_Handler( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as JsActionResult, + )); + } + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsActionResultCopyWith<$Res> get field0 { + return $JsActionResultCopyWith<$Res>(_self.field0, (value) { + return _then(_self.copyWith(field0: value)); + }); + } +} + +/// @nodoc + +class JsCallback_Bridge extends JsCallback { + const JsCallback_Bridge(this.field0) : super._(); + + final JsValue field0; + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCallback_BridgeCopyWith get copyWith => + _$JsCallback_BridgeCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCallback_Bridge && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsCallback.bridge(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCallback_BridgeCopyWith<$Res> + implements $JsCallbackCopyWith<$Res> { + factory $JsCallback_BridgeCopyWith( + JsCallback_Bridge value, $Res Function(JsCallback_Bridge) _then) = + _$JsCallback_BridgeCopyWithImpl; + @useResult + $Res call({JsValue field0}); + + $JsValueCopyWith<$Res> get field0; +} + +/// @nodoc +class _$JsCallback_BridgeCopyWithImpl<$Res> + implements $JsCallback_BridgeCopyWith<$Res> { + _$JsCallback_BridgeCopyWithImpl(this._self, this._then); + + final JsCallback_Bridge _self; + final $Res Function(JsCallback_Bridge) _then; + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCallback_Bridge( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as JsValue, + )); + } + + /// Create a copy of JsCallback + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsValueCopyWith<$Res> get field0 { + return $JsValueCopyWith<$Res>(_self.field0, (value) { + return _then(_self.copyWith(field0: value)); + }); + } +} + +/// @nodoc +mixin _$JsCallbackResult { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is JsCallbackResult); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'JsCallbackResult()'; + } +} + +/// @nodoc +class $JsCallbackResultCopyWith<$Res> { + $JsCallbackResultCopyWith( + JsCallbackResult _, $Res Function(JsCallbackResult) __); +} + +/// Adds pattern-matching-related methods to [JsCallbackResult]. +extension JsCallbackResultPatterns on JsCallbackResult { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsCallbackResult_Initialized value)? initialized, + TResult Function(JsCallbackResult_Handler value)? handler, + TResult Function(JsCallbackResult_Bridge value)? bridge, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized() when initialized != null: + return initialized(_that); + case JsCallbackResult_Handler() when handler != null: + return handler(_that); + case JsCallbackResult_Bridge() when bridge != null: + return bridge(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsCallbackResult_Initialized value) initialized, + required TResult Function(JsCallbackResult_Handler value) handler, + required TResult Function(JsCallbackResult_Bridge value) bridge, + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized(): + return initialized(_that); + case JsCallbackResult_Handler(): + return handler(_that); + case JsCallbackResult_Bridge(): + return bridge(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsCallbackResult_Initialized value)? initialized, + TResult? Function(JsCallbackResult_Handler value)? handler, + TResult? Function(JsCallbackResult_Bridge value)? bridge, + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized() when initialized != null: + return initialized(_that); + case JsCallbackResult_Handler() when handler != null: + return handler(_that); + case JsCallbackResult_Bridge() when bridge != null: + return bridge(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initialized, + TResult Function()? handler, + TResult Function(JsResult field0)? bridge, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized() when initialized != null: + return initialized(); + case JsCallbackResult_Handler() when handler != null: + return handler(); + case JsCallbackResult_Bridge() when bridge != null: + return bridge(_that.field0); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function() initialized, + required TResult Function() handler, + required TResult Function(JsResult field0) bridge, + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized(): + return initialized(); + case JsCallbackResult_Handler(): + return handler(); + case JsCallbackResult_Bridge(): + return bridge(_that.field0); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initialized, + TResult? Function()? handler, + TResult? Function(JsResult field0)? bridge, + }) { + final _that = this; + switch (_that) { + case JsCallbackResult_Initialized() when initialized != null: + return initialized(); + case JsCallbackResult_Handler() when handler != null: + return handler(); + case JsCallbackResult_Bridge() when bridge != null: + return bridge(_that.field0); + case _: + return null; + } + } +} + +/// @nodoc + +class JsCallbackResult_Initialized extends JsCallbackResult { + const JsCallbackResult_Initialized() : super._(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCallbackResult_Initialized); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'JsCallbackResult.initialized()'; + } +} + +/// @nodoc + +class JsCallbackResult_Handler extends JsCallbackResult { + const JsCallbackResult_Handler() : super._(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is JsCallbackResult_Handler); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'JsCallbackResult.handler()'; + } +} + +/// @nodoc + +class JsCallbackResult_Bridge extends JsCallbackResult { + const JsCallbackResult_Bridge(this.field0) : super._(); + + final JsResult field0; + + /// Create a copy of JsCallbackResult + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCallbackResult_BridgeCopyWith get copyWith => + _$JsCallbackResult_BridgeCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCallbackResult_Bridge && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsCallbackResult.bridge(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCallbackResult_BridgeCopyWith<$Res> + implements $JsCallbackResultCopyWith<$Res> { + factory $JsCallbackResult_BridgeCopyWith(JsCallbackResult_Bridge value, + $Res Function(JsCallbackResult_Bridge) _then) = + _$JsCallbackResult_BridgeCopyWithImpl; + @useResult + $Res call({JsResult field0}); + + $JsResultCopyWith<$Res> get field0; +} + +/// @nodoc +class _$JsCallbackResult_BridgeCopyWithImpl<$Res> + implements $JsCallbackResult_BridgeCopyWith<$Res> { + _$JsCallbackResult_BridgeCopyWithImpl(this._self, this._then); + + final JsCallbackResult_Bridge _self; + final $Res Function(JsCallbackResult_Bridge) _then; + + /// Create a copy of JsCallbackResult + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCallbackResult_Bridge( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as JsResult, + )); + } + + /// Create a copy of JsCallbackResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsResultCopyWith<$Res> get field0 { + return $JsResultCopyWith<$Res>(_self.field0, (value) { + return _then(_self.copyWith(field0: value)); + }); + } +} + +// dart format on diff --git a/lib/src/frb/api/error.dart b/lib/src/frb/api/error.dart new file mode 100644 index 0000000..b4c0123 --- /dev/null +++ b/lib/src/frb/api/error.dart @@ -0,0 +1,172 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.11.1. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; +import 'package:freezed_annotation/freezed_annotation.dart' hide protected; +import 'value.dart'; +part 'error.freezed.dart'; + +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `clone`, `fmt`, `fmt`, `fmt`, `from`, `from`, `from`, `from`, `from` +// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `bridge`, `cancelled`, `context`, `conversion`, `engine`, `err`, `generic`, `io`, `is_err`, `is_ok`, `map_err`, `map`, `memory_limit`, `module`, `ok`, `promise`, `reference`, `runtime`, `storage`, `syntax`, `timeout`, `type_error` + +@freezed +sealed class JsError with _$JsError { + const JsError._(); + + /// Promise-related errors (async operation failures) + const factory JsError.promise( + String field0, + ) = JsError_Promise; + + /// Module-related errors (import/export failures) + const factory JsError.module({ + /// Optional module name where the error occurred + String? module, + + /// Optional method name where the error occurred + String? method, + + /// Error message + required String message, + }) = JsError_Module; + + /// Context attachment errors (global object setup failures) + const factory JsError.context( + String field0, + ) = JsError_Context; + + /// Storage initialization errors (dynamic module storage failures) + const factory JsError.storage( + String field0, + ) = JsError_Storage; + + /// File I/O errors (file reading failures) + const factory JsError.io({ + /// Optional file path where the error occurred + String? path, + + /// Error message + required String message, + }) = JsError_Io; + + /// JavaScript runtime errors from QuickJS engine + const factory JsError.runtime( + String field0, + ) = JsError_Runtime; + + /// Generic catch-all errors + const factory JsError.generic( + String field0, + ) = JsError_Generic; + + /// Engine lifecycle errors + const factory JsError.engine( + String field0, + ) = JsError_Engine; + + /// Bridge communication errors + const factory JsError.bridge( + String field0, + ) = JsError_Bridge; + + /// Type conversion errors + const factory JsError.conversion({ + /// The source type + required String from, + + /// The target type + required String to, + + /// Error message + required String message, + }) = JsError_Conversion; + + /// Timeout errors + const factory JsError.timeout({ + /// Operation that timed out + required String operation, + + /// Timeout duration in milliseconds + required BigInt timeoutMs, + }) = JsError_Timeout; + + /// Memory limit exceeded errors + const factory JsError.memoryLimit({ + /// Current memory usage in bytes + required BigInt current, + + /// Memory limit in bytes + required BigInt limit, + }) = JsError_MemoryLimit; + + /// Stack overflow errors + const factory JsError.stackOverflow( + String field0, + ) = JsError_StackOverflow; + + /// Syntax errors in JavaScript code + const factory JsError.syntax({ + /// Line number where the error occurred + int? line, + + /// Column number where the error occurred + int? column, + + /// Error message + required String message, + }) = JsError_Syntax; + + /// Reference errors (undefined variables, etc.) + const factory JsError.reference( + String field0, + ) = JsError_Reference; + + /// Type errors in JavaScript + const factory JsError.type( + String field0, + ) = JsError_Type; + + /// Cancelled operation errors + const factory JsError.cancelled( + String field0, + ) = JsError_Cancelled; + + /// Returns the error code for this error type. + String code() => LibFjs.instance.api.crateApiErrorJsErrorCode( + that: this, + ); + + /// Returns whether this error is recoverable. + bool isRecoverable() => LibFjs.instance.api.crateApiErrorJsErrorIsRecoverable( + that: this, + ); + + /// Converts the error to a string representation. + @override + String toString() => LibFjs.instance.api.crateApiErrorJsErrorToString( + that: this, + ); +} + +@freezed +sealed class JsResult with _$JsResult { + const JsResult._(); + + /// Successful execution result + const factory JsResult.ok( + JsValue field0, + ) = JsResult_Ok; + + /// Error during execution + const factory JsResult.err( + JsError field0, + ) = JsResult_Err; + + bool get isOk => this is JsResult_Ok; + bool get isErr => this is JsResult_Err; + JsValue get ok => (this as JsResult_Ok).field0; + JsError get err => (this as JsResult_Err).field0; +} diff --git a/lib/src/frb/api/error.freezed.dart b/lib/src/frb/api/error.freezed.dart new file mode 100644 index 0000000..68d5658 --- /dev/null +++ b/lib/src/frb/api/error.freezed.dart @@ -0,0 +1,1922 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'error.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$JsError { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is JsError); + } + + @override + int get hashCode => runtimeType.hashCode; +} + +/// @nodoc +class $JsErrorCopyWith<$Res> { + $JsErrorCopyWith(JsError _, $Res Function(JsError) __); +} + +/// Adds pattern-matching-related methods to [JsError]. +extension JsErrorPatterns on JsError { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsError_Promise value)? promise, + TResult Function(JsError_Module value)? module, + TResult Function(JsError_Context value)? context, + TResult Function(JsError_Storage value)? storage, + TResult Function(JsError_Io value)? io, + TResult Function(JsError_Runtime value)? runtime, + TResult Function(JsError_Generic value)? generic, + TResult Function(JsError_Engine value)? engine, + TResult Function(JsError_Bridge value)? bridge, + TResult Function(JsError_Conversion value)? conversion, + TResult Function(JsError_Timeout value)? timeout, + TResult Function(JsError_MemoryLimit value)? memoryLimit, + TResult Function(JsError_StackOverflow value)? stackOverflow, + TResult Function(JsError_Syntax value)? syntax, + TResult Function(JsError_Reference value)? reference, + TResult Function(JsError_Type value)? type, + TResult Function(JsError_Cancelled value)? cancelled, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsError_Promise() when promise != null: + return promise(_that); + case JsError_Module() when module != null: + return module(_that); + case JsError_Context() when context != null: + return context(_that); + case JsError_Storage() when storage != null: + return storage(_that); + case JsError_Io() when io != null: + return io(_that); + case JsError_Runtime() when runtime != null: + return runtime(_that); + case JsError_Generic() when generic != null: + return generic(_that); + case JsError_Engine() when engine != null: + return engine(_that); + case JsError_Bridge() when bridge != null: + return bridge(_that); + case JsError_Conversion() when conversion != null: + return conversion(_that); + case JsError_Timeout() when timeout != null: + return timeout(_that); + case JsError_MemoryLimit() when memoryLimit != null: + return memoryLimit(_that); + case JsError_StackOverflow() when stackOverflow != null: + return stackOverflow(_that); + case JsError_Syntax() when syntax != null: + return syntax(_that); + case JsError_Reference() when reference != null: + return reference(_that); + case JsError_Type() when type != null: + return type(_that); + case JsError_Cancelled() when cancelled != null: + return cancelled(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsError_Promise value) promise, + required TResult Function(JsError_Module value) module, + required TResult Function(JsError_Context value) context, + required TResult Function(JsError_Storage value) storage, + required TResult Function(JsError_Io value) io, + required TResult Function(JsError_Runtime value) runtime, + required TResult Function(JsError_Generic value) generic, + required TResult Function(JsError_Engine value) engine, + required TResult Function(JsError_Bridge value) bridge, + required TResult Function(JsError_Conversion value) conversion, + required TResult Function(JsError_Timeout value) timeout, + required TResult Function(JsError_MemoryLimit value) memoryLimit, + required TResult Function(JsError_StackOverflow value) stackOverflow, + required TResult Function(JsError_Syntax value) syntax, + required TResult Function(JsError_Reference value) reference, + required TResult Function(JsError_Type value) type, + required TResult Function(JsError_Cancelled value) cancelled, + }) { + final _that = this; + switch (_that) { + case JsError_Promise(): + return promise(_that); + case JsError_Module(): + return module(_that); + case JsError_Context(): + return context(_that); + case JsError_Storage(): + return storage(_that); + case JsError_Io(): + return io(_that); + case JsError_Runtime(): + return runtime(_that); + case JsError_Generic(): + return generic(_that); + case JsError_Engine(): + return engine(_that); + case JsError_Bridge(): + return bridge(_that); + case JsError_Conversion(): + return conversion(_that); + case JsError_Timeout(): + return timeout(_that); + case JsError_MemoryLimit(): + return memoryLimit(_that); + case JsError_StackOverflow(): + return stackOverflow(_that); + case JsError_Syntax(): + return syntax(_that); + case JsError_Reference(): + return reference(_that); + case JsError_Type(): + return type(_that); + case JsError_Cancelled(): + return cancelled(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsError_Promise value)? promise, + TResult? Function(JsError_Module value)? module, + TResult? Function(JsError_Context value)? context, + TResult? Function(JsError_Storage value)? storage, + TResult? Function(JsError_Io value)? io, + TResult? Function(JsError_Runtime value)? runtime, + TResult? Function(JsError_Generic value)? generic, + TResult? Function(JsError_Engine value)? engine, + TResult? Function(JsError_Bridge value)? bridge, + TResult? Function(JsError_Conversion value)? conversion, + TResult? Function(JsError_Timeout value)? timeout, + TResult? Function(JsError_MemoryLimit value)? memoryLimit, + TResult? Function(JsError_StackOverflow value)? stackOverflow, + TResult? Function(JsError_Syntax value)? syntax, + TResult? Function(JsError_Reference value)? reference, + TResult? Function(JsError_Type value)? type, + TResult? Function(JsError_Cancelled value)? cancelled, + }) { + final _that = this; + switch (_that) { + case JsError_Promise() when promise != null: + return promise(_that); + case JsError_Module() when module != null: + return module(_that); + case JsError_Context() when context != null: + return context(_that); + case JsError_Storage() when storage != null: + return storage(_that); + case JsError_Io() when io != null: + return io(_that); + case JsError_Runtime() when runtime != null: + return runtime(_that); + case JsError_Generic() when generic != null: + return generic(_that); + case JsError_Engine() when engine != null: + return engine(_that); + case JsError_Bridge() when bridge != null: + return bridge(_that); + case JsError_Conversion() when conversion != null: + return conversion(_that); + case JsError_Timeout() when timeout != null: + return timeout(_that); + case JsError_MemoryLimit() when memoryLimit != null: + return memoryLimit(_that); + case JsError_StackOverflow() when stackOverflow != null: + return stackOverflow(_that); + case JsError_Syntax() when syntax != null: + return syntax(_that); + case JsError_Reference() when reference != null: + return reference(_that); + case JsError_Type() when type != null: + return type(_that); + case JsError_Cancelled() when cancelled != null: + return cancelled(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String field0)? promise, + TResult Function(String? module, String? method, String message)? module, + TResult Function(String field0)? context, + TResult Function(String field0)? storage, + TResult Function(String? path, String message)? io, + TResult Function(String field0)? runtime, + TResult Function(String field0)? generic, + TResult Function(String field0)? engine, + TResult Function(String field0)? bridge, + TResult Function(String from, String to, String message)? conversion, + TResult Function(String operation, BigInt timeoutMs)? timeout, + TResult Function(BigInt current, BigInt limit)? memoryLimit, + TResult Function(String field0)? stackOverflow, + TResult Function(int? line, int? column, String message)? syntax, + TResult Function(String field0)? reference, + TResult Function(String field0)? type, + TResult Function(String field0)? cancelled, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsError_Promise() when promise != null: + return promise(_that.field0); + case JsError_Module() when module != null: + return module(_that.module, _that.method, _that.message); + case JsError_Context() when context != null: + return context(_that.field0); + case JsError_Storage() when storage != null: + return storage(_that.field0); + case JsError_Io() when io != null: + return io(_that.path, _that.message); + case JsError_Runtime() when runtime != null: + return runtime(_that.field0); + case JsError_Generic() when generic != null: + return generic(_that.field0); + case JsError_Engine() when engine != null: + return engine(_that.field0); + case JsError_Bridge() when bridge != null: + return bridge(_that.field0); + case JsError_Conversion() when conversion != null: + return conversion(_that.from, _that.to, _that.message); + case JsError_Timeout() when timeout != null: + return timeout(_that.operation, _that.timeoutMs); + case JsError_MemoryLimit() when memoryLimit != null: + return memoryLimit(_that.current, _that.limit); + case JsError_StackOverflow() when stackOverflow != null: + return stackOverflow(_that.field0); + case JsError_Syntax() when syntax != null: + return syntax(_that.line, _that.column, _that.message); + case JsError_Reference() when reference != null: + return reference(_that.field0); + case JsError_Type() when type != null: + return type(_that.field0); + case JsError_Cancelled() when cancelled != null: + return cancelled(_that.field0); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(String field0) promise, + required TResult Function(String? module, String? method, String message) + module, + required TResult Function(String field0) context, + required TResult Function(String field0) storage, + required TResult Function(String? path, String message) io, + required TResult Function(String field0) runtime, + required TResult Function(String field0) generic, + required TResult Function(String field0) engine, + required TResult Function(String field0) bridge, + required TResult Function(String from, String to, String message) + conversion, + required TResult Function(String operation, BigInt timeoutMs) timeout, + required TResult Function(BigInt current, BigInt limit) memoryLimit, + required TResult Function(String field0) stackOverflow, + required TResult Function(int? line, int? column, String message) syntax, + required TResult Function(String field0) reference, + required TResult Function(String field0) type, + required TResult Function(String field0) cancelled, + }) { + final _that = this; + switch (_that) { + case JsError_Promise(): + return promise(_that.field0); + case JsError_Module(): + return module(_that.module, _that.method, _that.message); + case JsError_Context(): + return context(_that.field0); + case JsError_Storage(): + return storage(_that.field0); + case JsError_Io(): + return io(_that.path, _that.message); + case JsError_Runtime(): + return runtime(_that.field0); + case JsError_Generic(): + return generic(_that.field0); + case JsError_Engine(): + return engine(_that.field0); + case JsError_Bridge(): + return bridge(_that.field0); + case JsError_Conversion(): + return conversion(_that.from, _that.to, _that.message); + case JsError_Timeout(): + return timeout(_that.operation, _that.timeoutMs); + case JsError_MemoryLimit(): + return memoryLimit(_that.current, _that.limit); + case JsError_StackOverflow(): + return stackOverflow(_that.field0); + case JsError_Syntax(): + return syntax(_that.line, _that.column, _that.message); + case JsError_Reference(): + return reference(_that.field0); + case JsError_Type(): + return type(_that.field0); + case JsError_Cancelled(): + return cancelled(_that.field0); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String field0)? promise, + TResult? Function(String? module, String? method, String message)? module, + TResult? Function(String field0)? context, + TResult? Function(String field0)? storage, + TResult? Function(String? path, String message)? io, + TResult? Function(String field0)? runtime, + TResult? Function(String field0)? generic, + TResult? Function(String field0)? engine, + TResult? Function(String field0)? bridge, + TResult? Function(String from, String to, String message)? conversion, + TResult? Function(String operation, BigInt timeoutMs)? timeout, + TResult? Function(BigInt current, BigInt limit)? memoryLimit, + TResult? Function(String field0)? stackOverflow, + TResult? Function(int? line, int? column, String message)? syntax, + TResult? Function(String field0)? reference, + TResult? Function(String field0)? type, + TResult? Function(String field0)? cancelled, + }) { + final _that = this; + switch (_that) { + case JsError_Promise() when promise != null: + return promise(_that.field0); + case JsError_Module() when module != null: + return module(_that.module, _that.method, _that.message); + case JsError_Context() when context != null: + return context(_that.field0); + case JsError_Storage() when storage != null: + return storage(_that.field0); + case JsError_Io() when io != null: + return io(_that.path, _that.message); + case JsError_Runtime() when runtime != null: + return runtime(_that.field0); + case JsError_Generic() when generic != null: + return generic(_that.field0); + case JsError_Engine() when engine != null: + return engine(_that.field0); + case JsError_Bridge() when bridge != null: + return bridge(_that.field0); + case JsError_Conversion() when conversion != null: + return conversion(_that.from, _that.to, _that.message); + case JsError_Timeout() when timeout != null: + return timeout(_that.operation, _that.timeoutMs); + case JsError_MemoryLimit() when memoryLimit != null: + return memoryLimit(_that.current, _that.limit); + case JsError_StackOverflow() when stackOverflow != null: + return stackOverflow(_that.field0); + case JsError_Syntax() when syntax != null: + return syntax(_that.line, _that.column, _that.message); + case JsError_Reference() when reference != null: + return reference(_that.field0); + case JsError_Type() when type != null: + return type(_that.field0); + case JsError_Cancelled() when cancelled != null: + return cancelled(_that.field0); + case _: + return null; + } + } +} + +/// @nodoc + +class JsError_Promise extends JsError { + const JsError_Promise(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_PromiseCopyWith get copyWith => + _$JsError_PromiseCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Promise && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_PromiseCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_PromiseCopyWith( + JsError_Promise value, $Res Function(JsError_Promise) _then) = + _$JsError_PromiseCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_PromiseCopyWithImpl<$Res> + implements $JsError_PromiseCopyWith<$Res> { + _$JsError_PromiseCopyWithImpl(this._self, this._then); + + final JsError_Promise _self; + final $Res Function(JsError_Promise) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Promise( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Module extends JsError { + const JsError_Module({this.module, this.method, required this.message}) + : super._(); + + /// Optional module name where the error occurred + final String? module; + + /// Optional method name where the error occurred + final String? method; + + /// Error message + final String message; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_ModuleCopyWith get copyWith => + _$JsError_ModuleCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Module && + (identical(other.module, module) || other.module == module) && + (identical(other.method, method) || other.method == method) && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, module, method, message); +} + +/// @nodoc +abstract mixin class $JsError_ModuleCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_ModuleCopyWith( + JsError_Module value, $Res Function(JsError_Module) _then) = + _$JsError_ModuleCopyWithImpl; + @useResult + $Res call({String? module, String? method, String message}); +} + +/// @nodoc +class _$JsError_ModuleCopyWithImpl<$Res> + implements $JsError_ModuleCopyWith<$Res> { + _$JsError_ModuleCopyWithImpl(this._self, this._then); + + final JsError_Module _self; + final $Res Function(JsError_Module) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? module = freezed, + Object? method = freezed, + Object? message = null, + }) { + return _then(JsError_Module( + module: freezed == module + ? _self.module + : module // ignore: cast_nullable_to_non_nullable + as String?, + method: freezed == method + ? _self.method + : method // ignore: cast_nullable_to_non_nullable + as String?, + message: null == message + ? _self.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Context extends JsError { + const JsError_Context(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_ContextCopyWith get copyWith => + _$JsError_ContextCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Context && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_ContextCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_ContextCopyWith( + JsError_Context value, $Res Function(JsError_Context) _then) = + _$JsError_ContextCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_ContextCopyWithImpl<$Res> + implements $JsError_ContextCopyWith<$Res> { + _$JsError_ContextCopyWithImpl(this._self, this._then); + + final JsError_Context _self; + final $Res Function(JsError_Context) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Context( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Storage extends JsError { + const JsError_Storage(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_StorageCopyWith get copyWith => + _$JsError_StorageCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Storage && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_StorageCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_StorageCopyWith( + JsError_Storage value, $Res Function(JsError_Storage) _then) = + _$JsError_StorageCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_StorageCopyWithImpl<$Res> + implements $JsError_StorageCopyWith<$Res> { + _$JsError_StorageCopyWithImpl(this._self, this._then); + + final JsError_Storage _self; + final $Res Function(JsError_Storage) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Storage( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Io extends JsError { + const JsError_Io({this.path, required this.message}) : super._(); + + /// Optional file path where the error occurred + final String? path; + + /// Error message + final String message; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_IoCopyWith get copyWith => + _$JsError_IoCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Io && + (identical(other.path, path) || other.path == path) && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, path, message); +} + +/// @nodoc +abstract mixin class $JsError_IoCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_IoCopyWith( + JsError_Io value, $Res Function(JsError_Io) _then) = + _$JsError_IoCopyWithImpl; + @useResult + $Res call({String? path, String message}); +} + +/// @nodoc +class _$JsError_IoCopyWithImpl<$Res> implements $JsError_IoCopyWith<$Res> { + _$JsError_IoCopyWithImpl(this._self, this._then); + + final JsError_Io _self; + final $Res Function(JsError_Io) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? path = freezed, + Object? message = null, + }) { + return _then(JsError_Io( + path: freezed == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String?, + message: null == message + ? _self.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Runtime extends JsError { + const JsError_Runtime(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_RuntimeCopyWith get copyWith => + _$JsError_RuntimeCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Runtime && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_RuntimeCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_RuntimeCopyWith( + JsError_Runtime value, $Res Function(JsError_Runtime) _then) = + _$JsError_RuntimeCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_RuntimeCopyWithImpl<$Res> + implements $JsError_RuntimeCopyWith<$Res> { + _$JsError_RuntimeCopyWithImpl(this._self, this._then); + + final JsError_Runtime _self; + final $Res Function(JsError_Runtime) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Runtime( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Generic extends JsError { + const JsError_Generic(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_GenericCopyWith get copyWith => + _$JsError_GenericCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Generic && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_GenericCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_GenericCopyWith( + JsError_Generic value, $Res Function(JsError_Generic) _then) = + _$JsError_GenericCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_GenericCopyWithImpl<$Res> + implements $JsError_GenericCopyWith<$Res> { + _$JsError_GenericCopyWithImpl(this._self, this._then); + + final JsError_Generic _self; + final $Res Function(JsError_Generic) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Generic( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Engine extends JsError { + const JsError_Engine(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_EngineCopyWith get copyWith => + _$JsError_EngineCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Engine && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_EngineCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_EngineCopyWith( + JsError_Engine value, $Res Function(JsError_Engine) _then) = + _$JsError_EngineCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_EngineCopyWithImpl<$Res> + implements $JsError_EngineCopyWith<$Res> { + _$JsError_EngineCopyWithImpl(this._self, this._then); + + final JsError_Engine _self; + final $Res Function(JsError_Engine) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Engine( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Bridge extends JsError { + const JsError_Bridge(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_BridgeCopyWith get copyWith => + _$JsError_BridgeCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Bridge && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_BridgeCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_BridgeCopyWith( + JsError_Bridge value, $Res Function(JsError_Bridge) _then) = + _$JsError_BridgeCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_BridgeCopyWithImpl<$Res> + implements $JsError_BridgeCopyWith<$Res> { + _$JsError_BridgeCopyWithImpl(this._self, this._then); + + final JsError_Bridge _self; + final $Res Function(JsError_Bridge) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Bridge( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Conversion extends JsError { + const JsError_Conversion( + {required this.from, required this.to, required this.message}) + : super._(); + + /// The source type + final String from; + + /// The target type + final String to; + + /// Error message + final String message; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_ConversionCopyWith get copyWith => + _$JsError_ConversionCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Conversion && + (identical(other.from, from) || other.from == from) && + (identical(other.to, to) || other.to == to) && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, from, to, message); +} + +/// @nodoc +abstract mixin class $JsError_ConversionCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_ConversionCopyWith( + JsError_Conversion value, $Res Function(JsError_Conversion) _then) = + _$JsError_ConversionCopyWithImpl; + @useResult + $Res call({String from, String to, String message}); +} + +/// @nodoc +class _$JsError_ConversionCopyWithImpl<$Res> + implements $JsError_ConversionCopyWith<$Res> { + _$JsError_ConversionCopyWithImpl(this._self, this._then); + + final JsError_Conversion _self; + final $Res Function(JsError_Conversion) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? from = null, + Object? to = null, + Object? message = null, + }) { + return _then(JsError_Conversion( + from: null == from + ? _self.from + : from // ignore: cast_nullable_to_non_nullable + as String, + to: null == to + ? _self.to + : to // ignore: cast_nullable_to_non_nullable + as String, + message: null == message + ? _self.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Timeout extends JsError { + const JsError_Timeout({required this.operation, required this.timeoutMs}) + : super._(); + + /// Operation that timed out + final String operation; + + /// Timeout duration in milliseconds + final BigInt timeoutMs; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_TimeoutCopyWith get copyWith => + _$JsError_TimeoutCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Timeout && + (identical(other.operation, operation) || + other.operation == operation) && + (identical(other.timeoutMs, timeoutMs) || + other.timeoutMs == timeoutMs)); + } + + @override + int get hashCode => Object.hash(runtimeType, operation, timeoutMs); +} + +/// @nodoc +abstract mixin class $JsError_TimeoutCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_TimeoutCopyWith( + JsError_Timeout value, $Res Function(JsError_Timeout) _then) = + _$JsError_TimeoutCopyWithImpl; + @useResult + $Res call({String operation, BigInt timeoutMs}); +} + +/// @nodoc +class _$JsError_TimeoutCopyWithImpl<$Res> + implements $JsError_TimeoutCopyWith<$Res> { + _$JsError_TimeoutCopyWithImpl(this._self, this._then); + + final JsError_Timeout _self; + final $Res Function(JsError_Timeout) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? operation = null, + Object? timeoutMs = null, + }) { + return _then(JsError_Timeout( + operation: null == operation + ? _self.operation + : operation // ignore: cast_nullable_to_non_nullable + as String, + timeoutMs: null == timeoutMs + ? _self.timeoutMs + : timeoutMs // ignore: cast_nullable_to_non_nullable + as BigInt, + )); + } +} + +/// @nodoc + +class JsError_MemoryLimit extends JsError { + const JsError_MemoryLimit({required this.current, required this.limit}) + : super._(); + + /// Current memory usage in bytes + final BigInt current; + + /// Memory limit in bytes + final BigInt limit; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_MemoryLimitCopyWith get copyWith => + _$JsError_MemoryLimitCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_MemoryLimit && + (identical(other.current, current) || other.current == current) && + (identical(other.limit, limit) || other.limit == limit)); + } + + @override + int get hashCode => Object.hash(runtimeType, current, limit); +} + +/// @nodoc +abstract mixin class $JsError_MemoryLimitCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_MemoryLimitCopyWith( + JsError_MemoryLimit value, $Res Function(JsError_MemoryLimit) _then) = + _$JsError_MemoryLimitCopyWithImpl; + @useResult + $Res call({BigInt current, BigInt limit}); +} + +/// @nodoc +class _$JsError_MemoryLimitCopyWithImpl<$Res> + implements $JsError_MemoryLimitCopyWith<$Res> { + _$JsError_MemoryLimitCopyWithImpl(this._self, this._then); + + final JsError_MemoryLimit _self; + final $Res Function(JsError_MemoryLimit) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? current = null, + Object? limit = null, + }) { + return _then(JsError_MemoryLimit( + current: null == current + ? _self.current + : current // ignore: cast_nullable_to_non_nullable + as BigInt, + limit: null == limit + ? _self.limit + : limit // ignore: cast_nullable_to_non_nullable + as BigInt, + )); + } +} + +/// @nodoc + +class JsError_StackOverflow extends JsError { + const JsError_StackOverflow(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_StackOverflowCopyWith get copyWith => + _$JsError_StackOverflowCopyWithImpl( + this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_StackOverflow && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_StackOverflowCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_StackOverflowCopyWith(JsError_StackOverflow value, + $Res Function(JsError_StackOverflow) _then) = + _$JsError_StackOverflowCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_StackOverflowCopyWithImpl<$Res> + implements $JsError_StackOverflowCopyWith<$Res> { + _$JsError_StackOverflowCopyWithImpl(this._self, this._then); + + final JsError_StackOverflow _self; + final $Res Function(JsError_StackOverflow) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_StackOverflow( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Syntax extends JsError { + const JsError_Syntax({this.line, this.column, required this.message}) + : super._(); + + /// Line number where the error occurred + final int? line; + + /// Column number where the error occurred + final int? column; + + /// Error message + final String message; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_SyntaxCopyWith get copyWith => + _$JsError_SyntaxCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Syntax && + (identical(other.line, line) || other.line == line) && + (identical(other.column, column) || other.column == column) && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, line, column, message); +} + +/// @nodoc +abstract mixin class $JsError_SyntaxCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_SyntaxCopyWith( + JsError_Syntax value, $Res Function(JsError_Syntax) _then) = + _$JsError_SyntaxCopyWithImpl; + @useResult + $Res call({int? line, int? column, String message}); +} + +/// @nodoc +class _$JsError_SyntaxCopyWithImpl<$Res> + implements $JsError_SyntaxCopyWith<$Res> { + _$JsError_SyntaxCopyWithImpl(this._self, this._then); + + final JsError_Syntax _self; + final $Res Function(JsError_Syntax) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? line = freezed, + Object? column = freezed, + Object? message = null, + }) { + return _then(JsError_Syntax( + line: freezed == line + ? _self.line + : line // ignore: cast_nullable_to_non_nullable + as int?, + column: freezed == column + ? _self.column + : column // ignore: cast_nullable_to_non_nullable + as int?, + message: null == message + ? _self.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Reference extends JsError { + const JsError_Reference(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_ReferenceCopyWith get copyWith => + _$JsError_ReferenceCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Reference && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_ReferenceCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_ReferenceCopyWith( + JsError_Reference value, $Res Function(JsError_Reference) _then) = + _$JsError_ReferenceCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_ReferenceCopyWithImpl<$Res> + implements $JsError_ReferenceCopyWith<$Res> { + _$JsError_ReferenceCopyWithImpl(this._self, this._then); + + final JsError_Reference _self; + final $Res Function(JsError_Reference) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Reference( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Type extends JsError { + const JsError_Type(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_TypeCopyWith get copyWith => + _$JsError_TypeCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Type && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_TypeCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_TypeCopyWith( + JsError_Type value, $Res Function(JsError_Type) _then) = + _$JsError_TypeCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_TypeCopyWithImpl<$Res> implements $JsError_TypeCopyWith<$Res> { + _$JsError_TypeCopyWithImpl(this._self, this._then); + + final JsError_Type _self; + final $Res Function(JsError_Type) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Type( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsError_Cancelled extends JsError { + const JsError_Cancelled(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsError_CancelledCopyWith get copyWith => + _$JsError_CancelledCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsError_Cancelled && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); +} + +/// @nodoc +abstract mixin class $JsError_CancelledCopyWith<$Res> + implements $JsErrorCopyWith<$Res> { + factory $JsError_CancelledCopyWith( + JsError_Cancelled value, $Res Function(JsError_Cancelled) _then) = + _$JsError_CancelledCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsError_CancelledCopyWithImpl<$Res> + implements $JsError_CancelledCopyWith<$Res> { + _$JsError_CancelledCopyWithImpl(this._self, this._then); + + final JsError_Cancelled _self; + final $Res Function(JsError_Cancelled) _then; + + /// Create a copy of JsError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsError_Cancelled( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +mixin _$JsResult { + Object get field0; + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsResult && + const DeepCollectionEquality().equals(other.field0, field0)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); + + @override + String toString() { + return 'JsResult(field0: $field0)'; + } +} + +/// @nodoc +class $JsResultCopyWith<$Res> { + $JsResultCopyWith(JsResult _, $Res Function(JsResult) __); +} + +/// Adds pattern-matching-related methods to [JsResult]. +extension JsResultPatterns on JsResult { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsResult_Ok value)? ok, + TResult Function(JsResult_Err value)? err, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsResult_Ok() when ok != null: + return ok(_that); + case JsResult_Err() when err != null: + return err(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsResult_Ok value) ok, + required TResult Function(JsResult_Err value) err, + }) { + final _that = this; + switch (_that) { + case JsResult_Ok(): + return ok(_that); + case JsResult_Err(): + return err(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsResult_Ok value)? ok, + TResult? Function(JsResult_Err value)? err, + }) { + final _that = this; + switch (_that) { + case JsResult_Ok() when ok != null: + return ok(_that); + case JsResult_Err() when err != null: + return err(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(JsValue field0)? ok, + TResult Function(JsError field0)? err, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsResult_Ok() when ok != null: + return ok(_that.field0); + case JsResult_Err() when err != null: + return err(_that.field0); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(JsValue field0) ok, + required TResult Function(JsError field0) err, + }) { + final _that = this; + switch (_that) { + case JsResult_Ok(): + return ok(_that.field0); + case JsResult_Err(): + return err(_that.field0); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(JsValue field0)? ok, + TResult? Function(JsError field0)? err, + }) { + final _that = this; + switch (_that) { + case JsResult_Ok() when ok != null: + return ok(_that.field0); + case JsResult_Err() when err != null: + return err(_that.field0); + case _: + return null; + } + } +} + +/// @nodoc + +class JsResult_Ok extends JsResult { + const JsResult_Ok(this.field0) : super._(); + + @override + final JsValue field0; + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsResult_OkCopyWith get copyWith => + _$JsResult_OkCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsResult_Ok && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsResult.ok(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsResult_OkCopyWith<$Res> + implements $JsResultCopyWith<$Res> { + factory $JsResult_OkCopyWith( + JsResult_Ok value, $Res Function(JsResult_Ok) _then) = + _$JsResult_OkCopyWithImpl; + @useResult + $Res call({JsValue field0}); + + $JsValueCopyWith<$Res> get field0; +} + +/// @nodoc +class _$JsResult_OkCopyWithImpl<$Res> implements $JsResult_OkCopyWith<$Res> { + _$JsResult_OkCopyWithImpl(this._self, this._then); + + final JsResult_Ok _self; + final $Res Function(JsResult_Ok) _then; + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsResult_Ok( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as JsValue, + )); + } + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsValueCopyWith<$Res> get field0 { + return $JsValueCopyWith<$Res>(_self.field0, (value) { + return _then(_self.copyWith(field0: value)); + }); + } +} + +/// @nodoc + +class JsResult_Err extends JsResult { + const JsResult_Err(this.field0) : super._(); + + @override + final JsError field0; + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsResult_ErrCopyWith get copyWith => + _$JsResult_ErrCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsResult_Err && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsResult.err(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsResult_ErrCopyWith<$Res> + implements $JsResultCopyWith<$Res> { + factory $JsResult_ErrCopyWith( + JsResult_Err value, $Res Function(JsResult_Err) _then) = + _$JsResult_ErrCopyWithImpl; + @useResult + $Res call({JsError field0}); + + $JsErrorCopyWith<$Res> get field0; +} + +/// @nodoc +class _$JsResult_ErrCopyWithImpl<$Res> implements $JsResult_ErrCopyWith<$Res> { + _$JsResult_ErrCopyWithImpl(this._self, this._then); + + final JsResult_Err _self; + final $Res Function(JsResult_Err) _then; + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsResult_Err( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as JsError, + )); + } + + /// Create a copy of JsResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsErrorCopyWith<$Res> get field0 { + return $JsErrorCopyWith<$Res>(_self.field0, (value) { + return _then(_self.copyWith(field0: value)); + }); + } +} + +// dart format on diff --git a/lib/src/frb/api/js.dart b/lib/src/frb/api/js.dart deleted file mode 100644 index 5045f1a..0000000 --- a/lib/src/frb/api/js.dart +++ /dev/null @@ -1,992 +0,0 @@ -// This file is automatically generated, so please do not edit it. -// @generated by `flutter_rust_bridge`@ 2.11.1. - -// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import - -import '../frb_generated.dart'; -import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; -import 'package:freezed_annotation/freezed_annotation.dart' hide protected; -import 'value.dart'; -part 'js.freezed.dart'; - -// These functions are ignored because they are not marked as `pub`: `context`, `from_promise_result`, `from_result`, `generic`, `get_raw_source_code`, `handle_action`, `io`, `module`, `new_bridge_call`, `promise`, `register_fjs`, `runtime`, `storage`, `to_module_builder` -// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_receiver_is_total_eq`, `assert_receiver_is_total_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `cmp`, `cmp`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `hash`, `hash`, `partial_cmp`, `partial_cmp` -// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `default`, `default` - -// Rust type: RustOpaqueMoi> -abstract class JsAsyncContext implements RustOpaqueInterface { - /// Evaluates JavaScript code with default options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string()).await?; - /// let async_result = context.eval("await Promise.resolve(42)".to_string()).await?; - /// ``` - Future eval({required String code}); - - /// Evaluates JavaScript code from a file with default options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. - Future evalFile({required String path}); - - /// Evaluates JavaScript code from a file with custom options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - Future evalFileWithOptions( - {required String path, required JsEvalOptions options}); - - /// Evaluates a specific function from a module asynchronously. - /// - /// # Parameters - /// - /// - `module`: The name of the module containing the function - /// - `method`: The name of the function to call - /// - `params`: Optional parameters to pass to the function - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval_function( - /// "my-module".to_string(), - /// "myFunction".to_string(), - /// Some(vec![JsValue::integer(42)]) - /// ).await?; - /// ``` - Future evalFunction( - {required String module, required String method, List? params}); - - /// Evaluates JavaScript code with custom options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// This method supports promise evaluation and top-level await. - Future evalWithOptions( - {required String code, required JsEvalOptions options}); - - /// Creates a new asynchronous JavaScript context from a runtime. - /// - /// # Parameters - /// - /// - `rt`: The asynchronous runtime to create the context from - /// - /// # Returns - /// - /// Returns a new `JsAsyncContext` instance or an error if creation fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsAsyncRuntime::new().await?; - /// let context = JsAsyncContext::from(&runtime).await?; - /// let result = context.eval("await Promise.resolve(42)".to_string()).await?; - /// ``` - static Future from({required JsAsyncRuntime rt}) => - LibFjs.instance.api.crateApiJsJsAsyncContextFrom(rt: rt); -} - -// Rust type: RustOpaqueMoi> -abstract class JsAsyncRuntime implements RustOpaqueInterface { - /// Executes a pending job if one is available asynchronously. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. - Future executePendingJob(); - - /// Puts the runtime into idle state, waiting for events. - /// - /// This method should be called when the runtime is not actively executing - /// JavaScript code but needs to remain responsive to events. - Future idle(); - - /// Checks if there are pending jobs to be executed asynchronously. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. - Future isJobPending(); - - /// Returns the current memory usage statistics asynchronously. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. - Future memoryUsage(); - - /// Creates a new asynchronous JavaScript runtime with default configuration. - /// - /// # Returns - /// - /// Returns a new `JsAsyncRuntime` instance or an error if initialization fails. - factory JsAsyncRuntime() => LibFjs.instance.api.crateApiJsJsAsyncRuntimeNew(); - - /// Forces garbage collection to run immediately asynchronously. - Future runGc(); - - /// Sets the garbage collection threshold asynchronously. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes - Future setGcThreshold({required BigInt threshold}); - - /// Sets runtime information for debugging purposes asynchronously. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. - Future setInfo({required String info}); - - /// Sets the maximum stack size for JavaScript execution asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes - Future setMaxStackSize({required BigInt limit}); - - /// Sets the memory limit for the runtime asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes - Future setMemoryLimit({required BigInt limit}); - - /// Creates a new asynchronous JavaScript runtime with custom configuration. - /// - /// # Parameters - /// - /// - `builtin`: Optional configuration for builtin Node.js modules - /// - `additional`: Optional list of additional JavaScript modules to load - /// - /// # Returns - /// - /// Returns a new `JsAsyncRuntime` instance with the specified configuration. - /// - /// # Examples - /// - /// ```rust - /// let builtin = JsBuiltinOptions::all(); - /// let additional = vec![JsModule::code("my-module", "export const value = 42;")]; - /// let runtime = JsAsyncRuntime::with_options(Some(builtin), Some(additional)).await?; - /// ``` - static Future withOptions( - {JsBuiltinOptions? builtin, List? additional}) => - LibFjs.instance.api.crateApiJsJsAsyncRuntimeWithOptions( - builtin: builtin, additional: additional); -} - -// Rust type: RustOpaqueMoi> -abstract class JsContext implements RustOpaqueInterface { - /// Evaluates JavaScript code with default options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string())?; - /// ``` - JsResult eval({required String code}); - - /// Evaluates JavaScript code from a file with default options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. - JsResult evalFile({required String path}); - - /// Evaluates JavaScript code from a file with custom options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. - JsResult evalFileWithOptions( - {required String path, required JsEvalOptions options}); - - /// Evaluates JavaScript code with custom options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. - /// Use `JsAsyncContext` for asynchronous operations. - JsResult evalWithOptions( - {required String code, required JsEvalOptions options}); - - /// Creates a new JavaScript context from a runtime. - /// - /// # Parameters - /// - /// - `rt`: The runtime to create the context from - /// - /// # Returns - /// - /// Returns a new `JsContext` instance or an error if creation fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsRuntime::new()?; - /// let context = JsContext::new(&runtime)?; - /// let result = context.eval("2 + 2".to_string())?; - /// ``` - factory JsContext({required JsRuntime rt}) => - LibFjs.instance.api.crateApiJsJsContextNew(rt: rt); -} - -// Rust type: RustOpaqueMoi> -abstract class JsEngineCore implements RustOpaqueInterface { - /// Returns the asynchronous context used by this engine. - /// - /// # Returns - /// - /// Returns the `JsAsyncContext` instance. - JsAsyncContext get context; - - /// Disposes the engine and cleans up resources. - /// - /// This method marks the engine as disposed and prevents further operations. - /// The actual cleanup happens when all references are dropped. - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed. - @override - Future dispose(); - - /// Checks if the engine has been disposed. - /// - /// # Returns - /// - /// Returns `true` if the engine is disposed, `false` otherwise. - bool get disposed; - - /// Executes an action on the engine. - /// - /// # Parameters - /// - /// - `action`: The action to execute - /// - /// # Errors - /// - /// Returns an error if the engine is disposed or if sending the action fails. - Future exec({required JsAction action}); - - /// Creates a new JavaScript engine core with the given context. - /// - /// # Parameters - /// - /// - `context`: The asynchronous context to use for JavaScript execution - /// - /// # Returns - /// - /// Returns a new `JsEngineCore` instance or an error if creation fails. - factory JsEngineCore({required JsAsyncContext context}) => - LibFjs.instance.api.crateApiJsJsEngineCoreNew(context: context); - - /// Checks if the engine is currently running. - /// - /// # Returns - /// - /// Returns `true` if the engine is running, `false` otherwise. - bool get running; - - /// Starts the engine event loop with a bridge callback. - /// - /// # Parameters - /// - /// - `bridge`: Callback function for handling communication between JavaScript and Dart - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed or already running. - /// - /// # Examples - /// - /// ```rust - /// engine.start(|callback| { - /// match callback { - /// JsCallback::Initialized => { - /// println!("Engine initialized"); - /// JsCallbackResult::Initialized - /// } - /// JsCallback::Handler(result) => { - /// println!("Action completed: {:?}", result); - /// JsCallbackResult::Handler - /// } - /// JsCallback::Bridge(value) => { - /// println!("Bridge call: {:?}", value); - /// JsCallbackResult::Bridge(JsResult::Ok(value)) - /// } - /// } - /// }).await?; - /// ``` - Future start( - {required FutureOr Function(JsCallback) bridge}); -} - -// Rust type: RustOpaqueMoi> -abstract class JsRuntime implements RustOpaqueInterface { - /// Executes a pending job if one is available. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. - bool executePendingJob(); - - /// Checks if there are pending jobs to be executed. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. - bool isJobPending(); - - /// Returns the current memory usage statistics. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. - MemoryUsage memoryUsage(); - - /// Creates a new JavaScript runtime with default configuration. - /// - /// # Returns - /// - /// Returns a new `JsRuntime` instance or an error if initialization fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsRuntime::new()?; - /// let context = JsContext::new(&runtime)?; - /// ``` - factory JsRuntime() => LibFjs.instance.api.crateApiJsJsRuntimeNew(); - - /// Forces garbage collection to run immediately. - void runGc(); - - /// Sets dump flags for debugging and profiling. - /// - /// # Parameters - /// - /// - `flags`: Bitmask of dump flags - void setDumpFlags({required BigInt flags}); - - /// Sets the garbage collection threshold. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes - void setGcThreshold({required BigInt threshold}); - - /// Sets runtime information for debugging purposes. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. - void setInfo({required String info}); - - /// Sets the maximum stack size for JavaScript execution. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes - void setMaxStackSize({required BigInt limit}); - - /// Sets the memory limit for the runtime. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes - void setMemoryLimit({required BigInt limit}); - - /// Creates a new JavaScript runtime with custom builtin modules and additional modules. - /// - /// # Parameters - /// - /// - `builtin`: Optional configuration for builtin Node.js modules - /// - `additional`: Optional list of additional JavaScript modules to load - /// - /// # Returns - /// - /// Returns a new `JsRuntime` instance with the specified configuration. - /// - /// # Examples - /// - /// ```rust - /// let builtin = JsBuiltinOptions::all(); - /// let additional = vec![JsModule::code("my-module", "export const value = 42;")]; - /// let runtime = JsAsyncRuntime::with_options(Some(builtin), Some(additional)).await?; - /// ``` - static Future withOptions( - {JsBuiltinOptions? builtin, List? additional}) => - LibFjs.instance.api.crateApiJsJsRuntimeWithOptions( - builtin: builtin, additional: additional); -} - -// Rust type: RustOpaqueMoi> -abstract class MemoryUsage implements RustOpaqueInterface { - /// Returns the memory usage statistic for the given field. - PlatformInt64 get arrayCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get atomCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get atomSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get binaryObjectCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get binaryObjectSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get cFuncCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get fastArrayCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get fastArrayElements; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get jsFuncCodeSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get jsFuncCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get jsFuncPc2LineCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get jsFuncPc2LineSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get jsFuncSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get mallocCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get mallocLimit; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get mallocSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get memoryUsedCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get memoryUsedSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get objCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get objSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get propCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get propSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get shapeCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get shapeSize; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get strCount; - - /// Returns the memory usage statistic for the given field. - PlatformInt64 get strSize; -} - -@freezed -sealed class JsAction with _$JsAction { - const JsAction._(); - - /// Evaluate JavaScript code with optional evaluation options. - const factory JsAction.eval({ - /// Unique identifier for this action - required int id, - - /// The source code to evaluate (either inline code or file path) - required JsCode source, - - /// Optional evaluation options - JsEvalOptions? options, - }) = JsAction_Eval; - - /// Declare a new module in the dynamic module storage. - const factory JsAction.declareNewModule({ - /// Unique identifier for this action - required int id, - - /// The module to declare - required JsModule module, - }) = JsAction_DeclareNewModule; - - /// Declare multiple new modules in the dynamic module storage. - const factory JsAction.declareNewModules({ - /// Unique identifier for this action - required int id, - - /// List of modules to declare - required List modules, - }) = JsAction_DeclareNewModules; - - /// Clear all modules from the dynamic module storage. - const factory JsAction.clearNewModules({ - /// Unique identifier for this action - required int id, - }) = JsAction_ClearNewModules; - - /// Evaluate a module and return its result. - const factory JsAction.evaluateModule({ - /// Unique identifier for this action - required int id, - - /// The module to evaluate - required JsModule module, - }) = JsAction_EvaluateModule; - - /// Get all newly declared modules from the dynamic module storage. - const factory JsAction.getDeclaredModules({ - /// Unique identifier for this action - required int id, - }) = JsAction_GetDeclaredModules; - - /// Check if a specific module is declared in the dynamic module storage. - const factory JsAction.isModuleDeclared({ - /// Unique identifier for this action - required int id, - - /// The name of the module to check - required String moduleName, - }) = JsAction_IsModuleDeclared; -} - -/// Represents the result of a JavaScript action execution. -/// -/// This struct contains the result of an action execution along with -/// the action's unique identifier for correlation purposes. -@freezed -sealed class JsActionResult with _$JsActionResult { - const factory JsActionResult({ - required int id, - required JsResult result, - }) = _JsActionResult; -} - -/// Options for configuring builtin Node.js modules. -/// -/// This struct provides fine-grained control over which Node.js -/// compatibility modules should be available in the runtime. -@freezed -sealed class JsBuiltinOptions with _$JsBuiltinOptions { - const JsBuiltinOptions._(); - const factory JsBuiltinOptions({ - bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json, - }) = _JsBuiltinOptions; - - /// Creates builtin options with all modules enabled. - /// - /// # Returns - /// - /// Returns a `JsBuiltinOptions` instance with all available modules enabled. - static JsBuiltinOptions all() => - LibFjs.instance.api.crateApiJsJsBuiltinOptionsAll(); -} - -@freezed -sealed class JsCallback with _$JsCallback { - const JsCallback._(); - - /// Indicates that the engine has been initialized and is ready - const factory JsCallback.initialized() = JsCallback_Initialized; - - /// Indicates the result of an action execution - const factory JsCallback.handler( - JsActionResult field0, - ) = JsCallback_Handler; - - /// Indicates a bridge call from JavaScript to Dart - const factory JsCallback.bridge( - JsValue field0, - ) = JsCallback_Bridge; -} - -@freezed -sealed class JsCallbackResult with _$JsCallbackResult { - const JsCallbackResult._(); - - /// Indicates successful initialization handling - const factory JsCallbackResult.initialized() = JsCallbackResult_Initialized; - - /// Indicates successful action handling - const factory JsCallbackResult.handler() = JsCallbackResult_Handler; - - /// Indicates the result of a bridge call - const factory JsCallbackResult.bridge( - JsResult field0, - ) = JsCallbackResult_Bridge; -} - -@freezed -sealed class JsCode with _$JsCode { - const JsCode._(); - - /// Inline JavaScript code - const factory JsCode.code( - String field0, - ) = JsCode_Code; - - /// File path containing JavaScript code - const factory JsCode.path( - String field0, - ) = JsCode_Path; - - /// Raw bytes containing JavaScript code (UTF-8 encoded) - const factory JsCode.bytes( - Uint8List field0, - ) = JsCode_Bytes; -} - -@freezed -sealed class JsError with _$JsError { - const JsError._(); - - /// Promise-related errors (async operation failures) - const factory JsError.promise( - String field0, - ) = JsError_Promise; - - /// Module-related errors (import/export failures) - const factory JsError.module({ - /// Optional module name where the error occurred - String? module, - - /// Optional method name where the error occurred - String? method, - - /// Error message - required String message, - }) = JsError_Module; - - /// Context attachment errors (global object setup failures) - const factory JsError.context( - String field0, - ) = JsError_Context; - - /// Storage initialization errors (dynamic module storage failures) - const factory JsError.storage( - String field0, - ) = JsError_Storage; - - /// File I/O errors (file reading failures) - const factory JsError.io({ - /// Optional file path where the error occurred - String? path, - - /// Error message - required String message, - }) = JsError_Io; - - /// JavaScript runtime errors from QuickJS engine - const factory JsError.runtime( - String field0, - ) = JsError_Runtime; - - /// Generic catch-all errors - const factory JsError.generic( - String field0, - ) = JsError_Generic; - - /// Engine lifecycle errors - const factory JsError.engine( - String field0, - ) = JsError_Engine; - - /// Bridge communication errors - const factory JsError.bridge( - String field0, - ) = JsError_Bridge; - - /// Converts the error to a string representation. - /// - /// This method provides a human-readable description of the error, - /// including contextual information when available. - /// - /// # Returns - /// - /// Returns a string describing the error. - @override - String toString() => LibFjs.instance.api.crateApiJsJsErrorToString( - that: this, - ); -} - -/// Options for JavaScript code evaluation. -/// -/// This struct provides configuration options for how JavaScript -/// code should be executed and evaluated. -@freezed -sealed class JsEvalOptions with _$JsEvalOptions { - const JsEvalOptions._(); - const factory JsEvalOptions.raw({ - bool? global, - bool? strict, - bool? backtraceBarrier, - bool? promise, - }) = _JsEvalOptions; - - /// Creates new evaluation options with the specified parameters. - /// - /// # Parameters - /// - /// - `global`: Whether to evaluate in global scope - /// - `strict`: Whether to enforce strict mode - /// - `backtrace_barrier`: Whether to create backtrace barriers - /// - `promise`: Whether to enable promise support - /// - /// # Returns - /// - /// Returns a new `JsEvalOptions` instance. - factory JsEvalOptions( - {bool? global, - bool? strict, - bool? backtraceBarrier, - bool? promise}) => - LibFjs.instance.api.crateApiJsJsEvalOptionsNew( - global: global, - strict: strict, - backtraceBarrier: backtraceBarrier, - promise: promise); -} - -/// Represents a JavaScript module. -/// -/// This struct defines a module with a name and source code, -/// which can be loaded and executed in the JavaScript runtime. -@freezed -sealed class JsModule with _$JsModule { - const JsModule._(); - const factory JsModule.raw({ - required String name, - required JsCode source, - }) = _JsModule; - - /// Creates a module from raw bytes. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `bytes`: The raw bytes containing JavaScript code (UTF-8 encoded) - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::bytes( - /// "my-module".to_string(), - /// vec![101, 120, 112, 111, 114, 116] // "export" - /// ); - /// ``` - static JsModule bytes({required String module, required List bytes}) => - LibFjs.instance.api.crateApiJsJsModuleBytes(module: module, bytes: bytes); - - /// Creates a module from inline code. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `code`: The inline JavaScript code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::code( - /// "my-module".to_string(), - /// "export const value = 42;".to_string() - /// ); - /// ``` - static JsModule code({required String module, required String code}) => - LibFjs.instance.api.crateApiJsJsModuleCode(module: module, code: code); - - /// Creates a new module with the given name and source. - /// - /// # Parameters - /// - /// - `name`: The module name - /// - `source`: The module source code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - factory JsModule({required String name, required JsCode source}) => - LibFjs.instance.api.crateApiJsJsModuleNew(name: name, source: source); - - /// Creates a module from a file path. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `path`: The file path containing JavaScript code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::path( - /// "my-module".to_string(), - /// "/path/to/module.js".to_string() - /// ); - /// ``` - static JsModule path({required String module, required String path}) => - LibFjs.instance.api.crateApiJsJsModulePath(module: module, path: path); -} - -@freezed -sealed class JsResult with _$JsResult { - const JsResult._(); - - /// Successful execution result - const factory JsResult.ok( - JsValue field0, - ) = JsResult_Ok; - - /// Error during execution - const factory JsResult.err( - JsError field0, - ) = JsResult_Err; - - bool get isOk => this is JsResult_Ok; - bool get isErr => this is JsResult_Err; - JsValue get ok => (this as JsResult_Ok).field0; - JsError get err => (this as JsResult_Err).field0; -} diff --git a/lib/src/frb/api/js.freezed.dart b/lib/src/frb/api/js.freezed.dart deleted file mode 100644 index fb904ea..0000000 --- a/lib/src/frb/api/js.freezed.dart +++ /dev/null @@ -1,5250 +0,0 @@ -// GENERATED CODE - DO NOT MODIFY BY HAND -// coverage:ignore-file -// ignore_for_file: type=lint -// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark - -part of 'js.dart'; - -// ************************************************************************** -// FreezedGenerator -// ************************************************************************** - -// dart format off -T _$identity(T value) => value; - -/// @nodoc -mixin _$JsAction { - /// Unique identifier for this action - int get id; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsActionCopyWith get copyWith => - _$JsActionCopyWithImpl(this as JsAction, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction && - (identical(other.id, id) || other.id == id)); - } - - @override - int get hashCode => Object.hash(runtimeType, id); - - @override - String toString() { - return 'JsAction(id: $id)'; - } -} - -/// @nodoc -abstract mixin class $JsActionCopyWith<$Res> { - factory $JsActionCopyWith(JsAction value, $Res Function(JsAction) _then) = - _$JsActionCopyWithImpl; - @useResult - $Res call({int id}); -} - -/// @nodoc -class _$JsActionCopyWithImpl<$Res> implements $JsActionCopyWith<$Res> { - _$JsActionCopyWithImpl(this._self, this._then); - - final JsAction _self; - final $Res Function(JsAction) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - }) { - return _then(_self.copyWith( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// Adds pattern-matching-related methods to [JsAction]. -extension JsActionPatterns on JsAction { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsAction_Eval value)? eval, - TResult Function(JsAction_DeclareNewModule value)? declareNewModule, - TResult Function(JsAction_DeclareNewModules value)? declareNewModules, - TResult Function(JsAction_ClearNewModules value)? clearNewModules, - TResult Function(JsAction_EvaluateModule value)? evaluateModule, - TResult Function(JsAction_GetDeclaredModules value)? getDeclaredModules, - TResult Function(JsAction_IsModuleDeclared value)? isModuleDeclared, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsAction_Eval() when eval != null: - return eval(_that); - case JsAction_DeclareNewModule() when declareNewModule != null: - return declareNewModule(_that); - case JsAction_DeclareNewModules() when declareNewModules != null: - return declareNewModules(_that); - case JsAction_ClearNewModules() when clearNewModules != null: - return clearNewModules(_that); - case JsAction_EvaluateModule() when evaluateModule != null: - return evaluateModule(_that); - case JsAction_GetDeclaredModules() when getDeclaredModules != null: - return getDeclaredModules(_that); - case JsAction_IsModuleDeclared() when isModuleDeclared != null: - return isModuleDeclared(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsAction_Eval value) eval, - required TResult Function(JsAction_DeclareNewModule value) declareNewModule, - required TResult Function(JsAction_DeclareNewModules value) - declareNewModules, - required TResult Function(JsAction_ClearNewModules value) clearNewModules, - required TResult Function(JsAction_EvaluateModule value) evaluateModule, - required TResult Function(JsAction_GetDeclaredModules value) - getDeclaredModules, - required TResult Function(JsAction_IsModuleDeclared value) isModuleDeclared, - }) { - final _that = this; - switch (_that) { - case JsAction_Eval(): - return eval(_that); - case JsAction_DeclareNewModule(): - return declareNewModule(_that); - case JsAction_DeclareNewModules(): - return declareNewModules(_that); - case JsAction_ClearNewModules(): - return clearNewModules(_that); - case JsAction_EvaluateModule(): - return evaluateModule(_that); - case JsAction_GetDeclaredModules(): - return getDeclaredModules(_that); - case JsAction_IsModuleDeclared(): - return isModuleDeclared(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsAction_Eval value)? eval, - TResult? Function(JsAction_DeclareNewModule value)? declareNewModule, - TResult? Function(JsAction_DeclareNewModules value)? declareNewModules, - TResult? Function(JsAction_ClearNewModules value)? clearNewModules, - TResult? Function(JsAction_EvaluateModule value)? evaluateModule, - TResult? Function(JsAction_GetDeclaredModules value)? getDeclaredModules, - TResult? Function(JsAction_IsModuleDeclared value)? isModuleDeclared, - }) { - final _that = this; - switch (_that) { - case JsAction_Eval() when eval != null: - return eval(_that); - case JsAction_DeclareNewModule() when declareNewModule != null: - return declareNewModule(_that); - case JsAction_DeclareNewModules() when declareNewModules != null: - return declareNewModules(_that); - case JsAction_ClearNewModules() when clearNewModules != null: - return clearNewModules(_that); - case JsAction_EvaluateModule() when evaluateModule != null: - return evaluateModule(_that); - case JsAction_GetDeclaredModules() when getDeclaredModules != null: - return getDeclaredModules(_that); - case JsAction_IsModuleDeclared() when isModuleDeclared != null: - return isModuleDeclared(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(int id, JsCode source, JsEvalOptions? options)? eval, - TResult Function(int id, JsModule module)? declareNewModule, - TResult Function(int id, List modules)? declareNewModules, - TResult Function(int id)? clearNewModules, - TResult Function(int id, JsModule module)? evaluateModule, - TResult Function(int id)? getDeclaredModules, - TResult Function(int id, String moduleName)? isModuleDeclared, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsAction_Eval() when eval != null: - return eval(_that.id, _that.source, _that.options); - case JsAction_DeclareNewModule() when declareNewModule != null: - return declareNewModule(_that.id, _that.module); - case JsAction_DeclareNewModules() when declareNewModules != null: - return declareNewModules(_that.id, _that.modules); - case JsAction_ClearNewModules() when clearNewModules != null: - return clearNewModules(_that.id); - case JsAction_EvaluateModule() when evaluateModule != null: - return evaluateModule(_that.id, _that.module); - case JsAction_GetDeclaredModules() when getDeclaredModules != null: - return getDeclaredModules(_that.id); - case JsAction_IsModuleDeclared() when isModuleDeclared != null: - return isModuleDeclared(_that.id, _that.moduleName); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function(int id, JsCode source, JsEvalOptions? options) - eval, - required TResult Function(int id, JsModule module) declareNewModule, - required TResult Function(int id, List modules) declareNewModules, - required TResult Function(int id) clearNewModules, - required TResult Function(int id, JsModule module) evaluateModule, - required TResult Function(int id) getDeclaredModules, - required TResult Function(int id, String moduleName) isModuleDeclared, - }) { - final _that = this; - switch (_that) { - case JsAction_Eval(): - return eval(_that.id, _that.source, _that.options); - case JsAction_DeclareNewModule(): - return declareNewModule(_that.id, _that.module); - case JsAction_DeclareNewModules(): - return declareNewModules(_that.id, _that.modules); - case JsAction_ClearNewModules(): - return clearNewModules(_that.id); - case JsAction_EvaluateModule(): - return evaluateModule(_that.id, _that.module); - case JsAction_GetDeclaredModules(): - return getDeclaredModules(_that.id); - case JsAction_IsModuleDeclared(): - return isModuleDeclared(_that.id, _that.moduleName); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(int id, JsCode source, JsEvalOptions? options)? eval, - TResult? Function(int id, JsModule module)? declareNewModule, - TResult? Function(int id, List modules)? declareNewModules, - TResult? Function(int id)? clearNewModules, - TResult? Function(int id, JsModule module)? evaluateModule, - TResult? Function(int id)? getDeclaredModules, - TResult? Function(int id, String moduleName)? isModuleDeclared, - }) { - final _that = this; - switch (_that) { - case JsAction_Eval() when eval != null: - return eval(_that.id, _that.source, _that.options); - case JsAction_DeclareNewModule() when declareNewModule != null: - return declareNewModule(_that.id, _that.module); - case JsAction_DeclareNewModules() when declareNewModules != null: - return declareNewModules(_that.id, _that.modules); - case JsAction_ClearNewModules() when clearNewModules != null: - return clearNewModules(_that.id); - case JsAction_EvaluateModule() when evaluateModule != null: - return evaluateModule(_that.id, _that.module); - case JsAction_GetDeclaredModules() when getDeclaredModules != null: - return getDeclaredModules(_that.id); - case JsAction_IsModuleDeclared() when isModuleDeclared != null: - return isModuleDeclared(_that.id, _that.moduleName); - case _: - return null; - } - } -} - -/// @nodoc - -class JsAction_Eval extends JsAction { - const JsAction_Eval({required this.id, required this.source, this.options}) - : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// The source code to evaluate (either inline code or file path) - final JsCode source; - - /// Optional evaluation options - final JsEvalOptions? options; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_EvalCopyWith get copyWith => - _$JsAction_EvalCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_Eval && - (identical(other.id, id) || other.id == id) && - (identical(other.source, source) || other.source == source) && - (identical(other.options, options) || other.options == options)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, source, options); - - @override - String toString() { - return 'JsAction.eval(id: $id, source: $source, options: $options)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_EvalCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_EvalCopyWith( - JsAction_Eval value, $Res Function(JsAction_Eval) _then) = - _$JsAction_EvalCopyWithImpl; - @override - @useResult - $Res call({int id, JsCode source, JsEvalOptions? options}); - - $JsCodeCopyWith<$Res> get source; - $JsEvalOptionsCopyWith<$Res>? get options; -} - -/// @nodoc -class _$JsAction_EvalCopyWithImpl<$Res> - implements $JsAction_EvalCopyWith<$Res> { - _$JsAction_EvalCopyWithImpl(this._self, this._then); - - final JsAction_Eval _self; - final $Res Function(JsAction_Eval) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? source = null, - Object? options = freezed, - }) { - return _then(JsAction_Eval( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - source: null == source - ? _self.source - : source // ignore: cast_nullable_to_non_nullable - as JsCode, - options: freezed == options - ? _self.options - : options // ignore: cast_nullable_to_non_nullable - as JsEvalOptions?, - )); - } - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsCodeCopyWith<$Res> get source { - return $JsCodeCopyWith<$Res>(_self.source, (value) { - return _then(_self.copyWith(source: value)); - }); - } - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsEvalOptionsCopyWith<$Res>? get options { - if (_self.options == null) { - return null; - } - - return $JsEvalOptionsCopyWith<$Res>(_self.options!, (value) { - return _then(_self.copyWith(options: value)); - }); - } -} - -/// @nodoc - -class JsAction_DeclareNewModule extends JsAction { - const JsAction_DeclareNewModule({required this.id, required this.module}) - : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// The module to declare - final JsModule module; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_DeclareNewModuleCopyWith get copyWith => - _$JsAction_DeclareNewModuleCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_DeclareNewModule && - (identical(other.id, id) || other.id == id) && - (identical(other.module, module) || other.module == module)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, module); - - @override - String toString() { - return 'JsAction.declareNewModule(id: $id, module: $module)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_DeclareNewModuleCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_DeclareNewModuleCopyWith(JsAction_DeclareNewModule value, - $Res Function(JsAction_DeclareNewModule) _then) = - _$JsAction_DeclareNewModuleCopyWithImpl; - @override - @useResult - $Res call({int id, JsModule module}); - - $JsModuleCopyWith<$Res> get module; -} - -/// @nodoc -class _$JsAction_DeclareNewModuleCopyWithImpl<$Res> - implements $JsAction_DeclareNewModuleCopyWith<$Res> { - _$JsAction_DeclareNewModuleCopyWithImpl(this._self, this._then); - - final JsAction_DeclareNewModule _self; - final $Res Function(JsAction_DeclareNewModule) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? module = null, - }) { - return _then(JsAction_DeclareNewModule( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - module: null == module - ? _self.module - : module // ignore: cast_nullable_to_non_nullable - as JsModule, - )); - } - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsModuleCopyWith<$Res> get module { - return $JsModuleCopyWith<$Res>(_self.module, (value) { - return _then(_self.copyWith(module: value)); - }); - } -} - -/// @nodoc - -class JsAction_DeclareNewModules extends JsAction { - const JsAction_DeclareNewModules( - {required this.id, required final List modules}) - : _modules = modules, - super._(); - - /// Unique identifier for this action - @override - final int id; - - /// List of modules to declare - final List _modules; - - /// List of modules to declare - List get modules { - if (_modules is EqualUnmodifiableListView) return _modules; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_modules); - } - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_DeclareNewModulesCopyWith - get copyWith => - _$JsAction_DeclareNewModulesCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_DeclareNewModules && - (identical(other.id, id) || other.id == id) && - const DeepCollectionEquality().equals(other._modules, _modules)); - } - - @override - int get hashCode => Object.hash( - runtimeType, id, const DeepCollectionEquality().hash(_modules)); - - @override - String toString() { - return 'JsAction.declareNewModules(id: $id, modules: $modules)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_DeclareNewModulesCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_DeclareNewModulesCopyWith(JsAction_DeclareNewModules value, - $Res Function(JsAction_DeclareNewModules) _then) = - _$JsAction_DeclareNewModulesCopyWithImpl; - @override - @useResult - $Res call({int id, List modules}); -} - -/// @nodoc -class _$JsAction_DeclareNewModulesCopyWithImpl<$Res> - implements $JsAction_DeclareNewModulesCopyWith<$Res> { - _$JsAction_DeclareNewModulesCopyWithImpl(this._self, this._then); - - final JsAction_DeclareNewModules _self; - final $Res Function(JsAction_DeclareNewModules) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? modules = null, - }) { - return _then(JsAction_DeclareNewModules( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - modules: null == modules - ? _self._modules - : modules // ignore: cast_nullable_to_non_nullable - as List, - )); - } -} - -/// @nodoc - -class JsAction_ClearNewModules extends JsAction { - const JsAction_ClearNewModules({required this.id}) : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_ClearNewModulesCopyWith get copyWith => - _$JsAction_ClearNewModulesCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_ClearNewModules && - (identical(other.id, id) || other.id == id)); - } - - @override - int get hashCode => Object.hash(runtimeType, id); - - @override - String toString() { - return 'JsAction.clearNewModules(id: $id)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_ClearNewModulesCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_ClearNewModulesCopyWith(JsAction_ClearNewModules value, - $Res Function(JsAction_ClearNewModules) _then) = - _$JsAction_ClearNewModulesCopyWithImpl; - @override - @useResult - $Res call({int id}); -} - -/// @nodoc -class _$JsAction_ClearNewModulesCopyWithImpl<$Res> - implements $JsAction_ClearNewModulesCopyWith<$Res> { - _$JsAction_ClearNewModulesCopyWithImpl(this._self, this._then); - - final JsAction_ClearNewModules _self; - final $Res Function(JsAction_ClearNewModules) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - }) { - return _then(JsAction_ClearNewModules( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// @nodoc - -class JsAction_EvaluateModule extends JsAction { - const JsAction_EvaluateModule({required this.id, required this.module}) - : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// The module to evaluate - final JsModule module; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_EvaluateModuleCopyWith get copyWith => - _$JsAction_EvaluateModuleCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_EvaluateModule && - (identical(other.id, id) || other.id == id) && - (identical(other.module, module) || other.module == module)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, module); - - @override - String toString() { - return 'JsAction.evaluateModule(id: $id, module: $module)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_EvaluateModuleCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_EvaluateModuleCopyWith(JsAction_EvaluateModule value, - $Res Function(JsAction_EvaluateModule) _then) = - _$JsAction_EvaluateModuleCopyWithImpl; - @override - @useResult - $Res call({int id, JsModule module}); - - $JsModuleCopyWith<$Res> get module; -} - -/// @nodoc -class _$JsAction_EvaluateModuleCopyWithImpl<$Res> - implements $JsAction_EvaluateModuleCopyWith<$Res> { - _$JsAction_EvaluateModuleCopyWithImpl(this._self, this._then); - - final JsAction_EvaluateModule _self; - final $Res Function(JsAction_EvaluateModule) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? module = null, - }) { - return _then(JsAction_EvaluateModule( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - module: null == module - ? _self.module - : module // ignore: cast_nullable_to_non_nullable - as JsModule, - )); - } - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsModuleCopyWith<$Res> get module { - return $JsModuleCopyWith<$Res>(_self.module, (value) { - return _then(_self.copyWith(module: value)); - }); - } -} - -/// @nodoc - -class JsAction_GetDeclaredModules extends JsAction { - const JsAction_GetDeclaredModules({required this.id}) : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_GetDeclaredModulesCopyWith - get copyWith => _$JsAction_GetDeclaredModulesCopyWithImpl< - JsAction_GetDeclaredModules>(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_GetDeclaredModules && - (identical(other.id, id) || other.id == id)); - } - - @override - int get hashCode => Object.hash(runtimeType, id); - - @override - String toString() { - return 'JsAction.getDeclaredModules(id: $id)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_GetDeclaredModulesCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_GetDeclaredModulesCopyWith( - JsAction_GetDeclaredModules value, - $Res Function(JsAction_GetDeclaredModules) _then) = - _$JsAction_GetDeclaredModulesCopyWithImpl; - @override - @useResult - $Res call({int id}); -} - -/// @nodoc -class _$JsAction_GetDeclaredModulesCopyWithImpl<$Res> - implements $JsAction_GetDeclaredModulesCopyWith<$Res> { - _$JsAction_GetDeclaredModulesCopyWithImpl(this._self, this._then); - - final JsAction_GetDeclaredModules _self; - final $Res Function(JsAction_GetDeclaredModules) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - }) { - return _then(JsAction_GetDeclaredModules( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - )); - } -} - -/// @nodoc - -class JsAction_IsModuleDeclared extends JsAction { - const JsAction_IsModuleDeclared({required this.id, required this.moduleName}) - : super._(); - - /// Unique identifier for this action - @override - final int id; - - /// The name of the module to check - final String moduleName; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsAction_IsModuleDeclaredCopyWith get copyWith => - _$JsAction_IsModuleDeclaredCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsAction_IsModuleDeclared && - (identical(other.id, id) || other.id == id) && - (identical(other.moduleName, moduleName) || - other.moduleName == moduleName)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, moduleName); - - @override - String toString() { - return 'JsAction.isModuleDeclared(id: $id, moduleName: $moduleName)'; - } -} - -/// @nodoc -abstract mixin class $JsAction_IsModuleDeclaredCopyWith<$Res> - implements $JsActionCopyWith<$Res> { - factory $JsAction_IsModuleDeclaredCopyWith(JsAction_IsModuleDeclared value, - $Res Function(JsAction_IsModuleDeclared) _then) = - _$JsAction_IsModuleDeclaredCopyWithImpl; - @override - @useResult - $Res call({int id, String moduleName}); -} - -/// @nodoc -class _$JsAction_IsModuleDeclaredCopyWithImpl<$Res> - implements $JsAction_IsModuleDeclaredCopyWith<$Res> { - _$JsAction_IsModuleDeclaredCopyWithImpl(this._self, this._then); - - final JsAction_IsModuleDeclared _self; - final $Res Function(JsAction_IsModuleDeclared) _then; - - /// Create a copy of JsAction - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? moduleName = null, - }) { - return _then(JsAction_IsModuleDeclared( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - moduleName: null == moduleName - ? _self.moduleName - : moduleName // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc -mixin _$JsActionResult { - int get id; - JsResult get result; - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsActionResultCopyWith get copyWith => - _$JsActionResultCopyWithImpl( - this as JsActionResult, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsActionResult && - (identical(other.id, id) || other.id == id) && - (identical(other.result, result) || other.result == result)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, result); - - @override - String toString() { - return 'JsActionResult(id: $id, result: $result)'; - } -} - -/// @nodoc -abstract mixin class $JsActionResultCopyWith<$Res> { - factory $JsActionResultCopyWith( - JsActionResult value, $Res Function(JsActionResult) _then) = - _$JsActionResultCopyWithImpl; - @useResult - $Res call({int id, JsResult result}); - - $JsResultCopyWith<$Res> get result; -} - -/// @nodoc -class _$JsActionResultCopyWithImpl<$Res> - implements $JsActionResultCopyWith<$Res> { - _$JsActionResultCopyWithImpl(this._self, this._then); - - final JsActionResult _self; - final $Res Function(JsActionResult) _then; - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? id = null, - Object? result = null, - }) { - return _then(_self.copyWith( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - result: null == result - ? _self.result - : result // ignore: cast_nullable_to_non_nullable - as JsResult, - )); - } - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsResultCopyWith<$Res> get result { - return $JsResultCopyWith<$Res>(_self.result, (value) { - return _then(_self.copyWith(result: value)); - }); - } -} - -/// Adds pattern-matching-related methods to [JsActionResult]. -extension JsActionResultPatterns on JsActionResult { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap( - TResult Function(_JsActionResult value)? $default, { - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsActionResult() when $default != null: - return $default(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map( - TResult Function(_JsActionResult value) $default, - ) { - final _that = this; - switch (_that) { - case _JsActionResult(): - return $default(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull( - TResult? Function(_JsActionResult value)? $default, - ) { - final _that = this; - switch (_that) { - case _JsActionResult() when $default != null: - return $default(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen( - TResult Function(int id, JsResult result)? $default, { - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsActionResult() when $default != null: - return $default(_that.id, _that.result); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when( - TResult Function(int id, JsResult result) $default, - ) { - final _that = this; - switch (_that) { - case _JsActionResult(): - return $default(_that.id, _that.result); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull( - TResult? Function(int id, JsResult result)? $default, - ) { - final _that = this; - switch (_that) { - case _JsActionResult() when $default != null: - return $default(_that.id, _that.result); - case _: - return null; - } - } -} - -/// @nodoc - -class _JsActionResult implements JsActionResult { - const _JsActionResult({required this.id, required this.result}); - - @override - final int id; - @override - final JsResult result; - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - _$JsActionResultCopyWith<_JsActionResult> get copyWith => - __$JsActionResultCopyWithImpl<_JsActionResult>(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _JsActionResult && - (identical(other.id, id) || other.id == id) && - (identical(other.result, result) || other.result == result)); - } - - @override - int get hashCode => Object.hash(runtimeType, id, result); - - @override - String toString() { - return 'JsActionResult(id: $id, result: $result)'; - } -} - -/// @nodoc -abstract mixin class _$JsActionResultCopyWith<$Res> - implements $JsActionResultCopyWith<$Res> { - factory _$JsActionResultCopyWith( - _JsActionResult value, $Res Function(_JsActionResult) _then) = - __$JsActionResultCopyWithImpl; - @override - @useResult - $Res call({int id, JsResult result}); - - @override - $JsResultCopyWith<$Res> get result; -} - -/// @nodoc -class __$JsActionResultCopyWithImpl<$Res> - implements _$JsActionResultCopyWith<$Res> { - __$JsActionResultCopyWithImpl(this._self, this._then); - - final _JsActionResult _self; - final $Res Function(_JsActionResult) _then; - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? id = null, - Object? result = null, - }) { - return _then(_JsActionResult( - id: null == id - ? _self.id - : id // ignore: cast_nullable_to_non_nullable - as int, - result: null == result - ? _self.result - : result // ignore: cast_nullable_to_non_nullable - as JsResult, - )); - } - - /// Create a copy of JsActionResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsResultCopyWith<$Res> get result { - return $JsResultCopyWith<$Res>(_self.result, (value) { - return _then(_self.copyWith(result: value)); - }); - } -} - -/// @nodoc -mixin _$JsBuiltinOptions { - bool? get abort; - bool? get assert_; - bool? get asyncHooks; - bool? get buffer; - bool? get childProcess; - bool? get console; - bool? get crypto; - bool? get dns; - bool? get events; - bool? get exceptions; - bool? get fetch; - bool? get fs; - bool? get navigator; - bool? get net; - bool? get os; - bool? get path; - bool? get perfHooks; - bool? get process; - bool? get streamWeb; - bool? get stringDecoder; - bool? get timers; - bool? get tty; - bool? get url; - bool? get util; - bool? get zlib; - bool? get json; - - /// Create a copy of JsBuiltinOptions - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsBuiltinOptionsCopyWith get copyWith => - _$JsBuiltinOptionsCopyWithImpl( - this as JsBuiltinOptions, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsBuiltinOptions && - (identical(other.abort, abort) || other.abort == abort) && - (identical(other.assert_, assert_) || other.assert_ == assert_) && - (identical(other.asyncHooks, asyncHooks) || - other.asyncHooks == asyncHooks) && - (identical(other.buffer, buffer) || other.buffer == buffer) && - (identical(other.childProcess, childProcess) || - other.childProcess == childProcess) && - (identical(other.console, console) || other.console == console) && - (identical(other.crypto, crypto) || other.crypto == crypto) && - (identical(other.dns, dns) || other.dns == dns) && - (identical(other.events, events) || other.events == events) && - (identical(other.exceptions, exceptions) || - other.exceptions == exceptions) && - (identical(other.fetch, fetch) || other.fetch == fetch) && - (identical(other.fs, fs) || other.fs == fs) && - (identical(other.navigator, navigator) || - other.navigator == navigator) && - (identical(other.net, net) || other.net == net) && - (identical(other.os, os) || other.os == os) && - (identical(other.path, path) || other.path == path) && - (identical(other.perfHooks, perfHooks) || - other.perfHooks == perfHooks) && - (identical(other.process, process) || other.process == process) && - (identical(other.streamWeb, streamWeb) || - other.streamWeb == streamWeb) && - (identical(other.stringDecoder, stringDecoder) || - other.stringDecoder == stringDecoder) && - (identical(other.timers, timers) || other.timers == timers) && - (identical(other.tty, tty) || other.tty == tty) && - (identical(other.url, url) || other.url == url) && - (identical(other.util, util) || other.util == util) && - (identical(other.zlib, zlib) || other.zlib == zlib) && - (identical(other.json, json) || other.json == json)); - } - - @override - int get hashCode => Object.hashAll([ - runtimeType, - abort, - assert_, - asyncHooks, - buffer, - childProcess, - console, - crypto, - dns, - events, - exceptions, - fetch, - fs, - navigator, - net, - os, - path, - perfHooks, - process, - streamWeb, - stringDecoder, - timers, - tty, - url, - util, - zlib, - json - ]); - - @override - String toString() { - return 'JsBuiltinOptions(abort: $abort, assert_: $assert_, asyncHooks: $asyncHooks, buffer: $buffer, childProcess: $childProcess, console: $console, crypto: $crypto, dns: $dns, events: $events, exceptions: $exceptions, fetch: $fetch, fs: $fs, navigator: $navigator, net: $net, os: $os, path: $path, perfHooks: $perfHooks, process: $process, streamWeb: $streamWeb, stringDecoder: $stringDecoder, timers: $timers, tty: $tty, url: $url, util: $util, zlib: $zlib, json: $json)'; - } -} - -/// @nodoc -abstract mixin class $JsBuiltinOptionsCopyWith<$Res> { - factory $JsBuiltinOptionsCopyWith( - JsBuiltinOptions value, $Res Function(JsBuiltinOptions) _then) = - _$JsBuiltinOptionsCopyWithImpl; - @useResult - $Res call( - {bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json}); -} - -/// @nodoc -class _$JsBuiltinOptionsCopyWithImpl<$Res> - implements $JsBuiltinOptionsCopyWith<$Res> { - _$JsBuiltinOptionsCopyWithImpl(this._self, this._then); - - final JsBuiltinOptions _self; - final $Res Function(JsBuiltinOptions) _then; - - /// Create a copy of JsBuiltinOptions - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? abort = freezed, - Object? assert_ = freezed, - Object? asyncHooks = freezed, - Object? buffer = freezed, - Object? childProcess = freezed, - Object? console = freezed, - Object? crypto = freezed, - Object? dns = freezed, - Object? events = freezed, - Object? exceptions = freezed, - Object? fetch = freezed, - Object? fs = freezed, - Object? navigator = freezed, - Object? net = freezed, - Object? os = freezed, - Object? path = freezed, - Object? perfHooks = freezed, - Object? process = freezed, - Object? streamWeb = freezed, - Object? stringDecoder = freezed, - Object? timers = freezed, - Object? tty = freezed, - Object? url = freezed, - Object? util = freezed, - Object? zlib = freezed, - Object? json = freezed, - }) { - return _then(_self.copyWith( - abort: freezed == abort - ? _self.abort - : abort // ignore: cast_nullable_to_non_nullable - as bool?, - assert_: freezed == assert_ - ? _self.assert_ - : assert_ // ignore: cast_nullable_to_non_nullable - as bool?, - asyncHooks: freezed == asyncHooks - ? _self.asyncHooks - : asyncHooks // ignore: cast_nullable_to_non_nullable - as bool?, - buffer: freezed == buffer - ? _self.buffer - : buffer // ignore: cast_nullable_to_non_nullable - as bool?, - childProcess: freezed == childProcess - ? _self.childProcess - : childProcess // ignore: cast_nullable_to_non_nullable - as bool?, - console: freezed == console - ? _self.console - : console // ignore: cast_nullable_to_non_nullable - as bool?, - crypto: freezed == crypto - ? _self.crypto - : crypto // ignore: cast_nullable_to_non_nullable - as bool?, - dns: freezed == dns - ? _self.dns - : dns // ignore: cast_nullable_to_non_nullable - as bool?, - events: freezed == events - ? _self.events - : events // ignore: cast_nullable_to_non_nullable - as bool?, - exceptions: freezed == exceptions - ? _self.exceptions - : exceptions // ignore: cast_nullable_to_non_nullable - as bool?, - fetch: freezed == fetch - ? _self.fetch - : fetch // ignore: cast_nullable_to_non_nullable - as bool?, - fs: freezed == fs - ? _self.fs - : fs // ignore: cast_nullable_to_non_nullable - as bool?, - navigator: freezed == navigator - ? _self.navigator - : navigator // ignore: cast_nullable_to_non_nullable - as bool?, - net: freezed == net - ? _self.net - : net // ignore: cast_nullable_to_non_nullable - as bool?, - os: freezed == os - ? _self.os - : os // ignore: cast_nullable_to_non_nullable - as bool?, - path: freezed == path - ? _self.path - : path // ignore: cast_nullable_to_non_nullable - as bool?, - perfHooks: freezed == perfHooks - ? _self.perfHooks - : perfHooks // ignore: cast_nullable_to_non_nullable - as bool?, - process: freezed == process - ? _self.process - : process // ignore: cast_nullable_to_non_nullable - as bool?, - streamWeb: freezed == streamWeb - ? _self.streamWeb - : streamWeb // ignore: cast_nullable_to_non_nullable - as bool?, - stringDecoder: freezed == stringDecoder - ? _self.stringDecoder - : stringDecoder // ignore: cast_nullable_to_non_nullable - as bool?, - timers: freezed == timers - ? _self.timers - : timers // ignore: cast_nullable_to_non_nullable - as bool?, - tty: freezed == tty - ? _self.tty - : tty // ignore: cast_nullable_to_non_nullable - as bool?, - url: freezed == url - ? _self.url - : url // ignore: cast_nullable_to_non_nullable - as bool?, - util: freezed == util - ? _self.util - : util // ignore: cast_nullable_to_non_nullable - as bool?, - zlib: freezed == zlib - ? _self.zlib - : zlib // ignore: cast_nullable_to_non_nullable - as bool?, - json: freezed == json - ? _self.json - : json // ignore: cast_nullable_to_non_nullable - as bool?, - )); - } -} - -/// Adds pattern-matching-related methods to [JsBuiltinOptions]. -extension JsBuiltinOptionsPatterns on JsBuiltinOptions { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap( - TResult Function(_JsBuiltinOptions value)? $default, { - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions() when $default != null: - return $default(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map( - TResult Function(_JsBuiltinOptions value) $default, - ) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions(): - return $default(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull( - TResult? Function(_JsBuiltinOptions value)? $default, - ) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions() when $default != null: - return $default(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen( - TResult Function( - bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json)? - $default, { - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions() when $default != null: - return $default( - _that.abort, - _that.assert_, - _that.asyncHooks, - _that.buffer, - _that.childProcess, - _that.console, - _that.crypto, - _that.dns, - _that.events, - _that.exceptions, - _that.fetch, - _that.fs, - _that.navigator, - _that.net, - _that.os, - _that.path, - _that.perfHooks, - _that.process, - _that.streamWeb, - _that.stringDecoder, - _that.timers, - _that.tty, - _that.url, - _that.util, - _that.zlib, - _that.json); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when( - TResult Function( - bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json) - $default, - ) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions(): - return $default( - _that.abort, - _that.assert_, - _that.asyncHooks, - _that.buffer, - _that.childProcess, - _that.console, - _that.crypto, - _that.dns, - _that.events, - _that.exceptions, - _that.fetch, - _that.fs, - _that.navigator, - _that.net, - _that.os, - _that.path, - _that.perfHooks, - _that.process, - _that.streamWeb, - _that.stringDecoder, - _that.timers, - _that.tty, - _that.url, - _that.util, - _that.zlib, - _that.json); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull( - TResult? Function( - bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json)? - $default, - ) { - final _that = this; - switch (_that) { - case _JsBuiltinOptions() when $default != null: - return $default( - _that.abort, - _that.assert_, - _that.asyncHooks, - _that.buffer, - _that.childProcess, - _that.console, - _that.crypto, - _that.dns, - _that.events, - _that.exceptions, - _that.fetch, - _that.fs, - _that.navigator, - _that.net, - _that.os, - _that.path, - _that.perfHooks, - _that.process, - _that.streamWeb, - _that.stringDecoder, - _that.timers, - _that.tty, - _that.url, - _that.util, - _that.zlib, - _that.json); - case _: - return null; - } - } -} - -/// @nodoc - -class _JsBuiltinOptions extends JsBuiltinOptions { - const _JsBuiltinOptions( - {this.abort, - this.assert_, - this.asyncHooks, - this.buffer, - this.childProcess, - this.console, - this.crypto, - this.dns, - this.events, - this.exceptions, - this.fetch, - this.fs, - this.navigator, - this.net, - this.os, - this.path, - this.perfHooks, - this.process, - this.streamWeb, - this.stringDecoder, - this.timers, - this.tty, - this.url, - this.util, - this.zlib, - this.json}) - : super._(); - - @override - final bool? abort; - @override - final bool? assert_; - @override - final bool? asyncHooks; - @override - final bool? buffer; - @override - final bool? childProcess; - @override - final bool? console; - @override - final bool? crypto; - @override - final bool? dns; - @override - final bool? events; - @override - final bool? exceptions; - @override - final bool? fetch; - @override - final bool? fs; - @override - final bool? navigator; - @override - final bool? net; - @override - final bool? os; - @override - final bool? path; - @override - final bool? perfHooks; - @override - final bool? process; - @override - final bool? streamWeb; - @override - final bool? stringDecoder; - @override - final bool? timers; - @override - final bool? tty; - @override - final bool? url; - @override - final bool? util; - @override - final bool? zlib; - @override - final bool? json; - - /// Create a copy of JsBuiltinOptions - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - _$JsBuiltinOptionsCopyWith<_JsBuiltinOptions> get copyWith => - __$JsBuiltinOptionsCopyWithImpl<_JsBuiltinOptions>(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _JsBuiltinOptions && - (identical(other.abort, abort) || other.abort == abort) && - (identical(other.assert_, assert_) || other.assert_ == assert_) && - (identical(other.asyncHooks, asyncHooks) || - other.asyncHooks == asyncHooks) && - (identical(other.buffer, buffer) || other.buffer == buffer) && - (identical(other.childProcess, childProcess) || - other.childProcess == childProcess) && - (identical(other.console, console) || other.console == console) && - (identical(other.crypto, crypto) || other.crypto == crypto) && - (identical(other.dns, dns) || other.dns == dns) && - (identical(other.events, events) || other.events == events) && - (identical(other.exceptions, exceptions) || - other.exceptions == exceptions) && - (identical(other.fetch, fetch) || other.fetch == fetch) && - (identical(other.fs, fs) || other.fs == fs) && - (identical(other.navigator, navigator) || - other.navigator == navigator) && - (identical(other.net, net) || other.net == net) && - (identical(other.os, os) || other.os == os) && - (identical(other.path, path) || other.path == path) && - (identical(other.perfHooks, perfHooks) || - other.perfHooks == perfHooks) && - (identical(other.process, process) || other.process == process) && - (identical(other.streamWeb, streamWeb) || - other.streamWeb == streamWeb) && - (identical(other.stringDecoder, stringDecoder) || - other.stringDecoder == stringDecoder) && - (identical(other.timers, timers) || other.timers == timers) && - (identical(other.tty, tty) || other.tty == tty) && - (identical(other.url, url) || other.url == url) && - (identical(other.util, util) || other.util == util) && - (identical(other.zlib, zlib) || other.zlib == zlib) && - (identical(other.json, json) || other.json == json)); - } - - @override - int get hashCode => Object.hashAll([ - runtimeType, - abort, - assert_, - asyncHooks, - buffer, - childProcess, - console, - crypto, - dns, - events, - exceptions, - fetch, - fs, - navigator, - net, - os, - path, - perfHooks, - process, - streamWeb, - stringDecoder, - timers, - tty, - url, - util, - zlib, - json - ]); - - @override - String toString() { - return 'JsBuiltinOptions(abort: $abort, assert_: $assert_, asyncHooks: $asyncHooks, buffer: $buffer, childProcess: $childProcess, console: $console, crypto: $crypto, dns: $dns, events: $events, exceptions: $exceptions, fetch: $fetch, fs: $fs, navigator: $navigator, net: $net, os: $os, path: $path, perfHooks: $perfHooks, process: $process, streamWeb: $streamWeb, stringDecoder: $stringDecoder, timers: $timers, tty: $tty, url: $url, util: $util, zlib: $zlib, json: $json)'; - } -} - -/// @nodoc -abstract mixin class _$JsBuiltinOptionsCopyWith<$Res> - implements $JsBuiltinOptionsCopyWith<$Res> { - factory _$JsBuiltinOptionsCopyWith( - _JsBuiltinOptions value, $Res Function(_JsBuiltinOptions) _then) = - __$JsBuiltinOptionsCopyWithImpl; - @override - @useResult - $Res call( - {bool? abort, - bool? assert_, - bool? asyncHooks, - bool? buffer, - bool? childProcess, - bool? console, - bool? crypto, - bool? dns, - bool? events, - bool? exceptions, - bool? fetch, - bool? fs, - bool? navigator, - bool? net, - bool? os, - bool? path, - bool? perfHooks, - bool? process, - bool? streamWeb, - bool? stringDecoder, - bool? timers, - bool? tty, - bool? url, - bool? util, - bool? zlib, - bool? json}); -} - -/// @nodoc -class __$JsBuiltinOptionsCopyWithImpl<$Res> - implements _$JsBuiltinOptionsCopyWith<$Res> { - __$JsBuiltinOptionsCopyWithImpl(this._self, this._then); - - final _JsBuiltinOptions _self; - final $Res Function(_JsBuiltinOptions) _then; - - /// Create a copy of JsBuiltinOptions - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? abort = freezed, - Object? assert_ = freezed, - Object? asyncHooks = freezed, - Object? buffer = freezed, - Object? childProcess = freezed, - Object? console = freezed, - Object? crypto = freezed, - Object? dns = freezed, - Object? events = freezed, - Object? exceptions = freezed, - Object? fetch = freezed, - Object? fs = freezed, - Object? navigator = freezed, - Object? net = freezed, - Object? os = freezed, - Object? path = freezed, - Object? perfHooks = freezed, - Object? process = freezed, - Object? streamWeb = freezed, - Object? stringDecoder = freezed, - Object? timers = freezed, - Object? tty = freezed, - Object? url = freezed, - Object? util = freezed, - Object? zlib = freezed, - Object? json = freezed, - }) { - return _then(_JsBuiltinOptions( - abort: freezed == abort - ? _self.abort - : abort // ignore: cast_nullable_to_non_nullable - as bool?, - assert_: freezed == assert_ - ? _self.assert_ - : assert_ // ignore: cast_nullable_to_non_nullable - as bool?, - asyncHooks: freezed == asyncHooks - ? _self.asyncHooks - : asyncHooks // ignore: cast_nullable_to_non_nullable - as bool?, - buffer: freezed == buffer - ? _self.buffer - : buffer // ignore: cast_nullable_to_non_nullable - as bool?, - childProcess: freezed == childProcess - ? _self.childProcess - : childProcess // ignore: cast_nullable_to_non_nullable - as bool?, - console: freezed == console - ? _self.console - : console // ignore: cast_nullable_to_non_nullable - as bool?, - crypto: freezed == crypto - ? _self.crypto - : crypto // ignore: cast_nullable_to_non_nullable - as bool?, - dns: freezed == dns - ? _self.dns - : dns // ignore: cast_nullable_to_non_nullable - as bool?, - events: freezed == events - ? _self.events - : events // ignore: cast_nullable_to_non_nullable - as bool?, - exceptions: freezed == exceptions - ? _self.exceptions - : exceptions // ignore: cast_nullable_to_non_nullable - as bool?, - fetch: freezed == fetch - ? _self.fetch - : fetch // ignore: cast_nullable_to_non_nullable - as bool?, - fs: freezed == fs - ? _self.fs - : fs // ignore: cast_nullable_to_non_nullable - as bool?, - navigator: freezed == navigator - ? _self.navigator - : navigator // ignore: cast_nullable_to_non_nullable - as bool?, - net: freezed == net - ? _self.net - : net // ignore: cast_nullable_to_non_nullable - as bool?, - os: freezed == os - ? _self.os - : os // ignore: cast_nullable_to_non_nullable - as bool?, - path: freezed == path - ? _self.path - : path // ignore: cast_nullable_to_non_nullable - as bool?, - perfHooks: freezed == perfHooks - ? _self.perfHooks - : perfHooks // ignore: cast_nullable_to_non_nullable - as bool?, - process: freezed == process - ? _self.process - : process // ignore: cast_nullable_to_non_nullable - as bool?, - streamWeb: freezed == streamWeb - ? _self.streamWeb - : streamWeb // ignore: cast_nullable_to_non_nullable - as bool?, - stringDecoder: freezed == stringDecoder - ? _self.stringDecoder - : stringDecoder // ignore: cast_nullable_to_non_nullable - as bool?, - timers: freezed == timers - ? _self.timers - : timers // ignore: cast_nullable_to_non_nullable - as bool?, - tty: freezed == tty - ? _self.tty - : tty // ignore: cast_nullable_to_non_nullable - as bool?, - url: freezed == url - ? _self.url - : url // ignore: cast_nullable_to_non_nullable - as bool?, - util: freezed == util - ? _self.util - : util // ignore: cast_nullable_to_non_nullable - as bool?, - zlib: freezed == zlib - ? _self.zlib - : zlib // ignore: cast_nullable_to_non_nullable - as bool?, - json: freezed == json - ? _self.json - : json // ignore: cast_nullable_to_non_nullable - as bool?, - )); - } -} - -/// @nodoc -mixin _$JsCallback { - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is JsCallback); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - String toString() { - return 'JsCallback()'; - } -} - -/// @nodoc -class $JsCallbackCopyWith<$Res> { - $JsCallbackCopyWith(JsCallback _, $Res Function(JsCallback) __); -} - -/// Adds pattern-matching-related methods to [JsCallback]. -extension JsCallbackPatterns on JsCallback { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsCallback_Initialized value)? initialized, - TResult Function(JsCallback_Handler value)? handler, - TResult Function(JsCallback_Bridge value)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized() when initialized != null: - return initialized(_that); - case JsCallback_Handler() when handler != null: - return handler(_that); - case JsCallback_Bridge() when bridge != null: - return bridge(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsCallback_Initialized value) initialized, - required TResult Function(JsCallback_Handler value) handler, - required TResult Function(JsCallback_Bridge value) bridge, - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized(): - return initialized(_that); - case JsCallback_Handler(): - return handler(_that); - case JsCallback_Bridge(): - return bridge(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsCallback_Initialized value)? initialized, - TResult? Function(JsCallback_Handler value)? handler, - TResult? Function(JsCallback_Bridge value)? bridge, - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized() when initialized != null: - return initialized(_that); - case JsCallback_Handler() when handler != null: - return handler(_that); - case JsCallback_Bridge() when bridge != null: - return bridge(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function()? initialized, - TResult Function(JsActionResult field0)? handler, - TResult Function(JsValue field0)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized() when initialized != null: - return initialized(); - case JsCallback_Handler() when handler != null: - return handler(_that.field0); - case JsCallback_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function() initialized, - required TResult Function(JsActionResult field0) handler, - required TResult Function(JsValue field0) bridge, - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized(): - return initialized(); - case JsCallback_Handler(): - return handler(_that.field0); - case JsCallback_Bridge(): - return bridge(_that.field0); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function()? initialized, - TResult? Function(JsActionResult field0)? handler, - TResult? Function(JsValue field0)? bridge, - }) { - final _that = this; - switch (_that) { - case JsCallback_Initialized() when initialized != null: - return initialized(); - case JsCallback_Handler() when handler != null: - return handler(_that.field0); - case JsCallback_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return null; - } - } -} - -/// @nodoc - -class JsCallback_Initialized extends JsCallback { - const JsCallback_Initialized() : super._(); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is JsCallback_Initialized); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - String toString() { - return 'JsCallback.initialized()'; - } -} - -/// @nodoc - -class JsCallback_Handler extends JsCallback { - const JsCallback_Handler(this.field0) : super._(); - - final JsActionResult field0; - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCallback_HandlerCopyWith get copyWith => - _$JsCallback_HandlerCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCallback_Handler && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsCallback.handler(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCallback_HandlerCopyWith<$Res> - implements $JsCallbackCopyWith<$Res> { - factory $JsCallback_HandlerCopyWith( - JsCallback_Handler value, $Res Function(JsCallback_Handler) _then) = - _$JsCallback_HandlerCopyWithImpl; - @useResult - $Res call({JsActionResult field0}); - - $JsActionResultCopyWith<$Res> get field0; -} - -/// @nodoc -class _$JsCallback_HandlerCopyWithImpl<$Res> - implements $JsCallback_HandlerCopyWith<$Res> { - _$JsCallback_HandlerCopyWithImpl(this._self, this._then); - - final JsCallback_Handler _self; - final $Res Function(JsCallback_Handler) _then; - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCallback_Handler( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as JsActionResult, - )); - } - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsActionResultCopyWith<$Res> get field0 { - return $JsActionResultCopyWith<$Res>(_self.field0, (value) { - return _then(_self.copyWith(field0: value)); - }); - } -} - -/// @nodoc - -class JsCallback_Bridge extends JsCallback { - const JsCallback_Bridge(this.field0) : super._(); - - final JsValue field0; - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCallback_BridgeCopyWith get copyWith => - _$JsCallback_BridgeCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCallback_Bridge && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsCallback.bridge(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCallback_BridgeCopyWith<$Res> - implements $JsCallbackCopyWith<$Res> { - factory $JsCallback_BridgeCopyWith( - JsCallback_Bridge value, $Res Function(JsCallback_Bridge) _then) = - _$JsCallback_BridgeCopyWithImpl; - @useResult - $Res call({JsValue field0}); - - $JsValueCopyWith<$Res> get field0; -} - -/// @nodoc -class _$JsCallback_BridgeCopyWithImpl<$Res> - implements $JsCallback_BridgeCopyWith<$Res> { - _$JsCallback_BridgeCopyWithImpl(this._self, this._then); - - final JsCallback_Bridge _self; - final $Res Function(JsCallback_Bridge) _then; - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCallback_Bridge( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as JsValue, - )); - } - - /// Create a copy of JsCallback - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsValueCopyWith<$Res> get field0 { - return $JsValueCopyWith<$Res>(_self.field0, (value) { - return _then(_self.copyWith(field0: value)); - }); - } -} - -/// @nodoc -mixin _$JsCallbackResult { - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is JsCallbackResult); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - String toString() { - return 'JsCallbackResult()'; - } -} - -/// @nodoc -class $JsCallbackResultCopyWith<$Res> { - $JsCallbackResultCopyWith( - JsCallbackResult _, $Res Function(JsCallbackResult) __); -} - -/// Adds pattern-matching-related methods to [JsCallbackResult]. -extension JsCallbackResultPatterns on JsCallbackResult { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsCallbackResult_Initialized value)? initialized, - TResult Function(JsCallbackResult_Handler value)? handler, - TResult Function(JsCallbackResult_Bridge value)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized() when initialized != null: - return initialized(_that); - case JsCallbackResult_Handler() when handler != null: - return handler(_that); - case JsCallbackResult_Bridge() when bridge != null: - return bridge(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsCallbackResult_Initialized value) initialized, - required TResult Function(JsCallbackResult_Handler value) handler, - required TResult Function(JsCallbackResult_Bridge value) bridge, - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized(): - return initialized(_that); - case JsCallbackResult_Handler(): - return handler(_that); - case JsCallbackResult_Bridge(): - return bridge(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsCallbackResult_Initialized value)? initialized, - TResult? Function(JsCallbackResult_Handler value)? handler, - TResult? Function(JsCallbackResult_Bridge value)? bridge, - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized() when initialized != null: - return initialized(_that); - case JsCallbackResult_Handler() when handler != null: - return handler(_that); - case JsCallbackResult_Bridge() when bridge != null: - return bridge(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function()? initialized, - TResult Function()? handler, - TResult Function(JsResult field0)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized() when initialized != null: - return initialized(); - case JsCallbackResult_Handler() when handler != null: - return handler(); - case JsCallbackResult_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function() initialized, - required TResult Function() handler, - required TResult Function(JsResult field0) bridge, - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized(): - return initialized(); - case JsCallbackResult_Handler(): - return handler(); - case JsCallbackResult_Bridge(): - return bridge(_that.field0); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function()? initialized, - TResult? Function()? handler, - TResult? Function(JsResult field0)? bridge, - }) { - final _that = this; - switch (_that) { - case JsCallbackResult_Initialized() when initialized != null: - return initialized(); - case JsCallbackResult_Handler() when handler != null: - return handler(); - case JsCallbackResult_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return null; - } - } -} - -/// @nodoc - -class JsCallbackResult_Initialized extends JsCallbackResult { - const JsCallbackResult_Initialized() : super._(); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCallbackResult_Initialized); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - String toString() { - return 'JsCallbackResult.initialized()'; - } -} - -/// @nodoc - -class JsCallbackResult_Handler extends JsCallbackResult { - const JsCallbackResult_Handler() : super._(); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is JsCallbackResult_Handler); - } - - @override - int get hashCode => runtimeType.hashCode; - - @override - String toString() { - return 'JsCallbackResult.handler()'; - } -} - -/// @nodoc - -class JsCallbackResult_Bridge extends JsCallbackResult { - const JsCallbackResult_Bridge(this.field0) : super._(); - - final JsResult field0; - - /// Create a copy of JsCallbackResult - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCallbackResult_BridgeCopyWith get copyWith => - _$JsCallbackResult_BridgeCopyWithImpl( - this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCallbackResult_Bridge && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsCallbackResult.bridge(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCallbackResult_BridgeCopyWith<$Res> - implements $JsCallbackResultCopyWith<$Res> { - factory $JsCallbackResult_BridgeCopyWith(JsCallbackResult_Bridge value, - $Res Function(JsCallbackResult_Bridge) _then) = - _$JsCallbackResult_BridgeCopyWithImpl; - @useResult - $Res call({JsResult field0}); - - $JsResultCopyWith<$Res> get field0; -} - -/// @nodoc -class _$JsCallbackResult_BridgeCopyWithImpl<$Res> - implements $JsCallbackResult_BridgeCopyWith<$Res> { - _$JsCallbackResult_BridgeCopyWithImpl(this._self, this._then); - - final JsCallbackResult_Bridge _self; - final $Res Function(JsCallbackResult_Bridge) _then; - - /// Create a copy of JsCallbackResult - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCallbackResult_Bridge( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as JsResult, - )); - } - - /// Create a copy of JsCallbackResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsResultCopyWith<$Res> get field0 { - return $JsResultCopyWith<$Res>(_self.field0, (value) { - return _then(_self.copyWith(field0: value)); - }); - } -} - -/// @nodoc -mixin _$JsCode { - Object get field0; - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCode && - const DeepCollectionEquality().equals(other.field0, field0)); - } - - @override - int get hashCode => - Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); - - @override - String toString() { - return 'JsCode(field0: $field0)'; - } -} - -/// @nodoc -class $JsCodeCopyWith<$Res> { - $JsCodeCopyWith(JsCode _, $Res Function(JsCode) __); -} - -/// Adds pattern-matching-related methods to [JsCode]. -extension JsCodePatterns on JsCode { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsCode_Code value)? code, - TResult Function(JsCode_Path value)? path, - TResult Function(JsCode_Bytes value)? bytes, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCode_Code() when code != null: - return code(_that); - case JsCode_Path() when path != null: - return path(_that); - case JsCode_Bytes() when bytes != null: - return bytes(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsCode_Code value) code, - required TResult Function(JsCode_Path value) path, - required TResult Function(JsCode_Bytes value) bytes, - }) { - final _that = this; - switch (_that) { - case JsCode_Code(): - return code(_that); - case JsCode_Path(): - return path(_that); - case JsCode_Bytes(): - return bytes(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsCode_Code value)? code, - TResult? Function(JsCode_Path value)? path, - TResult? Function(JsCode_Bytes value)? bytes, - }) { - final _that = this; - switch (_that) { - case JsCode_Code() when code != null: - return code(_that); - case JsCode_Path() when path != null: - return path(_that); - case JsCode_Bytes() when bytes != null: - return bytes(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(String field0)? code, - TResult Function(String field0)? path, - TResult Function(Uint8List field0)? bytes, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsCode_Code() when code != null: - return code(_that.field0); - case JsCode_Path() when path != null: - return path(_that.field0); - case JsCode_Bytes() when bytes != null: - return bytes(_that.field0); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function(String field0) code, - required TResult Function(String field0) path, - required TResult Function(Uint8List field0) bytes, - }) { - final _that = this; - switch (_that) { - case JsCode_Code(): - return code(_that.field0); - case JsCode_Path(): - return path(_that.field0); - case JsCode_Bytes(): - return bytes(_that.field0); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(String field0)? code, - TResult? Function(String field0)? path, - TResult? Function(Uint8List field0)? bytes, - }) { - final _that = this; - switch (_that) { - case JsCode_Code() when code != null: - return code(_that.field0); - case JsCode_Path() when path != null: - return path(_that.field0); - case JsCode_Bytes() when bytes != null: - return bytes(_that.field0); - case _: - return null; - } - } -} - -/// @nodoc - -class JsCode_Code extends JsCode { - const JsCode_Code(this.field0) : super._(); - - @override - final String field0; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCode_CodeCopyWith get copyWith => - _$JsCode_CodeCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCode_Code && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsCode.code(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCode_CodeCopyWith<$Res> - implements $JsCodeCopyWith<$Res> { - factory $JsCode_CodeCopyWith( - JsCode_Code value, $Res Function(JsCode_Code) _then) = - _$JsCode_CodeCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsCode_CodeCopyWithImpl<$Res> implements $JsCode_CodeCopyWith<$Res> { - _$JsCode_CodeCopyWithImpl(this._self, this._then); - - final JsCode_Code _self; - final $Res Function(JsCode_Code) _then; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCode_Code( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsCode_Path extends JsCode { - const JsCode_Path(this.field0) : super._(); - - @override - final String field0; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCode_PathCopyWith get copyWith => - _$JsCode_PathCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCode_Path && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsCode.path(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCode_PathCopyWith<$Res> - implements $JsCodeCopyWith<$Res> { - factory $JsCode_PathCopyWith( - JsCode_Path value, $Res Function(JsCode_Path) _then) = - _$JsCode_PathCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsCode_PathCopyWithImpl<$Res> implements $JsCode_PathCopyWith<$Res> { - _$JsCode_PathCopyWithImpl(this._self, this._then); - - final JsCode_Path _self; - final $Res Function(JsCode_Path) _then; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCode_Path( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsCode_Bytes extends JsCode { - const JsCode_Bytes(this.field0) : super._(); - - @override - final Uint8List field0; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsCode_BytesCopyWith get copyWith => - _$JsCode_BytesCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsCode_Bytes && - const DeepCollectionEquality().equals(other.field0, field0)); - } - - @override - int get hashCode => - Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); - - @override - String toString() { - return 'JsCode.bytes(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsCode_BytesCopyWith<$Res> - implements $JsCodeCopyWith<$Res> { - factory $JsCode_BytesCopyWith( - JsCode_Bytes value, $Res Function(JsCode_Bytes) _then) = - _$JsCode_BytesCopyWithImpl; - @useResult - $Res call({Uint8List field0}); -} - -/// @nodoc -class _$JsCode_BytesCopyWithImpl<$Res> implements $JsCode_BytesCopyWith<$Res> { - _$JsCode_BytesCopyWithImpl(this._self, this._then); - - final JsCode_Bytes _self; - final $Res Function(JsCode_Bytes) _then; - - /// Create a copy of JsCode - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsCode_Bytes( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as Uint8List, - )); - } -} - -/// @nodoc -mixin _$JsError { - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && other is JsError); - } - - @override - int get hashCode => runtimeType.hashCode; -} - -/// @nodoc -class $JsErrorCopyWith<$Res> { - $JsErrorCopyWith(JsError _, $Res Function(JsError) __); -} - -/// Adds pattern-matching-related methods to [JsError]. -extension JsErrorPatterns on JsError { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsError_Promise value)? promise, - TResult Function(JsError_Module value)? module, - TResult Function(JsError_Context value)? context, - TResult Function(JsError_Storage value)? storage, - TResult Function(JsError_Io value)? io, - TResult Function(JsError_Runtime value)? runtime, - TResult Function(JsError_Generic value)? generic, - TResult Function(JsError_Engine value)? engine, - TResult Function(JsError_Bridge value)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsError_Promise() when promise != null: - return promise(_that); - case JsError_Module() when module != null: - return module(_that); - case JsError_Context() when context != null: - return context(_that); - case JsError_Storage() when storage != null: - return storage(_that); - case JsError_Io() when io != null: - return io(_that); - case JsError_Runtime() when runtime != null: - return runtime(_that); - case JsError_Generic() when generic != null: - return generic(_that); - case JsError_Engine() when engine != null: - return engine(_that); - case JsError_Bridge() when bridge != null: - return bridge(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsError_Promise value) promise, - required TResult Function(JsError_Module value) module, - required TResult Function(JsError_Context value) context, - required TResult Function(JsError_Storage value) storage, - required TResult Function(JsError_Io value) io, - required TResult Function(JsError_Runtime value) runtime, - required TResult Function(JsError_Generic value) generic, - required TResult Function(JsError_Engine value) engine, - required TResult Function(JsError_Bridge value) bridge, - }) { - final _that = this; - switch (_that) { - case JsError_Promise(): - return promise(_that); - case JsError_Module(): - return module(_that); - case JsError_Context(): - return context(_that); - case JsError_Storage(): - return storage(_that); - case JsError_Io(): - return io(_that); - case JsError_Runtime(): - return runtime(_that); - case JsError_Generic(): - return generic(_that); - case JsError_Engine(): - return engine(_that); - case JsError_Bridge(): - return bridge(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsError_Promise value)? promise, - TResult? Function(JsError_Module value)? module, - TResult? Function(JsError_Context value)? context, - TResult? Function(JsError_Storage value)? storage, - TResult? Function(JsError_Io value)? io, - TResult? Function(JsError_Runtime value)? runtime, - TResult? Function(JsError_Generic value)? generic, - TResult? Function(JsError_Engine value)? engine, - TResult? Function(JsError_Bridge value)? bridge, - }) { - final _that = this; - switch (_that) { - case JsError_Promise() when promise != null: - return promise(_that); - case JsError_Module() when module != null: - return module(_that); - case JsError_Context() when context != null: - return context(_that); - case JsError_Storage() when storage != null: - return storage(_that); - case JsError_Io() when io != null: - return io(_that); - case JsError_Runtime() when runtime != null: - return runtime(_that); - case JsError_Generic() when generic != null: - return generic(_that); - case JsError_Engine() when engine != null: - return engine(_that); - case JsError_Bridge() when bridge != null: - return bridge(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(String field0)? promise, - TResult Function(String? module, String? method, String message)? module, - TResult Function(String field0)? context, - TResult Function(String field0)? storage, - TResult Function(String? path, String message)? io, - TResult Function(String field0)? runtime, - TResult Function(String field0)? generic, - TResult Function(String field0)? engine, - TResult Function(String field0)? bridge, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsError_Promise() when promise != null: - return promise(_that.field0); - case JsError_Module() when module != null: - return module(_that.module, _that.method, _that.message); - case JsError_Context() when context != null: - return context(_that.field0); - case JsError_Storage() when storage != null: - return storage(_that.field0); - case JsError_Io() when io != null: - return io(_that.path, _that.message); - case JsError_Runtime() when runtime != null: - return runtime(_that.field0); - case JsError_Generic() when generic != null: - return generic(_that.field0); - case JsError_Engine() when engine != null: - return engine(_that.field0); - case JsError_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function(String field0) promise, - required TResult Function(String? module, String? method, String message) - module, - required TResult Function(String field0) context, - required TResult Function(String field0) storage, - required TResult Function(String? path, String message) io, - required TResult Function(String field0) runtime, - required TResult Function(String field0) generic, - required TResult Function(String field0) engine, - required TResult Function(String field0) bridge, - }) { - final _that = this; - switch (_that) { - case JsError_Promise(): - return promise(_that.field0); - case JsError_Module(): - return module(_that.module, _that.method, _that.message); - case JsError_Context(): - return context(_that.field0); - case JsError_Storage(): - return storage(_that.field0); - case JsError_Io(): - return io(_that.path, _that.message); - case JsError_Runtime(): - return runtime(_that.field0); - case JsError_Generic(): - return generic(_that.field0); - case JsError_Engine(): - return engine(_that.field0); - case JsError_Bridge(): - return bridge(_that.field0); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(String field0)? promise, - TResult? Function(String? module, String? method, String message)? module, - TResult? Function(String field0)? context, - TResult? Function(String field0)? storage, - TResult? Function(String? path, String message)? io, - TResult? Function(String field0)? runtime, - TResult? Function(String field0)? generic, - TResult? Function(String field0)? engine, - TResult? Function(String field0)? bridge, - }) { - final _that = this; - switch (_that) { - case JsError_Promise() when promise != null: - return promise(_that.field0); - case JsError_Module() when module != null: - return module(_that.module, _that.method, _that.message); - case JsError_Context() when context != null: - return context(_that.field0); - case JsError_Storage() when storage != null: - return storage(_that.field0); - case JsError_Io() when io != null: - return io(_that.path, _that.message); - case JsError_Runtime() when runtime != null: - return runtime(_that.field0); - case JsError_Generic() when generic != null: - return generic(_that.field0); - case JsError_Engine() when engine != null: - return engine(_that.field0); - case JsError_Bridge() when bridge != null: - return bridge(_that.field0); - case _: - return null; - } - } -} - -/// @nodoc - -class JsError_Promise extends JsError { - const JsError_Promise(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_PromiseCopyWith get copyWith => - _$JsError_PromiseCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Promise && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_PromiseCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_PromiseCopyWith( - JsError_Promise value, $Res Function(JsError_Promise) _then) = - _$JsError_PromiseCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_PromiseCopyWithImpl<$Res> - implements $JsError_PromiseCopyWith<$Res> { - _$JsError_PromiseCopyWithImpl(this._self, this._then); - - final JsError_Promise _self; - final $Res Function(JsError_Promise) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Promise( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Module extends JsError { - const JsError_Module({this.module, this.method, required this.message}) - : super._(); - - /// Optional module name where the error occurred - final String? module; - - /// Optional method name where the error occurred - final String? method; - - /// Error message - final String message; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_ModuleCopyWith get copyWith => - _$JsError_ModuleCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Module && - (identical(other.module, module) || other.module == module) && - (identical(other.method, method) || other.method == method) && - (identical(other.message, message) || other.message == message)); - } - - @override - int get hashCode => Object.hash(runtimeType, module, method, message); -} - -/// @nodoc -abstract mixin class $JsError_ModuleCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_ModuleCopyWith( - JsError_Module value, $Res Function(JsError_Module) _then) = - _$JsError_ModuleCopyWithImpl; - @useResult - $Res call({String? module, String? method, String message}); -} - -/// @nodoc -class _$JsError_ModuleCopyWithImpl<$Res> - implements $JsError_ModuleCopyWith<$Res> { - _$JsError_ModuleCopyWithImpl(this._self, this._then); - - final JsError_Module _self; - final $Res Function(JsError_Module) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? module = freezed, - Object? method = freezed, - Object? message = null, - }) { - return _then(JsError_Module( - module: freezed == module - ? _self.module - : module // ignore: cast_nullable_to_non_nullable - as String?, - method: freezed == method - ? _self.method - : method // ignore: cast_nullable_to_non_nullable - as String?, - message: null == message - ? _self.message - : message // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Context extends JsError { - const JsError_Context(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_ContextCopyWith get copyWith => - _$JsError_ContextCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Context && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_ContextCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_ContextCopyWith( - JsError_Context value, $Res Function(JsError_Context) _then) = - _$JsError_ContextCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_ContextCopyWithImpl<$Res> - implements $JsError_ContextCopyWith<$Res> { - _$JsError_ContextCopyWithImpl(this._self, this._then); - - final JsError_Context _self; - final $Res Function(JsError_Context) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Context( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Storage extends JsError { - const JsError_Storage(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_StorageCopyWith get copyWith => - _$JsError_StorageCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Storage && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_StorageCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_StorageCopyWith( - JsError_Storage value, $Res Function(JsError_Storage) _then) = - _$JsError_StorageCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_StorageCopyWithImpl<$Res> - implements $JsError_StorageCopyWith<$Res> { - _$JsError_StorageCopyWithImpl(this._self, this._then); - - final JsError_Storage _self; - final $Res Function(JsError_Storage) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Storage( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Io extends JsError { - const JsError_Io({this.path, required this.message}) : super._(); - - /// Optional file path where the error occurred - final String? path; - - /// Error message - final String message; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_IoCopyWith get copyWith => - _$JsError_IoCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Io && - (identical(other.path, path) || other.path == path) && - (identical(other.message, message) || other.message == message)); - } - - @override - int get hashCode => Object.hash(runtimeType, path, message); -} - -/// @nodoc -abstract mixin class $JsError_IoCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_IoCopyWith( - JsError_Io value, $Res Function(JsError_Io) _then) = - _$JsError_IoCopyWithImpl; - @useResult - $Res call({String? path, String message}); -} - -/// @nodoc -class _$JsError_IoCopyWithImpl<$Res> implements $JsError_IoCopyWith<$Res> { - _$JsError_IoCopyWithImpl(this._self, this._then); - - final JsError_Io _self; - final $Res Function(JsError_Io) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? path = freezed, - Object? message = null, - }) { - return _then(JsError_Io( - path: freezed == path - ? _self.path - : path // ignore: cast_nullable_to_non_nullable - as String?, - message: null == message - ? _self.message - : message // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Runtime extends JsError { - const JsError_Runtime(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_RuntimeCopyWith get copyWith => - _$JsError_RuntimeCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Runtime && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_RuntimeCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_RuntimeCopyWith( - JsError_Runtime value, $Res Function(JsError_Runtime) _then) = - _$JsError_RuntimeCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_RuntimeCopyWithImpl<$Res> - implements $JsError_RuntimeCopyWith<$Res> { - _$JsError_RuntimeCopyWithImpl(this._self, this._then); - - final JsError_Runtime _self; - final $Res Function(JsError_Runtime) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Runtime( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Generic extends JsError { - const JsError_Generic(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_GenericCopyWith get copyWith => - _$JsError_GenericCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Generic && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_GenericCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_GenericCopyWith( - JsError_Generic value, $Res Function(JsError_Generic) _then) = - _$JsError_GenericCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_GenericCopyWithImpl<$Res> - implements $JsError_GenericCopyWith<$Res> { - _$JsError_GenericCopyWithImpl(this._self, this._then); - - final JsError_Generic _self; - final $Res Function(JsError_Generic) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Generic( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Engine extends JsError { - const JsError_Engine(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_EngineCopyWith get copyWith => - _$JsError_EngineCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Engine && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_EngineCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_EngineCopyWith( - JsError_Engine value, $Res Function(JsError_Engine) _then) = - _$JsError_EngineCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_EngineCopyWithImpl<$Res> - implements $JsError_EngineCopyWith<$Res> { - _$JsError_EngineCopyWithImpl(this._self, this._then); - - final JsError_Engine _self; - final $Res Function(JsError_Engine) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Engine( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc - -class JsError_Bridge extends JsError { - const JsError_Bridge(this.field0) : super._(); - - final String field0; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsError_BridgeCopyWith get copyWith => - _$JsError_BridgeCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsError_Bridge && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); -} - -/// @nodoc -abstract mixin class $JsError_BridgeCopyWith<$Res> - implements $JsErrorCopyWith<$Res> { - factory $JsError_BridgeCopyWith( - JsError_Bridge value, $Res Function(JsError_Bridge) _then) = - _$JsError_BridgeCopyWithImpl; - @useResult - $Res call({String field0}); -} - -/// @nodoc -class _$JsError_BridgeCopyWithImpl<$Res> - implements $JsError_BridgeCopyWith<$Res> { - _$JsError_BridgeCopyWithImpl(this._self, this._then); - - final JsError_Bridge _self; - final $Res Function(JsError_Bridge) _then; - - /// Create a copy of JsError - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsError_Bridge( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as String, - )); - } -} - -/// @nodoc -mixin _$JsEvalOptions { - bool? get global; - bool? get strict; - bool? get backtraceBarrier; - bool? get promise; - - /// Create a copy of JsEvalOptions - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsEvalOptionsCopyWith get copyWith => - _$JsEvalOptionsCopyWithImpl( - this as JsEvalOptions, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsEvalOptions && - (identical(other.global, global) || other.global == global) && - (identical(other.strict, strict) || other.strict == strict) && - (identical(other.backtraceBarrier, backtraceBarrier) || - other.backtraceBarrier == backtraceBarrier) && - (identical(other.promise, promise) || other.promise == promise)); - } - - @override - int get hashCode => - Object.hash(runtimeType, global, strict, backtraceBarrier, promise); - - @override - String toString() { - return 'JsEvalOptions(global: $global, strict: $strict, backtraceBarrier: $backtraceBarrier, promise: $promise)'; - } -} - -/// @nodoc -abstract mixin class $JsEvalOptionsCopyWith<$Res> { - factory $JsEvalOptionsCopyWith( - JsEvalOptions value, $Res Function(JsEvalOptions) _then) = - _$JsEvalOptionsCopyWithImpl; - @useResult - $Res call( - {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}); -} - -/// @nodoc -class _$JsEvalOptionsCopyWithImpl<$Res> - implements $JsEvalOptionsCopyWith<$Res> { - _$JsEvalOptionsCopyWithImpl(this._self, this._then); - - final JsEvalOptions _self; - final $Res Function(JsEvalOptions) _then; - - /// Create a copy of JsEvalOptions - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? global = freezed, - Object? strict = freezed, - Object? backtraceBarrier = freezed, - Object? promise = freezed, - }) { - return _then(_self.copyWith( - global: freezed == global - ? _self.global - : global // ignore: cast_nullable_to_non_nullable - as bool?, - strict: freezed == strict - ? _self.strict - : strict // ignore: cast_nullable_to_non_nullable - as bool?, - backtraceBarrier: freezed == backtraceBarrier - ? _self.backtraceBarrier - : backtraceBarrier // ignore: cast_nullable_to_non_nullable - as bool?, - promise: freezed == promise - ? _self.promise - : promise // ignore: cast_nullable_to_non_nullable - as bool?, - )); - } -} - -/// Adds pattern-matching-related methods to [JsEvalOptions]. -extension JsEvalOptionsPatterns on JsEvalOptions { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(_JsEvalOptions value)? raw, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions() when raw != null: - return raw(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(_JsEvalOptions value) raw, - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions(): - return raw(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(_JsEvalOptions value)? raw, - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions() when raw != null: - return raw(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function( - bool? global, bool? strict, bool? backtraceBarrier, bool? promise)? - raw, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions() when raw != null: - return raw( - _that.global, _that.strict, _that.backtraceBarrier, _that.promise); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function( - bool? global, bool? strict, bool? backtraceBarrier, bool? promise) - raw, - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions(): - return raw( - _that.global, _that.strict, _that.backtraceBarrier, _that.promise); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function( - bool? global, bool? strict, bool? backtraceBarrier, bool? promise)? - raw, - }) { - final _that = this; - switch (_that) { - case _JsEvalOptions() when raw != null: - return raw( - _that.global, _that.strict, _that.backtraceBarrier, _that.promise); - case _: - return null; - } - } -} - -/// @nodoc - -class _JsEvalOptions extends JsEvalOptions { - const _JsEvalOptions( - {this.global, this.strict, this.backtraceBarrier, this.promise}) - : super._(); - - @override - final bool? global; - @override - final bool? strict; - @override - final bool? backtraceBarrier; - @override - final bool? promise; - - /// Create a copy of JsEvalOptions - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - _$JsEvalOptionsCopyWith<_JsEvalOptions> get copyWith => - __$JsEvalOptionsCopyWithImpl<_JsEvalOptions>(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _JsEvalOptions && - (identical(other.global, global) || other.global == global) && - (identical(other.strict, strict) || other.strict == strict) && - (identical(other.backtraceBarrier, backtraceBarrier) || - other.backtraceBarrier == backtraceBarrier) && - (identical(other.promise, promise) || other.promise == promise)); - } - - @override - int get hashCode => - Object.hash(runtimeType, global, strict, backtraceBarrier, promise); - - @override - String toString() { - return 'JsEvalOptions.raw(global: $global, strict: $strict, backtraceBarrier: $backtraceBarrier, promise: $promise)'; - } -} - -/// @nodoc -abstract mixin class _$JsEvalOptionsCopyWith<$Res> - implements $JsEvalOptionsCopyWith<$Res> { - factory _$JsEvalOptionsCopyWith( - _JsEvalOptions value, $Res Function(_JsEvalOptions) _then) = - __$JsEvalOptionsCopyWithImpl; - @override - @useResult - $Res call( - {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}); -} - -/// @nodoc -class __$JsEvalOptionsCopyWithImpl<$Res> - implements _$JsEvalOptionsCopyWith<$Res> { - __$JsEvalOptionsCopyWithImpl(this._self, this._then); - - final _JsEvalOptions _self; - final $Res Function(_JsEvalOptions) _then; - - /// Create a copy of JsEvalOptions - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? global = freezed, - Object? strict = freezed, - Object? backtraceBarrier = freezed, - Object? promise = freezed, - }) { - return _then(_JsEvalOptions( - global: freezed == global - ? _self.global - : global // ignore: cast_nullable_to_non_nullable - as bool?, - strict: freezed == strict - ? _self.strict - : strict // ignore: cast_nullable_to_non_nullable - as bool?, - backtraceBarrier: freezed == backtraceBarrier - ? _self.backtraceBarrier - : backtraceBarrier // ignore: cast_nullable_to_non_nullable - as bool?, - promise: freezed == promise - ? _self.promise - : promise // ignore: cast_nullable_to_non_nullable - as bool?, - )); - } -} - -/// @nodoc -mixin _$JsModule { - String get name; - JsCode get source; - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsModuleCopyWith get copyWith => - _$JsModuleCopyWithImpl(this as JsModule, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsModule && - (identical(other.name, name) || other.name == name) && - (identical(other.source, source) || other.source == source)); - } - - @override - int get hashCode => Object.hash(runtimeType, name, source); - - @override - String toString() { - return 'JsModule(name: $name, source: $source)'; - } -} - -/// @nodoc -abstract mixin class $JsModuleCopyWith<$Res> { - factory $JsModuleCopyWith(JsModule value, $Res Function(JsModule) _then) = - _$JsModuleCopyWithImpl; - @useResult - $Res call({String name, JsCode source}); - - $JsCodeCopyWith<$Res> get source; -} - -/// @nodoc -class _$JsModuleCopyWithImpl<$Res> implements $JsModuleCopyWith<$Res> { - _$JsModuleCopyWithImpl(this._self, this._then); - - final JsModule _self; - final $Res Function(JsModule) _then; - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - @override - $Res call({ - Object? name = null, - Object? source = null, - }) { - return _then(_self.copyWith( - name: null == name - ? _self.name - : name // ignore: cast_nullable_to_non_nullable - as String, - source: null == source - ? _self.source - : source // ignore: cast_nullable_to_non_nullable - as JsCode, - )); - } - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsCodeCopyWith<$Res> get source { - return $JsCodeCopyWith<$Res>(_self.source, (value) { - return _then(_self.copyWith(source: value)); - }); - } -} - -/// Adds pattern-matching-related methods to [JsModule]. -extension JsModulePatterns on JsModule { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(_JsModule value)? raw, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsModule() when raw != null: - return raw(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(_JsModule value) raw, - }) { - final _that = this; - switch (_that) { - case _JsModule(): - return raw(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(_JsModule value)? raw, - }) { - final _that = this; - switch (_that) { - case _JsModule() when raw != null: - return raw(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(String name, JsCode source)? raw, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case _JsModule() when raw != null: - return raw(_that.name, _that.source); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function(String name, JsCode source) raw, - }) { - final _that = this; - switch (_that) { - case _JsModule(): - return raw(_that.name, _that.source); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(String name, JsCode source)? raw, - }) { - final _that = this; - switch (_that) { - case _JsModule() when raw != null: - return raw(_that.name, _that.source); - case _: - return null; - } - } -} - -/// @nodoc - -class _JsModule extends JsModule { - const _JsModule({required this.name, required this.source}) : super._(); - - @override - final String name; - @override - final JsCode source; - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @override - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - _$JsModuleCopyWith<_JsModule> get copyWith => - __$JsModuleCopyWithImpl<_JsModule>(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is _JsModule && - (identical(other.name, name) || other.name == name) && - (identical(other.source, source) || other.source == source)); - } - - @override - int get hashCode => Object.hash(runtimeType, name, source); - - @override - String toString() { - return 'JsModule.raw(name: $name, source: $source)'; - } -} - -/// @nodoc -abstract mixin class _$JsModuleCopyWith<$Res> - implements $JsModuleCopyWith<$Res> { - factory _$JsModuleCopyWith(_JsModule value, $Res Function(_JsModule) _then) = - __$JsModuleCopyWithImpl; - @override - @useResult - $Res call({String name, JsCode source}); - - @override - $JsCodeCopyWith<$Res> get source; -} - -/// @nodoc -class __$JsModuleCopyWithImpl<$Res> implements _$JsModuleCopyWith<$Res> { - __$JsModuleCopyWithImpl(this._self, this._then); - - final _JsModule _self; - final $Res Function(_JsModule) _then; - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $Res call({ - Object? name = null, - Object? source = null, - }) { - return _then(_JsModule( - name: null == name - ? _self.name - : name // ignore: cast_nullable_to_non_nullable - as String, - source: null == source - ? _self.source - : source // ignore: cast_nullable_to_non_nullable - as JsCode, - )); - } - - /// Create a copy of JsModule - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsCodeCopyWith<$Res> get source { - return $JsCodeCopyWith<$Res>(_self.source, (value) { - return _then(_self.copyWith(source: value)); - }); - } -} - -/// @nodoc -mixin _$JsResult { - Object get field0; - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsResult && - const DeepCollectionEquality().equals(other.field0, field0)); - } - - @override - int get hashCode => - Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); - - @override - String toString() { - return 'JsResult(field0: $field0)'; - } -} - -/// @nodoc -class $JsResultCopyWith<$Res> { - $JsResultCopyWith(JsResult _, $Res Function(JsResult) __); -} - -/// Adds pattern-matching-related methods to [JsResult]. -extension JsResultPatterns on JsResult { - /// A variant of `map` that fallback to returning `orElse`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeMap({ - TResult Function(JsResult_Ok value)? ok, - TResult Function(JsResult_Err value)? err, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsResult_Ok() when ok != null: - return ok(_that); - case JsResult_Err() when err != null: - return err(_that); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// Callbacks receives the raw object, upcasted. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case final Subclass2 value: - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult map({ - required TResult Function(JsResult_Ok value) ok, - required TResult Function(JsResult_Err value) err, - }) { - final _that = this; - switch (_that) { - case JsResult_Ok(): - return ok(_that); - case JsResult_Err(): - return err(_that); - } - } - - /// A variant of `map` that fallback to returning `null`. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case final Subclass value: - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? mapOrNull({ - TResult? Function(JsResult_Ok value)? ok, - TResult? Function(JsResult_Err value)? err, - }) { - final _that = this; - switch (_that) { - case JsResult_Ok() when ok != null: - return ok(_that); - case JsResult_Err() when err != null: - return err(_that); - case _: - return null; - } - } - - /// A variant of `when` that fallback to an `orElse` callback. - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return orElse(); - /// } - /// ``` - - @optionalTypeArgs - TResult maybeWhen({ - TResult Function(JsValue field0)? ok, - TResult Function(JsError field0)? err, - required TResult orElse(), - }) { - final _that = this; - switch (_that) { - case JsResult_Ok() when ok != null: - return ok(_that.field0); - case JsResult_Err() when err != null: - return err(_that.field0); - case _: - return orElse(); - } - } - - /// A `switch`-like method, using callbacks. - /// - /// As opposed to `map`, this offers destructuring. - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case Subclass2(:final field2): - /// return ...; - /// } - /// ``` - - @optionalTypeArgs - TResult when({ - required TResult Function(JsValue field0) ok, - required TResult Function(JsError field0) err, - }) { - final _that = this; - switch (_that) { - case JsResult_Ok(): - return ok(_that.field0); - case JsResult_Err(): - return err(_that.field0); - } - } - - /// A variant of `when` that fallback to returning `null` - /// - /// It is equivalent to doing: - /// ```dart - /// switch (sealedClass) { - /// case Subclass(:final field): - /// return ...; - /// case _: - /// return null; - /// } - /// ``` - - @optionalTypeArgs - TResult? whenOrNull({ - TResult? Function(JsValue field0)? ok, - TResult? Function(JsError field0)? err, - }) { - final _that = this; - switch (_that) { - case JsResult_Ok() when ok != null: - return ok(_that.field0); - case JsResult_Err() when err != null: - return err(_that.field0); - case _: - return null; - } - } -} - -/// @nodoc - -class JsResult_Ok extends JsResult { - const JsResult_Ok(this.field0) : super._(); - - @override - final JsValue field0; - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsResult_OkCopyWith get copyWith => - _$JsResult_OkCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsResult_Ok && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsResult.ok(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsResult_OkCopyWith<$Res> - implements $JsResultCopyWith<$Res> { - factory $JsResult_OkCopyWith( - JsResult_Ok value, $Res Function(JsResult_Ok) _then) = - _$JsResult_OkCopyWithImpl; - @useResult - $Res call({JsValue field0}); - - $JsValueCopyWith<$Res> get field0; -} - -/// @nodoc -class _$JsResult_OkCopyWithImpl<$Res> implements $JsResult_OkCopyWith<$Res> { - _$JsResult_OkCopyWithImpl(this._self, this._then); - - final JsResult_Ok _self; - final $Res Function(JsResult_Ok) _then; - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsResult_Ok( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as JsValue, - )); - } - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsValueCopyWith<$Res> get field0 { - return $JsValueCopyWith<$Res>(_self.field0, (value) { - return _then(_self.copyWith(field0: value)); - }); - } -} - -/// @nodoc - -class JsResult_Err extends JsResult { - const JsResult_Err(this.field0) : super._(); - - @override - final JsError field0; - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @JsonKey(includeFromJson: false, includeToJson: false) - @pragma('vm:prefer-inline') - $JsResult_ErrCopyWith get copyWith => - _$JsResult_ErrCopyWithImpl(this, _$identity); - - @override - bool operator ==(Object other) { - return identical(this, other) || - (other.runtimeType == runtimeType && - other is JsResult_Err && - (identical(other.field0, field0) || other.field0 == field0)); - } - - @override - int get hashCode => Object.hash(runtimeType, field0); - - @override - String toString() { - return 'JsResult.err(field0: $field0)'; - } -} - -/// @nodoc -abstract mixin class $JsResult_ErrCopyWith<$Res> - implements $JsResultCopyWith<$Res> { - factory $JsResult_ErrCopyWith( - JsResult_Err value, $Res Function(JsResult_Err) _then) = - _$JsResult_ErrCopyWithImpl; - @useResult - $Res call({JsError field0}); - - $JsErrorCopyWith<$Res> get field0; -} - -/// @nodoc -class _$JsResult_ErrCopyWithImpl<$Res> implements $JsResult_ErrCopyWith<$Res> { - _$JsResult_ErrCopyWithImpl(this._self, this._then); - - final JsResult_Err _self; - final $Res Function(JsResult_Err) _then; - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @pragma('vm:prefer-inline') - $Res call({ - Object? field0 = null, - }) { - return _then(JsResult_Err( - null == field0 - ? _self.field0 - : field0 // ignore: cast_nullable_to_non_nullable - as JsError, - )); - } - - /// Create a copy of JsResult - /// with the given fields replaced by the non-null parameter values. - @override - @pragma('vm:prefer-inline') - $JsErrorCopyWith<$Res> get field0 { - return $JsErrorCopyWith<$Res>(_self.field0, (value) { - return _then(_self.copyWith(field0: value)); - }); - } -} - -// dart format on diff --git a/lib/src/frb/api/runtime.dart b/lib/src/frb/api/runtime.dart new file mode 100644 index 0000000..18bda08 --- /dev/null +++ b/lib/src/frb/api/runtime.dart @@ -0,0 +1,202 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.11.1. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; +import 'error.dart'; +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; +import 'source.dart'; +import 'value.dart'; + +// These functions are ignored because they are not marked as `pub`: `build_loaders`, `result_from_promise`, `result_from_sync` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `clone`, `clone`, `clone`, `clone` + +// Rust type: RustOpaqueMoi> +abstract class JsAsyncContext implements RustOpaqueInterface { + /// Evaluates JavaScript code. + Future eval({required String code}); + + /// Evaluates JavaScript code from a file. + Future evalFile({required String path}); + + /// Evaluates JavaScript code from a file with options. + Future evalFileWithOptions( + {required String path, required JsEvalOptions options}); + + /// Evaluates a function from a module. + Future evalFunction( + {required String module, required String method, List? params}); + + /// Evaluates JavaScript code with options. + Future evalWithOptions( + {required String code, required JsEvalOptions options}); + + /// Creates a new async context from a runtime. + static Future from({required JsAsyncRuntime rt}) => + LibFjs.instance.api.crateApiRuntimeJsAsyncContextFrom(rt: rt); +} + +// Rust type: RustOpaqueMoi> +abstract class JsAsyncRuntime implements RustOpaqueInterface { + /// Executes a pending job. + Future executePendingJob(); + + /// Puts the runtime into idle state. + Future idle(); + + /// Checks if there are pending jobs. + Future isJobPending(); + + /// Returns memory usage statistics. + Future memoryUsage(); + + /// Creates a new async runtime with default configuration. + factory JsAsyncRuntime() => + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeNew(); + + /// Forces garbage collection. + Future runGc(); + + /// Sets the garbage collection threshold. + Future setGcThreshold({required BigInt threshold}); + + /// Sets runtime info string. + Future setInfo({required String info}); + + /// Sets the maximum stack size. + Future setMaxStackSize({required BigInt limit}); + + /// Sets the memory limit. + Future setMemoryLimit({required BigInt limit}); + + /// Creates a new async runtime with custom configuration. + static Future withOptions( + {JsBuiltinOptions? builtin, List? additional}) => + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeWithOptions( + builtin: builtin, additional: additional); +} + +// Rust type: RustOpaqueMoi> +abstract class JsContext implements RustOpaqueInterface { + /// Evaluates JavaScript code. + JsResult eval({required String code}); + + /// Evaluates JavaScript code from a file. + JsResult evalFile({required String path}); + + /// Evaluates JavaScript code from a file with options. + JsResult evalFileWithOptions( + {required String path, required JsEvalOptions options}); + + /// Evaluates JavaScript code with options. + JsResult evalWithOptions( + {required String code, required JsEvalOptions options}); + + /// Creates a new context from a runtime. + factory JsContext({required JsRuntime rt}) => + LibFjs.instance.api.crateApiRuntimeJsContextNew(rt: rt); +} + +// Rust type: RustOpaqueMoi> +abstract class JsRuntime implements RustOpaqueInterface { + /// Executes a pending job. + bool executePendingJob(); + + /// Checks if there are pending jobs. + bool isJobPending(); + + /// Returns memory usage statistics. + MemoryUsage memoryUsage(); + + /// Creates a new JavaScript runtime with default configuration. + factory JsRuntime() => LibFjs.instance.api.crateApiRuntimeJsRuntimeNew(); + + /// Forces garbage collection. + void runGc(); + + /// Sets dump flags for debugging. + void setDumpFlags({required BigInt flags}); + + /// Sets the garbage collection threshold. + void setGcThreshold({required BigInt threshold}); + + /// Sets runtime info string. + void setInfo({required String info}); + + /// Sets the maximum stack size. + void setMaxStackSize({required BigInt limit}); + + /// Sets the memory limit for the runtime. + void setMemoryLimit({required BigInt limit}); + + /// Creates a new JavaScript runtime with custom builtin modules. + static Future withOptions( + {JsBuiltinOptions? builtin, List? additional}) => + LibFjs.instance.api.crateApiRuntimeJsRuntimeWithOptions( + builtin: builtin, additional: additional); +} + +// Rust type: RustOpaqueMoi> +abstract class MemoryUsage implements RustOpaqueInterface { + PlatformInt64 get arrayCount; + + PlatformInt64 get atomCount; + + PlatformInt64 get atomSize; + + PlatformInt64 get binaryObjectCount; + + PlatformInt64 get binaryObjectSize; + + PlatformInt64 get cFuncCount; + + PlatformInt64 get fastArrayCount; + + PlatformInt64 get fastArrayElements; + + PlatformInt64 get jsFuncCodeSize; + + PlatformInt64 get jsFuncCount; + + PlatformInt64 get jsFuncPc2LineCount; + + PlatformInt64 get jsFuncPc2LineSize; + + PlatformInt64 get jsFuncSize; + + PlatformInt64 get mallocCount; + + PlatformInt64 get mallocLimit; + + PlatformInt64 get mallocSize; + + PlatformInt64 get memoryUsedCount; + + PlatformInt64 get memoryUsedSize; + + PlatformInt64 get objCount; + + PlatformInt64 get objSize; + + PlatformInt64 get propCount; + + PlatformInt64 get propSize; + + PlatformInt64 get shapeCount; + + PlatformInt64 get shapeSize; + + PlatformInt64 get strCount; + + PlatformInt64 get strSize; + + /// Returns a human-readable summary of memory usage. + String summary(); + + /// Returns total allocation count. + PlatformInt64 get totalAllocations; + + /// Returns total memory used in bytes. + PlatformInt64 get totalMemory; +} diff --git a/lib/src/frb/api/source.dart b/lib/src/frb/api/source.dart new file mode 100644 index 0000000..4edf6cb --- /dev/null +++ b/lib/src/frb/api/source.dart @@ -0,0 +1,184 @@ +// This file is automatically generated, so please do not edit it. +// @generated by `flutter_rust_bridge`@ 2.11.1. + +// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import + +import '../frb_generated.dart'; +import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; +import 'package:freezed_annotation/freezed_annotation.dart' hide protected; +part 'source.freezed.dart'; + +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_receiver_is_total_eq`, `assert_receiver_is_total_eq`, `clone`, `clone`, `clone`, `clone`, `cmp`, `cmp`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `hash`, `hash`, `partial_cmp`, `partial_cmp` +// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `as_path`, `bytes`, `bytes`, `code`, `code`, `get_raw_source_code_sync`, `get_raw_source_code`, `path`, `path` + +/// Options for configuring builtin Node.js modules. +/// +/// This struct provides fine-grained control over which Node.js +/// compatibility modules should be available in the runtime. +@freezed +sealed class JsBuiltinOptions with _$JsBuiltinOptions { + const JsBuiltinOptions._(); + const factory JsBuiltinOptions({ + bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json, + }) = _JsBuiltinOptions; + + /// Creates builtin options with all modules enabled. + static JsBuiltinOptions all() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsAll(); + + static Future default_() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsDefault(); + + /// Creates builtin options with essential modules only. + /// Includes: console, timers, buffer, util, json + static JsBuiltinOptions essential() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsEssential(); + + /// Creates builtin options for Node.js-like environment. + /// Includes most modules except OS-specific ones. + static JsBuiltinOptions node() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsNode(); + + /// Creates builtin options with no modules enabled. + static JsBuiltinOptions none() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsNone(); + + /// Creates builtin options for web-like environment. + /// Includes: console, timers, fetch, url, crypto, stream_web + static JsBuiltinOptions web() => + LibFjs.instance.api.crateApiSourceJsBuiltinOptionsWeb(); +} + +@freezed +sealed class JsCode with _$JsCode { + const JsCode._(); + + /// Inline JavaScript code as a string + const factory JsCode.code( + String field0, + ) = JsCode_Code; + + /// File path containing JavaScript code + const factory JsCode.path( + String field0, + ) = JsCode_Path; + + /// Raw bytes containing JavaScript code (UTF-8 encoded) + const factory JsCode.bytes( + Uint8List field0, + ) = JsCode_Bytes; + + /// Returns true if this is a Bytes variant. + bool isBytes() => LibFjs.instance.api.crateApiSourceJsCodeIsBytes( + that: this, + ); + + /// Returns true if this is a Code variant. + bool isCode() => LibFjs.instance.api.crateApiSourceJsCodeIsCode( + that: this, + ); + + /// Returns true if this is a Path variant. + bool isPath() => LibFjs.instance.api.crateApiSourceJsCodeIsPath( + that: this, + ); +} + +/// Options for JavaScript code evaluation. +/// +/// This struct provides configuration options for how JavaScript +/// code should be executed and evaluated. +@freezed +sealed class JsEvalOptions with _$JsEvalOptions { + const JsEvalOptions._(); + const factory JsEvalOptions.raw({ + bool? global, + bool? strict, + bool? backtraceBarrier, + bool? promise, + }) = _JsEvalOptions; + static Future default_() => + LibFjs.instance.api.crateApiSourceJsEvalOptionsDefault(); + + /// Creates options with default values (global scope, strict mode). + static JsEvalOptions defaults() => + LibFjs.instance.api.crateApiSourceJsEvalOptionsDefaults(); + + /// Creates options for module evaluation. + static JsEvalOptions module() => + LibFjs.instance.api.crateApiSourceJsEvalOptionsModule(); + + /// Creates new evaluation options with the specified parameters. + factory JsEvalOptions( + {bool? global, + bool? strict, + bool? backtraceBarrier, + bool? promise}) => + LibFjs.instance.api.crateApiSourceJsEvalOptionsNew( + global: global, + strict: strict, + backtraceBarrier: backtraceBarrier, + promise: promise); + + /// Creates options with promise support enabled. + static JsEvalOptions withPromise() => + LibFjs.instance.api.crateApiSourceJsEvalOptionsWithPromise(); +} + +/// Represents a JavaScript module. +/// +/// This struct defines a module with a name and source code, +/// which can be loaded and executed in the JavaScript runtime. +@freezed +sealed class JsModule with _$JsModule { + const JsModule._(); + const factory JsModule.raw({ + required String name, + required JsCode source, + }) = _JsModule; + + /// Creates a module from raw bytes. + static JsModule fromBytes( + {required String module, required List bytes}) => + LibFjs.instance.api + .crateApiSourceJsModuleFromBytes(module: module, bytes: bytes); + + /// Creates a module from inline code string. + static JsModule fromCode({required String module, required String code}) => + LibFjs.instance.api + .crateApiSourceJsModuleFromCode(module: module, code: code); + + /// Creates a module from a file path string. + static JsModule fromPath({required String module, required String path}) => + LibFjs.instance.api + .crateApiSourceJsModuleFromPath(module: module, path: path); + + /// Creates a new module with the given name and source. + factory JsModule({required String name, required JsCode source}) => + LibFjs.instance.api.crateApiSourceJsModuleNew(name: name, source: source); +} diff --git a/lib/src/frb/api/source.freezed.dart b/lib/src/frb/api/source.freezed.dart new file mode 100644 index 0000000..a23a0f0 --- /dev/null +++ b/lib/src/frb/api/source.freezed.dart @@ -0,0 +1,2053 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'source.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$JsBuiltinOptions { + bool? get abort; + bool? get assert_; + bool? get asyncHooks; + bool? get buffer; + bool? get childProcess; + bool? get console; + bool? get crypto; + bool? get dns; + bool? get events; + bool? get exceptions; + bool? get fetch; + bool? get fs; + bool? get navigator; + bool? get net; + bool? get os; + bool? get path; + bool? get perfHooks; + bool? get process; + bool? get streamWeb; + bool? get stringDecoder; + bool? get timers; + bool? get tty; + bool? get url; + bool? get util; + bool? get zlib; + bool? get json; + + /// Create a copy of JsBuiltinOptions + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsBuiltinOptionsCopyWith get copyWith => + _$JsBuiltinOptionsCopyWithImpl( + this as JsBuiltinOptions, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsBuiltinOptions && + (identical(other.abort, abort) || other.abort == abort) && + (identical(other.assert_, assert_) || other.assert_ == assert_) && + (identical(other.asyncHooks, asyncHooks) || + other.asyncHooks == asyncHooks) && + (identical(other.buffer, buffer) || other.buffer == buffer) && + (identical(other.childProcess, childProcess) || + other.childProcess == childProcess) && + (identical(other.console, console) || other.console == console) && + (identical(other.crypto, crypto) || other.crypto == crypto) && + (identical(other.dns, dns) || other.dns == dns) && + (identical(other.events, events) || other.events == events) && + (identical(other.exceptions, exceptions) || + other.exceptions == exceptions) && + (identical(other.fetch, fetch) || other.fetch == fetch) && + (identical(other.fs, fs) || other.fs == fs) && + (identical(other.navigator, navigator) || + other.navigator == navigator) && + (identical(other.net, net) || other.net == net) && + (identical(other.os, os) || other.os == os) && + (identical(other.path, path) || other.path == path) && + (identical(other.perfHooks, perfHooks) || + other.perfHooks == perfHooks) && + (identical(other.process, process) || other.process == process) && + (identical(other.streamWeb, streamWeb) || + other.streamWeb == streamWeb) && + (identical(other.stringDecoder, stringDecoder) || + other.stringDecoder == stringDecoder) && + (identical(other.timers, timers) || other.timers == timers) && + (identical(other.tty, tty) || other.tty == tty) && + (identical(other.url, url) || other.url == url) && + (identical(other.util, util) || other.util == util) && + (identical(other.zlib, zlib) || other.zlib == zlib) && + (identical(other.json, json) || other.json == json)); + } + + @override + int get hashCode => Object.hashAll([ + runtimeType, + abort, + assert_, + asyncHooks, + buffer, + childProcess, + console, + crypto, + dns, + events, + exceptions, + fetch, + fs, + navigator, + net, + os, + path, + perfHooks, + process, + streamWeb, + stringDecoder, + timers, + tty, + url, + util, + zlib, + json + ]); + + @override + String toString() { + return 'JsBuiltinOptions(abort: $abort, assert_: $assert_, asyncHooks: $asyncHooks, buffer: $buffer, childProcess: $childProcess, console: $console, crypto: $crypto, dns: $dns, events: $events, exceptions: $exceptions, fetch: $fetch, fs: $fs, navigator: $navigator, net: $net, os: $os, path: $path, perfHooks: $perfHooks, process: $process, streamWeb: $streamWeb, stringDecoder: $stringDecoder, timers: $timers, tty: $tty, url: $url, util: $util, zlib: $zlib, json: $json)'; + } +} + +/// @nodoc +abstract mixin class $JsBuiltinOptionsCopyWith<$Res> { + factory $JsBuiltinOptionsCopyWith( + JsBuiltinOptions value, $Res Function(JsBuiltinOptions) _then) = + _$JsBuiltinOptionsCopyWithImpl; + @useResult + $Res call( + {bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json}); +} + +/// @nodoc +class _$JsBuiltinOptionsCopyWithImpl<$Res> + implements $JsBuiltinOptionsCopyWith<$Res> { + _$JsBuiltinOptionsCopyWithImpl(this._self, this._then); + + final JsBuiltinOptions _self; + final $Res Function(JsBuiltinOptions) _then; + + /// Create a copy of JsBuiltinOptions + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? abort = freezed, + Object? assert_ = freezed, + Object? asyncHooks = freezed, + Object? buffer = freezed, + Object? childProcess = freezed, + Object? console = freezed, + Object? crypto = freezed, + Object? dns = freezed, + Object? events = freezed, + Object? exceptions = freezed, + Object? fetch = freezed, + Object? fs = freezed, + Object? navigator = freezed, + Object? net = freezed, + Object? os = freezed, + Object? path = freezed, + Object? perfHooks = freezed, + Object? process = freezed, + Object? streamWeb = freezed, + Object? stringDecoder = freezed, + Object? timers = freezed, + Object? tty = freezed, + Object? url = freezed, + Object? util = freezed, + Object? zlib = freezed, + Object? json = freezed, + }) { + return _then(_self.copyWith( + abort: freezed == abort + ? _self.abort + : abort // ignore: cast_nullable_to_non_nullable + as bool?, + assert_: freezed == assert_ + ? _self.assert_ + : assert_ // ignore: cast_nullable_to_non_nullable + as bool?, + asyncHooks: freezed == asyncHooks + ? _self.asyncHooks + : asyncHooks // ignore: cast_nullable_to_non_nullable + as bool?, + buffer: freezed == buffer + ? _self.buffer + : buffer // ignore: cast_nullable_to_non_nullable + as bool?, + childProcess: freezed == childProcess + ? _self.childProcess + : childProcess // ignore: cast_nullable_to_non_nullable + as bool?, + console: freezed == console + ? _self.console + : console // ignore: cast_nullable_to_non_nullable + as bool?, + crypto: freezed == crypto + ? _self.crypto + : crypto // ignore: cast_nullable_to_non_nullable + as bool?, + dns: freezed == dns + ? _self.dns + : dns // ignore: cast_nullable_to_non_nullable + as bool?, + events: freezed == events + ? _self.events + : events // ignore: cast_nullable_to_non_nullable + as bool?, + exceptions: freezed == exceptions + ? _self.exceptions + : exceptions // ignore: cast_nullable_to_non_nullable + as bool?, + fetch: freezed == fetch + ? _self.fetch + : fetch // ignore: cast_nullable_to_non_nullable + as bool?, + fs: freezed == fs + ? _self.fs + : fs // ignore: cast_nullable_to_non_nullable + as bool?, + navigator: freezed == navigator + ? _self.navigator + : navigator // ignore: cast_nullable_to_non_nullable + as bool?, + net: freezed == net + ? _self.net + : net // ignore: cast_nullable_to_non_nullable + as bool?, + os: freezed == os + ? _self.os + : os // ignore: cast_nullable_to_non_nullable + as bool?, + path: freezed == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as bool?, + perfHooks: freezed == perfHooks + ? _self.perfHooks + : perfHooks // ignore: cast_nullable_to_non_nullable + as bool?, + process: freezed == process + ? _self.process + : process // ignore: cast_nullable_to_non_nullable + as bool?, + streamWeb: freezed == streamWeb + ? _self.streamWeb + : streamWeb // ignore: cast_nullable_to_non_nullable + as bool?, + stringDecoder: freezed == stringDecoder + ? _self.stringDecoder + : stringDecoder // ignore: cast_nullable_to_non_nullable + as bool?, + timers: freezed == timers + ? _self.timers + : timers // ignore: cast_nullable_to_non_nullable + as bool?, + tty: freezed == tty + ? _self.tty + : tty // ignore: cast_nullable_to_non_nullable + as bool?, + url: freezed == url + ? _self.url + : url // ignore: cast_nullable_to_non_nullable + as bool?, + util: freezed == util + ? _self.util + : util // ignore: cast_nullable_to_non_nullable + as bool?, + zlib: freezed == zlib + ? _self.zlib + : zlib // ignore: cast_nullable_to_non_nullable + as bool?, + json: freezed == json + ? _self.json + : json // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// Adds pattern-matching-related methods to [JsBuiltinOptions]. +extension JsBuiltinOptionsPatterns on JsBuiltinOptions { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_JsBuiltinOptions value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_JsBuiltinOptions value) $default, + ) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions(): + return $default(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_JsBuiltinOptions value)? $default, + ) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions() when $default != null: + return $default( + _that.abort, + _that.assert_, + _that.asyncHooks, + _that.buffer, + _that.childProcess, + _that.console, + _that.crypto, + _that.dns, + _that.events, + _that.exceptions, + _that.fetch, + _that.fs, + _that.navigator, + _that.net, + _that.os, + _that.path, + _that.perfHooks, + _that.process, + _that.streamWeb, + _that.stringDecoder, + _that.timers, + _that.tty, + _that.url, + _that.util, + _that.zlib, + _that.json); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json) + $default, + ) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions(): + return $default( + _that.abort, + _that.assert_, + _that.asyncHooks, + _that.buffer, + _that.childProcess, + _that.console, + _that.crypto, + _that.dns, + _that.events, + _that.exceptions, + _that.fetch, + _that.fs, + _that.navigator, + _that.net, + _that.os, + _that.path, + _that.perfHooks, + _that.process, + _that.streamWeb, + _that.stringDecoder, + _that.timers, + _that.tty, + _that.url, + _that.util, + _that.zlib, + _that.json); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json)? + $default, + ) { + final _that = this; + switch (_that) { + case _JsBuiltinOptions() when $default != null: + return $default( + _that.abort, + _that.assert_, + _that.asyncHooks, + _that.buffer, + _that.childProcess, + _that.console, + _that.crypto, + _that.dns, + _that.events, + _that.exceptions, + _that.fetch, + _that.fs, + _that.navigator, + _that.net, + _that.os, + _that.path, + _that.perfHooks, + _that.process, + _that.streamWeb, + _that.stringDecoder, + _that.timers, + _that.tty, + _that.url, + _that.util, + _that.zlib, + _that.json); + case _: + return null; + } + } +} + +/// @nodoc + +class _JsBuiltinOptions extends JsBuiltinOptions { + const _JsBuiltinOptions( + {this.abort, + this.assert_, + this.asyncHooks, + this.buffer, + this.childProcess, + this.console, + this.crypto, + this.dns, + this.events, + this.exceptions, + this.fetch, + this.fs, + this.navigator, + this.net, + this.os, + this.path, + this.perfHooks, + this.process, + this.streamWeb, + this.stringDecoder, + this.timers, + this.tty, + this.url, + this.util, + this.zlib, + this.json}) + : super._(); + + @override + final bool? abort; + @override + final bool? assert_; + @override + final bool? asyncHooks; + @override + final bool? buffer; + @override + final bool? childProcess; + @override + final bool? console; + @override + final bool? crypto; + @override + final bool? dns; + @override + final bool? events; + @override + final bool? exceptions; + @override + final bool? fetch; + @override + final bool? fs; + @override + final bool? navigator; + @override + final bool? net; + @override + final bool? os; + @override + final bool? path; + @override + final bool? perfHooks; + @override + final bool? process; + @override + final bool? streamWeb; + @override + final bool? stringDecoder; + @override + final bool? timers; + @override + final bool? tty; + @override + final bool? url; + @override + final bool? util; + @override + final bool? zlib; + @override + final bool? json; + + /// Create a copy of JsBuiltinOptions + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$JsBuiltinOptionsCopyWith<_JsBuiltinOptions> get copyWith => + __$JsBuiltinOptionsCopyWithImpl<_JsBuiltinOptions>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _JsBuiltinOptions && + (identical(other.abort, abort) || other.abort == abort) && + (identical(other.assert_, assert_) || other.assert_ == assert_) && + (identical(other.asyncHooks, asyncHooks) || + other.asyncHooks == asyncHooks) && + (identical(other.buffer, buffer) || other.buffer == buffer) && + (identical(other.childProcess, childProcess) || + other.childProcess == childProcess) && + (identical(other.console, console) || other.console == console) && + (identical(other.crypto, crypto) || other.crypto == crypto) && + (identical(other.dns, dns) || other.dns == dns) && + (identical(other.events, events) || other.events == events) && + (identical(other.exceptions, exceptions) || + other.exceptions == exceptions) && + (identical(other.fetch, fetch) || other.fetch == fetch) && + (identical(other.fs, fs) || other.fs == fs) && + (identical(other.navigator, navigator) || + other.navigator == navigator) && + (identical(other.net, net) || other.net == net) && + (identical(other.os, os) || other.os == os) && + (identical(other.path, path) || other.path == path) && + (identical(other.perfHooks, perfHooks) || + other.perfHooks == perfHooks) && + (identical(other.process, process) || other.process == process) && + (identical(other.streamWeb, streamWeb) || + other.streamWeb == streamWeb) && + (identical(other.stringDecoder, stringDecoder) || + other.stringDecoder == stringDecoder) && + (identical(other.timers, timers) || other.timers == timers) && + (identical(other.tty, tty) || other.tty == tty) && + (identical(other.url, url) || other.url == url) && + (identical(other.util, util) || other.util == util) && + (identical(other.zlib, zlib) || other.zlib == zlib) && + (identical(other.json, json) || other.json == json)); + } + + @override + int get hashCode => Object.hashAll([ + runtimeType, + abort, + assert_, + asyncHooks, + buffer, + childProcess, + console, + crypto, + dns, + events, + exceptions, + fetch, + fs, + navigator, + net, + os, + path, + perfHooks, + process, + streamWeb, + stringDecoder, + timers, + tty, + url, + util, + zlib, + json + ]); + + @override + String toString() { + return 'JsBuiltinOptions(abort: $abort, assert_: $assert_, asyncHooks: $asyncHooks, buffer: $buffer, childProcess: $childProcess, console: $console, crypto: $crypto, dns: $dns, events: $events, exceptions: $exceptions, fetch: $fetch, fs: $fs, navigator: $navigator, net: $net, os: $os, path: $path, perfHooks: $perfHooks, process: $process, streamWeb: $streamWeb, stringDecoder: $stringDecoder, timers: $timers, tty: $tty, url: $url, util: $util, zlib: $zlib, json: $json)'; + } +} + +/// @nodoc +abstract mixin class _$JsBuiltinOptionsCopyWith<$Res> + implements $JsBuiltinOptionsCopyWith<$Res> { + factory _$JsBuiltinOptionsCopyWith( + _JsBuiltinOptions value, $Res Function(_JsBuiltinOptions) _then) = + __$JsBuiltinOptionsCopyWithImpl; + @override + @useResult + $Res call( + {bool? abort, + bool? assert_, + bool? asyncHooks, + bool? buffer, + bool? childProcess, + bool? console, + bool? crypto, + bool? dns, + bool? events, + bool? exceptions, + bool? fetch, + bool? fs, + bool? navigator, + bool? net, + bool? os, + bool? path, + bool? perfHooks, + bool? process, + bool? streamWeb, + bool? stringDecoder, + bool? timers, + bool? tty, + bool? url, + bool? util, + bool? zlib, + bool? json}); +} + +/// @nodoc +class __$JsBuiltinOptionsCopyWithImpl<$Res> + implements _$JsBuiltinOptionsCopyWith<$Res> { + __$JsBuiltinOptionsCopyWithImpl(this._self, this._then); + + final _JsBuiltinOptions _self; + final $Res Function(_JsBuiltinOptions) _then; + + /// Create a copy of JsBuiltinOptions + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? abort = freezed, + Object? assert_ = freezed, + Object? asyncHooks = freezed, + Object? buffer = freezed, + Object? childProcess = freezed, + Object? console = freezed, + Object? crypto = freezed, + Object? dns = freezed, + Object? events = freezed, + Object? exceptions = freezed, + Object? fetch = freezed, + Object? fs = freezed, + Object? navigator = freezed, + Object? net = freezed, + Object? os = freezed, + Object? path = freezed, + Object? perfHooks = freezed, + Object? process = freezed, + Object? streamWeb = freezed, + Object? stringDecoder = freezed, + Object? timers = freezed, + Object? tty = freezed, + Object? url = freezed, + Object? util = freezed, + Object? zlib = freezed, + Object? json = freezed, + }) { + return _then(_JsBuiltinOptions( + abort: freezed == abort + ? _self.abort + : abort // ignore: cast_nullable_to_non_nullable + as bool?, + assert_: freezed == assert_ + ? _self.assert_ + : assert_ // ignore: cast_nullable_to_non_nullable + as bool?, + asyncHooks: freezed == asyncHooks + ? _self.asyncHooks + : asyncHooks // ignore: cast_nullable_to_non_nullable + as bool?, + buffer: freezed == buffer + ? _self.buffer + : buffer // ignore: cast_nullable_to_non_nullable + as bool?, + childProcess: freezed == childProcess + ? _self.childProcess + : childProcess // ignore: cast_nullable_to_non_nullable + as bool?, + console: freezed == console + ? _self.console + : console // ignore: cast_nullable_to_non_nullable + as bool?, + crypto: freezed == crypto + ? _self.crypto + : crypto // ignore: cast_nullable_to_non_nullable + as bool?, + dns: freezed == dns + ? _self.dns + : dns // ignore: cast_nullable_to_non_nullable + as bool?, + events: freezed == events + ? _self.events + : events // ignore: cast_nullable_to_non_nullable + as bool?, + exceptions: freezed == exceptions + ? _self.exceptions + : exceptions // ignore: cast_nullable_to_non_nullable + as bool?, + fetch: freezed == fetch + ? _self.fetch + : fetch // ignore: cast_nullable_to_non_nullable + as bool?, + fs: freezed == fs + ? _self.fs + : fs // ignore: cast_nullable_to_non_nullable + as bool?, + navigator: freezed == navigator + ? _self.navigator + : navigator // ignore: cast_nullable_to_non_nullable + as bool?, + net: freezed == net + ? _self.net + : net // ignore: cast_nullable_to_non_nullable + as bool?, + os: freezed == os + ? _self.os + : os // ignore: cast_nullable_to_non_nullable + as bool?, + path: freezed == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as bool?, + perfHooks: freezed == perfHooks + ? _self.perfHooks + : perfHooks // ignore: cast_nullable_to_non_nullable + as bool?, + process: freezed == process + ? _self.process + : process // ignore: cast_nullable_to_non_nullable + as bool?, + streamWeb: freezed == streamWeb + ? _self.streamWeb + : streamWeb // ignore: cast_nullable_to_non_nullable + as bool?, + stringDecoder: freezed == stringDecoder + ? _self.stringDecoder + : stringDecoder // ignore: cast_nullable_to_non_nullable + as bool?, + timers: freezed == timers + ? _self.timers + : timers // ignore: cast_nullable_to_non_nullable + as bool?, + tty: freezed == tty + ? _self.tty + : tty // ignore: cast_nullable_to_non_nullable + as bool?, + url: freezed == url + ? _self.url + : url // ignore: cast_nullable_to_non_nullable + as bool?, + util: freezed == util + ? _self.util + : util // ignore: cast_nullable_to_non_nullable + as bool?, + zlib: freezed == zlib + ? _self.zlib + : zlib // ignore: cast_nullable_to_non_nullable + as bool?, + json: freezed == json + ? _self.json + : json // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc +mixin _$JsCode { + Object get field0; + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCode && + const DeepCollectionEquality().equals(other.field0, field0)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); + + @override + String toString() { + return 'JsCode(field0: $field0)'; + } +} + +/// @nodoc +class $JsCodeCopyWith<$Res> { + $JsCodeCopyWith(JsCode _, $Res Function(JsCode) __); +} + +/// Adds pattern-matching-related methods to [JsCode]. +extension JsCodePatterns on JsCode { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(JsCode_Code value)? code, + TResult Function(JsCode_Path value)? path, + TResult Function(JsCode_Bytes value)? bytes, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCode_Code() when code != null: + return code(_that); + case JsCode_Path() when path != null: + return path(_that); + case JsCode_Bytes() when bytes != null: + return bytes(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(JsCode_Code value) code, + required TResult Function(JsCode_Path value) path, + required TResult Function(JsCode_Bytes value) bytes, + }) { + final _that = this; + switch (_that) { + case JsCode_Code(): + return code(_that); + case JsCode_Path(): + return path(_that); + case JsCode_Bytes(): + return bytes(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(JsCode_Code value)? code, + TResult? Function(JsCode_Path value)? path, + TResult? Function(JsCode_Bytes value)? bytes, + }) { + final _that = this; + switch (_that) { + case JsCode_Code() when code != null: + return code(_that); + case JsCode_Path() when path != null: + return path(_that); + case JsCode_Bytes() when bytes != null: + return bytes(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String field0)? code, + TResult Function(String field0)? path, + TResult Function(Uint8List field0)? bytes, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case JsCode_Code() when code != null: + return code(_that.field0); + case JsCode_Path() when path != null: + return path(_that.field0); + case JsCode_Bytes() when bytes != null: + return bytes(_that.field0); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(String field0) code, + required TResult Function(String field0) path, + required TResult Function(Uint8List field0) bytes, + }) { + final _that = this; + switch (_that) { + case JsCode_Code(): + return code(_that.field0); + case JsCode_Path(): + return path(_that.field0); + case JsCode_Bytes(): + return bytes(_that.field0); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String field0)? code, + TResult? Function(String field0)? path, + TResult? Function(Uint8List field0)? bytes, + }) { + final _that = this; + switch (_that) { + case JsCode_Code() when code != null: + return code(_that.field0); + case JsCode_Path() when path != null: + return path(_that.field0); + case JsCode_Bytes() when bytes != null: + return bytes(_that.field0); + case _: + return null; + } + } +} + +/// @nodoc + +class JsCode_Code extends JsCode { + const JsCode_Code(this.field0) : super._(); + + @override + final String field0; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCode_CodeCopyWith get copyWith => + _$JsCode_CodeCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCode_Code && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsCode.code(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCode_CodeCopyWith<$Res> + implements $JsCodeCopyWith<$Res> { + factory $JsCode_CodeCopyWith( + JsCode_Code value, $Res Function(JsCode_Code) _then) = + _$JsCode_CodeCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsCode_CodeCopyWithImpl<$Res> implements $JsCode_CodeCopyWith<$Res> { + _$JsCode_CodeCopyWithImpl(this._self, this._then); + + final JsCode_Code _self; + final $Res Function(JsCode_Code) _then; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCode_Code( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsCode_Path extends JsCode { + const JsCode_Path(this.field0) : super._(); + + @override + final String field0; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCode_PathCopyWith get copyWith => + _$JsCode_PathCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCode_Path && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsCode.path(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCode_PathCopyWith<$Res> + implements $JsCodeCopyWith<$Res> { + factory $JsCode_PathCopyWith( + JsCode_Path value, $Res Function(JsCode_Path) _then) = + _$JsCode_PathCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsCode_PathCopyWithImpl<$Res> implements $JsCode_PathCopyWith<$Res> { + _$JsCode_PathCopyWithImpl(this._self, this._then); + + final JsCode_Path _self; + final $Res Function(JsCode_Path) _then; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCode_Path( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsCode_Bytes extends JsCode { + const JsCode_Bytes(this.field0) : super._(); + + @override + final Uint8List field0; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsCode_BytesCopyWith get copyWith => + _$JsCode_BytesCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsCode_Bytes && + const DeepCollectionEquality().equals(other.field0, field0)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); + + @override + String toString() { + return 'JsCode.bytes(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsCode_BytesCopyWith<$Res> + implements $JsCodeCopyWith<$Res> { + factory $JsCode_BytesCopyWith( + JsCode_Bytes value, $Res Function(JsCode_Bytes) _then) = + _$JsCode_BytesCopyWithImpl; + @useResult + $Res call({Uint8List field0}); +} + +/// @nodoc +class _$JsCode_BytesCopyWithImpl<$Res> implements $JsCode_BytesCopyWith<$Res> { + _$JsCode_BytesCopyWithImpl(this._self, this._then); + + final JsCode_Bytes _self; + final $Res Function(JsCode_Bytes) _then; + + /// Create a copy of JsCode + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsCode_Bytes( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as Uint8List, + )); + } +} + +/// @nodoc +mixin _$JsEvalOptions { + bool? get global; + bool? get strict; + bool? get backtraceBarrier; + bool? get promise; + + /// Create a copy of JsEvalOptions + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsEvalOptionsCopyWith get copyWith => + _$JsEvalOptionsCopyWithImpl( + this as JsEvalOptions, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsEvalOptions && + (identical(other.global, global) || other.global == global) && + (identical(other.strict, strict) || other.strict == strict) && + (identical(other.backtraceBarrier, backtraceBarrier) || + other.backtraceBarrier == backtraceBarrier) && + (identical(other.promise, promise) || other.promise == promise)); + } + + @override + int get hashCode => + Object.hash(runtimeType, global, strict, backtraceBarrier, promise); + + @override + String toString() { + return 'JsEvalOptions(global: $global, strict: $strict, backtraceBarrier: $backtraceBarrier, promise: $promise)'; + } +} + +/// @nodoc +abstract mixin class $JsEvalOptionsCopyWith<$Res> { + factory $JsEvalOptionsCopyWith( + JsEvalOptions value, $Res Function(JsEvalOptions) _then) = + _$JsEvalOptionsCopyWithImpl; + @useResult + $Res call( + {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}); +} + +/// @nodoc +class _$JsEvalOptionsCopyWithImpl<$Res> + implements $JsEvalOptionsCopyWith<$Res> { + _$JsEvalOptionsCopyWithImpl(this._self, this._then); + + final JsEvalOptions _self; + final $Res Function(JsEvalOptions) _then; + + /// Create a copy of JsEvalOptions + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? global = freezed, + Object? strict = freezed, + Object? backtraceBarrier = freezed, + Object? promise = freezed, + }) { + return _then(_self.copyWith( + global: freezed == global + ? _self.global + : global // ignore: cast_nullable_to_non_nullable + as bool?, + strict: freezed == strict + ? _self.strict + : strict // ignore: cast_nullable_to_non_nullable + as bool?, + backtraceBarrier: freezed == backtraceBarrier + ? _self.backtraceBarrier + : backtraceBarrier // ignore: cast_nullable_to_non_nullable + as bool?, + promise: freezed == promise + ? _self.promise + : promise // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// Adds pattern-matching-related methods to [JsEvalOptions]. +extension JsEvalOptionsPatterns on JsEvalOptions { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_JsEvalOptions value)? raw, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions() when raw != null: + return raw(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(_JsEvalOptions value) raw, + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions(): + return raw(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_JsEvalOptions value)? raw, + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions() when raw != null: + return raw(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function( + bool? global, bool? strict, bool? backtraceBarrier, bool? promise)? + raw, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions() when raw != null: + return raw( + _that.global, _that.strict, _that.backtraceBarrier, _that.promise); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function( + bool? global, bool? strict, bool? backtraceBarrier, bool? promise) + raw, + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions(): + return raw( + _that.global, _that.strict, _that.backtraceBarrier, _that.promise); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + bool? global, bool? strict, bool? backtraceBarrier, bool? promise)? + raw, + }) { + final _that = this; + switch (_that) { + case _JsEvalOptions() when raw != null: + return raw( + _that.global, _that.strict, _that.backtraceBarrier, _that.promise); + case _: + return null; + } + } +} + +/// @nodoc + +class _JsEvalOptions extends JsEvalOptions { + const _JsEvalOptions( + {this.global, this.strict, this.backtraceBarrier, this.promise}) + : super._(); + + @override + final bool? global; + @override + final bool? strict; + @override + final bool? backtraceBarrier; + @override + final bool? promise; + + /// Create a copy of JsEvalOptions + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$JsEvalOptionsCopyWith<_JsEvalOptions> get copyWith => + __$JsEvalOptionsCopyWithImpl<_JsEvalOptions>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _JsEvalOptions && + (identical(other.global, global) || other.global == global) && + (identical(other.strict, strict) || other.strict == strict) && + (identical(other.backtraceBarrier, backtraceBarrier) || + other.backtraceBarrier == backtraceBarrier) && + (identical(other.promise, promise) || other.promise == promise)); + } + + @override + int get hashCode => + Object.hash(runtimeType, global, strict, backtraceBarrier, promise); + + @override + String toString() { + return 'JsEvalOptions.raw(global: $global, strict: $strict, backtraceBarrier: $backtraceBarrier, promise: $promise)'; + } +} + +/// @nodoc +abstract mixin class _$JsEvalOptionsCopyWith<$Res> + implements $JsEvalOptionsCopyWith<$Res> { + factory _$JsEvalOptionsCopyWith( + _JsEvalOptions value, $Res Function(_JsEvalOptions) _then) = + __$JsEvalOptionsCopyWithImpl; + @override + @useResult + $Res call( + {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}); +} + +/// @nodoc +class __$JsEvalOptionsCopyWithImpl<$Res> + implements _$JsEvalOptionsCopyWith<$Res> { + __$JsEvalOptionsCopyWithImpl(this._self, this._then); + + final _JsEvalOptions _self; + final $Res Function(_JsEvalOptions) _then; + + /// Create a copy of JsEvalOptions + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? global = freezed, + Object? strict = freezed, + Object? backtraceBarrier = freezed, + Object? promise = freezed, + }) { + return _then(_JsEvalOptions( + global: freezed == global + ? _self.global + : global // ignore: cast_nullable_to_non_nullable + as bool?, + strict: freezed == strict + ? _self.strict + : strict // ignore: cast_nullable_to_non_nullable + as bool?, + backtraceBarrier: freezed == backtraceBarrier + ? _self.backtraceBarrier + : backtraceBarrier // ignore: cast_nullable_to_non_nullable + as bool?, + promise: freezed == promise + ? _self.promise + : promise // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc +mixin _$JsModule { + String get name; + JsCode get source; + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsModuleCopyWith get copyWith => + _$JsModuleCopyWithImpl(this as JsModule, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsModule && + (identical(other.name, name) || other.name == name) && + (identical(other.source, source) || other.source == source)); + } + + @override + int get hashCode => Object.hash(runtimeType, name, source); + + @override + String toString() { + return 'JsModule(name: $name, source: $source)'; + } +} + +/// @nodoc +abstract mixin class $JsModuleCopyWith<$Res> { + factory $JsModuleCopyWith(JsModule value, $Res Function(JsModule) _then) = + _$JsModuleCopyWithImpl; + @useResult + $Res call({String name, JsCode source}); + + $JsCodeCopyWith<$Res> get source; +} + +/// @nodoc +class _$JsModuleCopyWithImpl<$Res> implements $JsModuleCopyWith<$Res> { + _$JsModuleCopyWithImpl(this._self, this._then); + + final JsModule _self; + final $Res Function(JsModule) _then; + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? source = null, + }) { + return _then(_self.copyWith( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + source: null == source + ? _self.source + : source // ignore: cast_nullable_to_non_nullable + as JsCode, + )); + } + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsCodeCopyWith<$Res> get source { + return $JsCodeCopyWith<$Res>(_self.source, (value) { + return _then(_self.copyWith(source: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [JsModule]. +extension JsModulePatterns on JsModule { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_JsModule value)? raw, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsModule() when raw != null: + return raw(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(_JsModule value) raw, + }) { + final _that = this; + switch (_that) { + case _JsModule(): + return raw(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_JsModule value)? raw, + }) { + final _that = this; + switch (_that) { + case _JsModule() when raw != null: + return raw(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String name, JsCode source)? raw, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _JsModule() when raw != null: + return raw(_that.name, _that.source); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(String name, JsCode source) raw, + }) { + final _that = this; + switch (_that) { + case _JsModule(): + return raw(_that.name, _that.source); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String name, JsCode source)? raw, + }) { + final _that = this; + switch (_that) { + case _JsModule() when raw != null: + return raw(_that.name, _that.source); + case _: + return null; + } + } +} + +/// @nodoc + +class _JsModule extends JsModule { + const _JsModule({required this.name, required this.source}) : super._(); + + @override + final String name; + @override + final JsCode source; + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$JsModuleCopyWith<_JsModule> get copyWith => + __$JsModuleCopyWithImpl<_JsModule>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _JsModule && + (identical(other.name, name) || other.name == name) && + (identical(other.source, source) || other.source == source)); + } + + @override + int get hashCode => Object.hash(runtimeType, name, source); + + @override + String toString() { + return 'JsModule.raw(name: $name, source: $source)'; + } +} + +/// @nodoc +abstract mixin class _$JsModuleCopyWith<$Res> + implements $JsModuleCopyWith<$Res> { + factory _$JsModuleCopyWith(_JsModule value, $Res Function(_JsModule) _then) = + __$JsModuleCopyWithImpl; + @override + @useResult + $Res call({String name, JsCode source}); + + @override + $JsCodeCopyWith<$Res> get source; +} + +/// @nodoc +class __$JsModuleCopyWithImpl<$Res> implements _$JsModuleCopyWith<$Res> { + __$JsModuleCopyWithImpl(this._self, this._then); + + final _JsModule _self; + final $Res Function(_JsModule) _then; + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? name = null, + Object? source = null, + }) { + return _then(_JsModule( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + source: null == source + ? _self.source + : source // ignore: cast_nullable_to_non_nullable + as JsCode, + )); + } + + /// Create a copy of JsModule + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $JsCodeCopyWith<$Res> get source { + return $JsCodeCopyWith<$Res>(_self.source, (value) { + return _then(_self.copyWith(source: value)); + }); + } +} + +// dart format on diff --git a/lib/src/frb/api/value.dart b/lib/src/frb/api/value.dart index 27912a0..1658625 100644 --- a/lib/src/frb/api/value.dart +++ b/lib/src/frb/api/value.dart @@ -8,8 +8,8 @@ import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; import 'package:freezed_annotation/freezed_annotation.dart' hide protected; part 'value.freezed.dart'; -// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `fmt` -// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `from_js`, `into_js` +// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`, `eq`, `fmt`, `from_js`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `from`, `into_js` +// These functions are ignored (category: IgnoreBecauseExplicitAttribute): `array`, `bigint`, `boolean`, `bytes`, `date`, `float`, `integer`, `none`, `object`, `string` @freezed sealed class JsValue with _$JsValue { @@ -43,6 +43,11 @@ sealed class JsValue with _$JsValue { String field0, ) = JsValue_String; + /// Represents binary data (ArrayBuffer/TypedArray) + const factory JsValue.bytes( + Uint8List field0, + ) = JsValue_Bytes; + /// Represents arrays with nested value support const factory JsValue.array( List field0, @@ -53,6 +58,75 @@ sealed class JsValue with _$JsValue { Map field0, ) = JsValue_Object; + /// Represents Date objects (milliseconds since epoch) + const factory JsValue.date( + PlatformInt64 field0, + ) = JsValue_Date; + + /// Represents Symbol values (description) + const factory JsValue.symbol( + String field0, + ) = JsValue_Symbol; + + /// Represents function references (serialized name/id) + const factory JsValue.function( + String field0, + ) = JsValue_Function; + + static Future default_() => + LibFjs.instance.api.crateApiValueJsValueDefault(); + + /// Returns true if the value is an array. + bool isArray() => LibFjs.instance.api.crateApiValueJsValueIsArray( + that: this, + ); + + /// Returns true if the value is a boolean. + bool isBoolean() => LibFjs.instance.api.crateApiValueJsValueIsBoolean( + that: this, + ); + + /// Returns true if the value is bytes (binary data). + bool isBytes() => LibFjs.instance.api.crateApiValueJsValueIsBytes( + that: this, + ); + + /// Returns true if the value is a Date. + bool isDate() => LibFjs.instance.api.crateApiValueJsValueIsDate( + that: this, + ); + + /// Returns true if the value is None. + bool isNone() => LibFjs.instance.api.crateApiValueJsValueIsNone( + that: this, + ); + + /// Returns true if the value is a number (integer, float, or bigint). + bool isNumber() => LibFjs.instance.api.crateApiValueJsValueIsNumber( + that: this, + ); + + /// Returns true if the value is an object. + bool isObject() => LibFjs.instance.api.crateApiValueJsValueIsObject( + that: this, + ); + + /// Returns true if the value is a primitive type. + bool isPrimitive() => LibFjs.instance.api.crateApiValueJsValueIsPrimitive( + that: this, + ); + + /// Returns true if the value is a string. + bool isString() => LibFjs.instance.api.crateApiValueJsValueIsString( + that: this, + ); + + /// Returns the type name of this value. + String typeName() => LibFjs.instance.api.crateApiValueJsValueTypeName( + that: this, + ); + + /// Creates a JsValue from any Dart object. static JsValue from(Object? any) { if (any == null) { return const JsValue.none(); @@ -66,6 +140,8 @@ sealed class JsValue with _$JsValue { return JsValue.bigint(any.toString()); } else if (any is String) { return JsValue.string(any); + } else if (any is Uint8List) { + return JsValue.bytes(any); } else if (any is List) { return JsValue.array(any.map((e) => from(e)).toList()); } else if (any is Map) { @@ -77,6 +153,7 @@ sealed class JsValue with _$JsValue { } } + /// Gets the underlying Dart value. dynamic get value => when( none: () => null, boolean: (v) => v, @@ -84,23 +161,43 @@ sealed class JsValue with _$JsValue { float: (v) => v, bigint: (v) => BigInt.parse(v), string: (v) => v, + bytes: (v) => v, array: (v) => v.map((e) => e.value).toList(), object: (v) => v.map((key, value) => MapEntry(key, value.value)), + date: (ms) => DateTime.fromMillisecondsSinceEpoch(ms.toInt()), + symbol: (v) => v, + function: (v) => v, ); - bool get isNone => this is JsValue_None; - - bool get isBoolean => this is JsValue_Boolean; - - bool get isInteger => this is JsValue_Integer; - - bool get isFloat => this is JsValue_Float; - - bool get isBigint => this is JsValue_Bigint; - - bool get isString => this is JsValue_String; - - bool get isArray => this is JsValue_Array; - - bool get isObject => this is JsValue_Object; + /// Safe casting methods + bool? get asBoolean => + this is JsValue_Boolean ? (this as JsValue_Boolean).field0 : null; + int? get asInteger => + this is JsValue_Integer ? (this as JsValue_Integer).field0 : null; + double? get asFloat => + this is JsValue_Float ? (this as JsValue_Float).field0 : null; + String? get asBigint => + this is JsValue_Bigint ? (this as JsValue_Bigint).field0 : null; + String? get asString => + this is JsValue_String ? (this as JsValue_String).field0 : null; + Uint8List? get asBytes => + this is JsValue_Bytes ? (this as JsValue_Bytes).field0 : null; + List? get asArray => + this is JsValue_Array ? (this as JsValue_Array).field0 : null; + Map? get asObject => + this is JsValue_Object ? (this as JsValue_Object).field0 : null; + + /// Converts to num if possible. + num? get asNum { + if (this is JsValue_Integer) return (this as JsValue_Integer).field0; + if (this is JsValue_Float) return (this as JsValue_Float).field0; + if (this is JsValue_Bigint) { + final bigint = BigInt.parse((this as JsValue_Bigint).field0); + if (bigint >= BigInt.from(-9007199254740991) && + bigint <= BigInt.from(9007199254740991)) { + return bigint.toInt(); + } + } + return null; + } } diff --git a/lib/src/frb/api/value.freezed.dart b/lib/src/frb/api/value.freezed.dart index 5dd9fae..7a155cb 100644 --- a/lib/src/frb/api/value.freezed.dart +++ b/lib/src/frb/api/value.freezed.dart @@ -56,8 +56,12 @@ extension JsValuePatterns on JsValue { TResult Function(JsValue_Float value)? float, TResult Function(JsValue_Bigint value)? bigint, TResult Function(JsValue_String value)? string, + TResult Function(JsValue_Bytes value)? bytes, TResult Function(JsValue_Array value)? array, TResult Function(JsValue_Object value)? object, + TResult Function(JsValue_Date value)? date, + TResult Function(JsValue_Symbol value)? symbol, + TResult Function(JsValue_Function value)? function, required TResult orElse(), }) { final _that = this; @@ -74,10 +78,18 @@ extension JsValuePatterns on JsValue { return bigint(_that); case JsValue_String() when string != null: return string(_that); + case JsValue_Bytes() when bytes != null: + return bytes(_that); case JsValue_Array() when array != null: return array(_that); case JsValue_Object() when object != null: return object(_that); + case JsValue_Date() when date != null: + return date(_that); + case JsValue_Symbol() when symbol != null: + return symbol(_that); + case JsValue_Function() when function != null: + return function(_that); case _: return orElse(); } @@ -104,8 +116,12 @@ extension JsValuePatterns on JsValue { required TResult Function(JsValue_Float value) float, required TResult Function(JsValue_Bigint value) bigint, required TResult Function(JsValue_String value) string, + required TResult Function(JsValue_Bytes value) bytes, required TResult Function(JsValue_Array value) array, required TResult Function(JsValue_Object value) object, + required TResult Function(JsValue_Date value) date, + required TResult Function(JsValue_Symbol value) symbol, + required TResult Function(JsValue_Function value) function, }) { final _that = this; switch (_that) { @@ -121,10 +137,18 @@ extension JsValuePatterns on JsValue { return bigint(_that); case JsValue_String(): return string(_that); + case JsValue_Bytes(): + return bytes(_that); case JsValue_Array(): return array(_that); case JsValue_Object(): return object(_that); + case JsValue_Date(): + return date(_that); + case JsValue_Symbol(): + return symbol(_that); + case JsValue_Function(): + return function(_that); } } @@ -148,8 +172,12 @@ extension JsValuePatterns on JsValue { TResult? Function(JsValue_Float value)? float, TResult? Function(JsValue_Bigint value)? bigint, TResult? Function(JsValue_String value)? string, + TResult? Function(JsValue_Bytes value)? bytes, TResult? Function(JsValue_Array value)? array, TResult? Function(JsValue_Object value)? object, + TResult? Function(JsValue_Date value)? date, + TResult? Function(JsValue_Symbol value)? symbol, + TResult? Function(JsValue_Function value)? function, }) { final _that = this; switch (_that) { @@ -165,10 +193,18 @@ extension JsValuePatterns on JsValue { return bigint(_that); case JsValue_String() when string != null: return string(_that); + case JsValue_Bytes() when bytes != null: + return bytes(_that); case JsValue_Array() when array != null: return array(_that); case JsValue_Object() when object != null: return object(_that); + case JsValue_Date() when date != null: + return date(_that); + case JsValue_Symbol() when symbol != null: + return symbol(_that); + case JsValue_Function() when function != null: + return function(_that); case _: return null; } @@ -194,8 +230,12 @@ extension JsValuePatterns on JsValue { TResult Function(double field0)? float, TResult Function(String field0)? bigint, TResult Function(String field0)? string, + TResult Function(Uint8List field0)? bytes, TResult Function(List field0)? array, TResult Function(Map field0)? object, + TResult Function(PlatformInt64 field0)? date, + TResult Function(String field0)? symbol, + TResult Function(String field0)? function, required TResult orElse(), }) { final _that = this; @@ -212,10 +252,18 @@ extension JsValuePatterns on JsValue { return bigint(_that.field0); case JsValue_String() when string != null: return string(_that.field0); + case JsValue_Bytes() when bytes != null: + return bytes(_that.field0); case JsValue_Array() when array != null: return array(_that.field0); case JsValue_Object() when object != null: return object(_that.field0); + case JsValue_Date() when date != null: + return date(_that.field0); + case JsValue_Symbol() when symbol != null: + return symbol(_that.field0); + case JsValue_Function() when function != null: + return function(_that.field0); case _: return orElse(); } @@ -242,8 +290,12 @@ extension JsValuePatterns on JsValue { required TResult Function(double field0) float, required TResult Function(String field0) bigint, required TResult Function(String field0) string, + required TResult Function(Uint8List field0) bytes, required TResult Function(List field0) array, required TResult Function(Map field0) object, + required TResult Function(PlatformInt64 field0) date, + required TResult Function(String field0) symbol, + required TResult Function(String field0) function, }) { final _that = this; switch (_that) { @@ -259,10 +311,18 @@ extension JsValuePatterns on JsValue { return bigint(_that.field0); case JsValue_String(): return string(_that.field0); + case JsValue_Bytes(): + return bytes(_that.field0); case JsValue_Array(): return array(_that.field0); case JsValue_Object(): return object(_that.field0); + case JsValue_Date(): + return date(_that.field0); + case JsValue_Symbol(): + return symbol(_that.field0); + case JsValue_Function(): + return function(_that.field0); } } @@ -286,8 +346,12 @@ extension JsValuePatterns on JsValue { TResult? Function(double field0)? float, TResult? Function(String field0)? bigint, TResult? Function(String field0)? string, + TResult? Function(Uint8List field0)? bytes, TResult? Function(List field0)? array, TResult? Function(Map field0)? object, + TResult? Function(PlatformInt64 field0)? date, + TResult? Function(String field0)? symbol, + TResult? Function(String field0)? function, }) { final _that = this; switch (_that) { @@ -303,10 +367,18 @@ extension JsValuePatterns on JsValue { return bigint(_that.field0); case JsValue_String() when string != null: return string(_that.field0); + case JsValue_Bytes() when bytes != null: + return bytes(_that.field0); case JsValue_Array() when array != null: return array(_that.field0); case JsValue_Object() when object != null: return object(_that.field0); + case JsValue_Date() when date != null: + return date(_that.field0); + case JsValue_Symbol() when symbol != null: + return symbol(_that.field0); + case JsValue_Function() when function != null: + return function(_that.field0); case _: return null; } @@ -655,6 +727,71 @@ class _$JsValue_StringCopyWithImpl<$Res> /// @nodoc +class JsValue_Bytes extends JsValue { + const JsValue_Bytes(this.field0) : super._(); + + final Uint8List field0; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsValue_BytesCopyWith get copyWith => + _$JsValue_BytesCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsValue_Bytes && + const DeepCollectionEquality().equals(other.field0, field0)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(field0)); + + @override + String toString() { + return 'JsValue.bytes(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsValue_BytesCopyWith<$Res> + implements $JsValueCopyWith<$Res> { + factory $JsValue_BytesCopyWith( + JsValue_Bytes value, $Res Function(JsValue_Bytes) _then) = + _$JsValue_BytesCopyWithImpl; + @useResult + $Res call({Uint8List field0}); +} + +/// @nodoc +class _$JsValue_BytesCopyWithImpl<$Res> + implements $JsValue_BytesCopyWith<$Res> { + _$JsValue_BytesCopyWithImpl(this._self, this._then); + + final JsValue_Bytes _self; + final $Res Function(JsValue_Bytes) _then; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsValue_Bytes( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as Uint8List, + )); + } +} + +/// @nodoc + class JsValue_Array extends JsValue { const JsValue_Array(final List field0) : _field0 = field0, @@ -797,4 +934,195 @@ class _$JsValue_ObjectCopyWithImpl<$Res> } } +/// @nodoc + +class JsValue_Date extends JsValue { + const JsValue_Date(this.field0) : super._(); + + final PlatformInt64 field0; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsValue_DateCopyWith get copyWith => + _$JsValue_DateCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsValue_Date && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsValue.date(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsValue_DateCopyWith<$Res> + implements $JsValueCopyWith<$Res> { + factory $JsValue_DateCopyWith( + JsValue_Date value, $Res Function(JsValue_Date) _then) = + _$JsValue_DateCopyWithImpl; + @useResult + $Res call({PlatformInt64 field0}); +} + +/// @nodoc +class _$JsValue_DateCopyWithImpl<$Res> implements $JsValue_DateCopyWith<$Res> { + _$JsValue_DateCopyWithImpl(this._self, this._then); + + final JsValue_Date _self; + final $Res Function(JsValue_Date) _then; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsValue_Date( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as PlatformInt64, + )); + } +} + +/// @nodoc + +class JsValue_Symbol extends JsValue { + const JsValue_Symbol(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsValue_SymbolCopyWith get copyWith => + _$JsValue_SymbolCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsValue_Symbol && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsValue.symbol(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsValue_SymbolCopyWith<$Res> + implements $JsValueCopyWith<$Res> { + factory $JsValue_SymbolCopyWith( + JsValue_Symbol value, $Res Function(JsValue_Symbol) _then) = + _$JsValue_SymbolCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsValue_SymbolCopyWithImpl<$Res> + implements $JsValue_SymbolCopyWith<$Res> { + _$JsValue_SymbolCopyWithImpl(this._self, this._then); + + final JsValue_Symbol _self; + final $Res Function(JsValue_Symbol) _then; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsValue_Symbol( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class JsValue_Function extends JsValue { + const JsValue_Function(this.field0) : super._(); + + final String field0; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $JsValue_FunctionCopyWith get copyWith => + _$JsValue_FunctionCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is JsValue_Function && + (identical(other.field0, field0) || other.field0 == field0)); + } + + @override + int get hashCode => Object.hash(runtimeType, field0); + + @override + String toString() { + return 'JsValue.function(field0: $field0)'; + } +} + +/// @nodoc +abstract mixin class $JsValue_FunctionCopyWith<$Res> + implements $JsValueCopyWith<$Res> { + factory $JsValue_FunctionCopyWith( + JsValue_Function value, $Res Function(JsValue_Function) _then) = + _$JsValue_FunctionCopyWithImpl; + @useResult + $Res call({String field0}); +} + +/// @nodoc +class _$JsValue_FunctionCopyWithImpl<$Res> + implements $JsValue_FunctionCopyWith<$Res> { + _$JsValue_FunctionCopyWithImpl(this._self, this._then); + + final JsValue_Function _self; + final $Res Function(JsValue_Function) _then; + + /// Create a copy of JsValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? field0 = null, + }) { + return _then(JsValue_Function( + null == field0 + ? _self.field0 + : field0 // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + // dart format on diff --git a/lib/src/frb/frb_generated.dart b/lib/src/frb/frb_generated.dart index 6fff7aa..9127fd2 100644 --- a/lib/src/frb/frb_generated.dart +++ b/lib/src/frb/frb_generated.dart @@ -3,7 +3,10 @@ // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field -import 'api/js.dart'; +import 'api/engine.dart'; +import 'api/error.dart'; +import 'api/runtime.dart'; +import 'api/source.dart'; import 'api/value.dart'; import 'dart:async'; import 'dart:convert'; @@ -71,7 +74,7 @@ class LibFjs extends BaseEntrypoint { String get codegenVersion => '2.11.1'; @override - int get rustContentHash => 2034567146; + int get rustContentHash => 869436497; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -82,205 +85,277 @@ class LibFjs extends BaseEntrypoint { } abstract class LibFjsApi extends BaseApi { - Future crateApiJsJsAsyncContextEval( + Future crateApiRuntimeJsAsyncContextEval( {required JsAsyncContext that, required String code}); - Future crateApiJsJsAsyncContextEvalFile( + Future crateApiRuntimeJsAsyncContextEvalFile( {required JsAsyncContext that, required String path}); - Future crateApiJsJsAsyncContextEvalFileWithOptions( + Future crateApiRuntimeJsAsyncContextEvalFileWithOptions( {required JsAsyncContext that, required String path, required JsEvalOptions options}); - Future crateApiJsJsAsyncContextEvalFunction( + Future crateApiRuntimeJsAsyncContextEvalFunction( {required JsAsyncContext that, required String module, required String method, List? params}); - Future crateApiJsJsAsyncContextEvalWithOptions( + Future crateApiRuntimeJsAsyncContextEvalWithOptions( {required JsAsyncContext that, required String code, required JsEvalOptions options}); - Future crateApiJsJsAsyncContextFrom( + Future crateApiRuntimeJsAsyncContextFrom( {required JsAsyncRuntime rt}); - Future crateApiJsJsAsyncRuntimeExecutePendingJob( + Future crateApiRuntimeJsAsyncRuntimeExecutePendingJob( {required JsAsyncRuntime that}); - Future crateApiJsJsAsyncRuntimeIdle({required JsAsyncRuntime that}); + Future crateApiRuntimeJsAsyncRuntimeIdle( + {required JsAsyncRuntime that}); - Future crateApiJsJsAsyncRuntimeIsJobPending( + Future crateApiRuntimeJsAsyncRuntimeIsJobPending( {required JsAsyncRuntime that}); - Future crateApiJsJsAsyncRuntimeMemoryUsage( + Future crateApiRuntimeJsAsyncRuntimeMemoryUsage( {required JsAsyncRuntime that}); - JsAsyncRuntime crateApiJsJsAsyncRuntimeNew(); + JsAsyncRuntime crateApiRuntimeJsAsyncRuntimeNew(); - Future crateApiJsJsAsyncRuntimeRunGc({required JsAsyncRuntime that}); + Future crateApiRuntimeJsAsyncRuntimeRunGc( + {required JsAsyncRuntime that}); - Future crateApiJsJsAsyncRuntimeSetGcThreshold( + Future crateApiRuntimeJsAsyncRuntimeSetGcThreshold( {required JsAsyncRuntime that, required BigInt threshold}); - Future crateApiJsJsAsyncRuntimeSetInfo( + Future crateApiRuntimeJsAsyncRuntimeSetInfo( {required JsAsyncRuntime that, required String info}); - Future crateApiJsJsAsyncRuntimeSetMaxStackSize( + Future crateApiRuntimeJsAsyncRuntimeSetMaxStackSize( {required JsAsyncRuntime that, required BigInt limit}); - Future crateApiJsJsAsyncRuntimeSetMemoryLimit( + Future crateApiRuntimeJsAsyncRuntimeSetMemoryLimit( {required JsAsyncRuntime that, required BigInt limit}); - Future crateApiJsJsAsyncRuntimeWithOptions( + Future crateApiRuntimeJsAsyncRuntimeWithOptions( {JsBuiltinOptions? builtin, List? additional}); - JsResult crateApiJsJsContextEval( + JsResult crateApiRuntimeJsContextEval( {required JsContext that, required String code}); - JsResult crateApiJsJsContextEvalFile( + JsResult crateApiRuntimeJsContextEvalFile( {required JsContext that, required String path}); - JsResult crateApiJsJsContextEvalFileWithOptions( + JsResult crateApiRuntimeJsContextEvalFileWithOptions( {required JsContext that, required String path, required JsEvalOptions options}); - JsResult crateApiJsJsContextEvalWithOptions( + JsResult crateApiRuntimeJsContextEvalWithOptions( {required JsContext that, required String code, required JsEvalOptions options}); - JsContext crateApiJsJsContextNew({required JsRuntime rt}); + JsContext crateApiRuntimeJsContextNew({required JsRuntime rt}); - JsAsyncContext crateApiJsJsEngineCoreContext({required JsEngineCore that}); + JsAsyncContext crateApiEngineJsEngineCoreContext( + {required JsEngineCore that}); - Future crateApiJsJsEngineCoreDispose({required JsEngineCore that}); + Future crateApiEngineJsEngineCoreDispose({required JsEngineCore that}); - bool crateApiJsJsEngineCoreDisposed({required JsEngineCore that}); + bool crateApiEngineJsEngineCoreDisposed({required JsEngineCore that}); - Future crateApiJsJsEngineCoreExec( + Future crateApiEngineJsEngineCoreExec( {required JsEngineCore that, required JsAction action}); - JsEngineCore crateApiJsJsEngineCoreNew({required JsAsyncContext context}); + JsEngineCore crateApiEngineJsEngineCoreNew({required JsAsyncContext context}); - bool crateApiJsJsEngineCoreRunning({required JsEngineCore that}); + bool crateApiEngineJsEngineCoreRunning({required JsEngineCore that}); - Future crateApiJsJsEngineCoreStart( + Future crateApiEngineJsEngineCoreStart( {required JsEngineCore that, required FutureOr Function(JsCallback) bridge}); - bool crateApiJsJsRuntimeExecutePendingJob({required JsRuntime that}); + bool crateApiRuntimeJsRuntimeExecutePendingJob({required JsRuntime that}); - bool crateApiJsJsRuntimeIsJobPending({required JsRuntime that}); + bool crateApiRuntimeJsRuntimeIsJobPending({required JsRuntime that}); - MemoryUsage crateApiJsJsRuntimeMemoryUsage({required JsRuntime that}); + MemoryUsage crateApiRuntimeJsRuntimeMemoryUsage({required JsRuntime that}); - JsRuntime crateApiJsJsRuntimeNew(); + JsRuntime crateApiRuntimeJsRuntimeNew(); - void crateApiJsJsRuntimeRunGc({required JsRuntime that}); + void crateApiRuntimeJsRuntimeRunGc({required JsRuntime that}); - void crateApiJsJsRuntimeSetDumpFlags( + void crateApiRuntimeJsRuntimeSetDumpFlags( {required JsRuntime that, required BigInt flags}); - void crateApiJsJsRuntimeSetGcThreshold( + void crateApiRuntimeJsRuntimeSetGcThreshold( {required JsRuntime that, required BigInt threshold}); - void crateApiJsJsRuntimeSetInfo( + void crateApiRuntimeJsRuntimeSetInfo( {required JsRuntime that, required String info}); - void crateApiJsJsRuntimeSetMaxStackSize( + void crateApiRuntimeJsRuntimeSetMaxStackSize( {required JsRuntime that, required BigInt limit}); - void crateApiJsJsRuntimeSetMemoryLimit( + void crateApiRuntimeJsRuntimeSetMemoryLimit( {required JsRuntime that, required BigInt limit}); - Future crateApiJsJsRuntimeWithOptions( + Future crateApiRuntimeJsRuntimeWithOptions( {JsBuiltinOptions? builtin, List? additional}); - PlatformInt64 crateApiJsMemoryUsageArrayCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageArrayCount( + {required MemoryUsage that}); + + PlatformInt64 crateApiRuntimeMemoryUsageAtomCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageAtomCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageAtomSize({required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageAtomSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageBinaryObjectCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageBinaryObjectCount( + PlatformInt64 crateApiRuntimeMemoryUsageBinaryObjectSize( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageBinaryObjectSize( + PlatformInt64 crateApiRuntimeMemoryUsageCFuncCount( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageCFuncCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageFastArrayCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageFastArrayCount( + PlatformInt64 crateApiRuntimeMemoryUsageFastArrayElements( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageFastArrayElements( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncCodeSize( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageJsFuncCodeSize( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncCount( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageJsFuncCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncPc2LineCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageJsFuncPc2LineCount( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncPc2LineSize( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageJsFuncPc2LineSize( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncSize( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageJsFuncSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageMallocCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageMallocCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageMallocLimit( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageMallocLimit({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageMallocSize( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageMallocSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageMemoryUsedCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageMemoryUsedCount( + PlatformInt64 crateApiRuntimeMemoryUsageMemoryUsedSize( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageMemoryUsedSize( + PlatformInt64 crateApiRuntimeMemoryUsageObjCount({required MemoryUsage that}); + + PlatformInt64 crateApiRuntimeMemoryUsageObjSize({required MemoryUsage that}); + + PlatformInt64 crateApiRuntimeMemoryUsagePropCount( {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageObjCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsagePropSize({required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageObjSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageShapeCount( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsagePropCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageShapeSize( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsagePropSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageStrCount({required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageShapeCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageStrSize({required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageShapeSize({required MemoryUsage that}); + String crateApiRuntimeMemoryUsageSummary({required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageStrCount({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageTotalAllocations( + {required MemoryUsage that}); - PlatformInt64 crateApiJsMemoryUsageStrSize({required MemoryUsage that}); + PlatformInt64 crateApiRuntimeMemoryUsageTotalMemory( + {required MemoryUsage that}); Future crateApiInitApp(); - JsBuiltinOptions crateApiJsJsBuiltinOptionsAll(); + JsBuiltinOptions crateApiSourceJsBuiltinOptionsAll(); + + Future crateApiSourceJsBuiltinOptionsDefault(); + + JsBuiltinOptions crateApiSourceJsBuiltinOptionsEssential(); + + JsBuiltinOptions crateApiSourceJsBuiltinOptionsNode(); + + JsBuiltinOptions crateApiSourceJsBuiltinOptionsNone(); + + JsBuiltinOptions crateApiSourceJsBuiltinOptionsWeb(); + + bool crateApiSourceJsCodeIsBytes({required JsCode that}); - String crateApiJsJsErrorToString({required JsError that}); + bool crateApiSourceJsCodeIsCode({required JsCode that}); - JsEvalOptions crateApiJsJsEvalOptionsNew( + bool crateApiSourceJsCodeIsPath({required JsCode that}); + + String crateApiErrorJsErrorCode({required JsError that}); + + bool crateApiErrorJsErrorIsRecoverable({required JsError that}); + + String crateApiErrorJsErrorToString({required JsError that}); + + Future crateApiSourceJsEvalOptionsDefault(); + + JsEvalOptions crateApiSourceJsEvalOptionsDefaults(); + + JsEvalOptions crateApiSourceJsEvalOptionsModule(); + + JsEvalOptions crateApiSourceJsEvalOptionsNew( {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}); - JsModule crateApiJsJsModuleBytes( + JsEvalOptions crateApiSourceJsEvalOptionsWithPromise(); + + JsModule crateApiSourceJsModuleFromBytes( {required String module, required List bytes}); - JsModule crateApiJsJsModuleCode( + JsModule crateApiSourceJsModuleFromCode( {required String module, required String code}); - JsModule crateApiJsJsModuleNew( + JsModule crateApiSourceJsModuleFromPath( + {required String module, required String path}); + + JsModule crateApiSourceJsModuleNew( {required String name, required JsCode source}); - JsModule crateApiJsJsModulePath( - {required String module, required String path}); + Future crateApiValueJsValueDefault(); + + bool crateApiValueJsValueIsArray({required JsValue that}); + + bool crateApiValueJsValueIsBoolean({required JsValue that}); + + bool crateApiValueJsValueIsBytes({required JsValue that}); + + bool crateApiValueJsValueIsDate({required JsValue that}); + + bool crateApiValueJsValueIsNone({required JsValue that}); + + bool crateApiValueJsValueIsNumber({required JsValue that}); + + bool crateApiValueJsValueIsObject({required JsValue that}); + + bool crateApiValueJsValueIsPrimitive({required JsValue that}); + + bool crateApiValueJsValueIsString({required JsValue that}); + + String crateApiValueJsValueTypeName({required JsValue that}); RustArcIncrementStrongCountFnType get rust_arc_increment_strong_count_JsAsyncContext; @@ -342,7 +417,7 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { }); @override - Future crateApiJsJsAsyncContextEval( + Future crateApiRuntimeJsAsyncContextEval( {required JsAsyncContext that, required String code}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -357,20 +432,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncContextEvalConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextEvalConstMeta, argValues: [that, code], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextEvalConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncContextEvalConstMeta => const TaskConstMeta( debugName: "JsAsyncContext_eval", argNames: ["that", "code"], ); @override - Future crateApiJsJsAsyncContextEvalFile( + Future crateApiRuntimeJsAsyncContextEvalFile( {required JsAsyncContext that, required String path}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -385,20 +460,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncContextEvalFileConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextEvalFileConstMeta, argValues: [that, path], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextEvalFileConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncContextEvalFileConstMeta => const TaskConstMeta( debugName: "JsAsyncContext_eval_file", argNames: ["that", "path"], ); @override - Future crateApiJsJsAsyncContextEvalFileWithOptions( + Future crateApiRuntimeJsAsyncContextEvalFileWithOptions( {required JsAsyncContext that, required String path, required JsEvalOptions options}) { @@ -416,20 +491,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncContextEvalFileWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextEvalFileWithOptionsConstMeta, argValues: [that, path, options], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextEvalFileWithOptionsConstMeta => - const TaskConstMeta( - debugName: "JsAsyncContext_eval_file_with_options", - argNames: ["that", "path", "options"], - ); + TaskConstMeta + get kCrateApiRuntimeJsAsyncContextEvalFileWithOptionsConstMeta => + const TaskConstMeta( + debugName: "JsAsyncContext_eval_file_with_options", + argNames: ["that", "path", "options"], + ); @override - Future crateApiJsJsAsyncContextEvalFunction( + Future crateApiRuntimeJsAsyncContextEvalFunction( {required JsAsyncContext that, required String module, required String method, @@ -449,20 +525,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncContextEvalFunctionConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextEvalFunctionConstMeta, argValues: [that, module, method, params], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextEvalFunctionConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncContextEvalFunctionConstMeta => const TaskConstMeta( debugName: "JsAsyncContext_eval_function", argNames: ["that", "module", "method", "params"], ); @override - Future crateApiJsJsAsyncContextEvalWithOptions( + Future crateApiRuntimeJsAsyncContextEvalWithOptions( {required JsAsyncContext that, required String code, required JsEvalOptions options}) { @@ -480,20 +556,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncContextEvalWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextEvalWithOptionsConstMeta, argValues: [that, code, options], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextEvalWithOptionsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncContextEvalWithOptionsConstMeta => const TaskConstMeta( debugName: "JsAsyncContext_eval_with_options", argNames: ["that", "code", "options"], ); @override - Future crateApiJsJsAsyncContextFrom( + Future crateApiRuntimeJsAsyncContextFrom( {required JsAsyncRuntime rt}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -508,20 +584,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsAsyncContext, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsAsyncContextFromConstMeta, + constMeta: kCrateApiRuntimeJsAsyncContextFromConstMeta, argValues: [rt], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncContextFromConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncContextFromConstMeta => const TaskConstMeta( debugName: "JsAsyncContext_from", argNames: ["rt"], ); @override - Future crateApiJsJsAsyncRuntimeExecutePendingJob( + Future crateApiRuntimeJsAsyncRuntimeExecutePendingJob( {required JsAsyncRuntime that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -535,20 +611,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsAsyncRuntimeExecutePendingJobConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeExecutePendingJobConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeExecutePendingJobConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeExecutePendingJobConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_execute_pending_job", argNames: ["that"], ); @override - Future crateApiJsJsAsyncRuntimeIdle({required JsAsyncRuntime that}) { + Future crateApiRuntimeJsAsyncRuntimeIdle( + {required JsAsyncRuntime that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -561,20 +638,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeIdleConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeIdleConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeIdleConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeIdleConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_idle", argNames: ["that"], ); @override - Future crateApiJsJsAsyncRuntimeIsJobPending( + Future crateApiRuntimeJsAsyncRuntimeIsJobPending( {required JsAsyncRuntime that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -588,20 +665,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeIsJobPendingConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeIsJobPendingConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeIsJobPendingConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeIsJobPendingConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_is_job_pending", argNames: ["that"], ); @override - Future crateApiJsJsAsyncRuntimeMemoryUsage( + Future crateApiRuntimeJsAsyncRuntimeMemoryUsage( {required JsAsyncRuntime that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -616,20 +693,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMemoryUsage, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeMemoryUsageConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeMemoryUsageConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeMemoryUsageConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeMemoryUsageConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_memory_usage", argNames: ["that"], ); @override - JsAsyncRuntime crateApiJsJsAsyncRuntimeNew() { + JsAsyncRuntime crateApiRuntimeJsAsyncRuntimeNew() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -640,20 +717,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsAsyncRuntime, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsAsyncRuntimeNewConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeNewConstMeta, argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeNewConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeNewConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_new", argNames: [], ); @override - Future crateApiJsJsAsyncRuntimeRunGc({required JsAsyncRuntime that}) { + Future crateApiRuntimeJsAsyncRuntimeRunGc( + {required JsAsyncRuntime that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -666,20 +744,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeRunGcConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeRunGcConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeRunGcConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeRunGcConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_run_gc", argNames: ["that"], ); @override - Future crateApiJsJsAsyncRuntimeSetGcThreshold( + Future crateApiRuntimeJsAsyncRuntimeSetGcThreshold( {required JsAsyncRuntime that, required BigInt threshold}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -694,20 +772,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeSetGcThresholdConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeSetGcThresholdConstMeta, argValues: [that, threshold], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeSetGcThresholdConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeSetGcThresholdConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_set_gc_threshold", argNames: ["that", "threshold"], ); @override - Future crateApiJsJsAsyncRuntimeSetInfo( + Future crateApiRuntimeJsAsyncRuntimeSetInfo( {required JsAsyncRuntime that, required String info}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -722,20 +800,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsAsyncRuntimeSetInfoConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeSetInfoConstMeta, argValues: [that, info], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeSetInfoConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeSetInfoConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_set_info", argNames: ["that", "info"], ); @override - Future crateApiJsJsAsyncRuntimeSetMaxStackSize( + Future crateApiRuntimeJsAsyncRuntimeSetMaxStackSize( {required JsAsyncRuntime that, required BigInt limit}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -750,20 +828,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeSetMaxStackSizeConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeSetMaxStackSizeConstMeta, argValues: [that, limit], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeSetMaxStackSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeSetMaxStackSizeConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_set_max_stack_size", argNames: ["that", "limit"], ); @override - Future crateApiJsJsAsyncRuntimeSetMemoryLimit( + Future crateApiRuntimeJsAsyncRuntimeSetMemoryLimit( {required JsAsyncRuntime that, required BigInt limit}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -778,20 +856,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsAsyncRuntimeSetMemoryLimitConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeSetMemoryLimitConstMeta, argValues: [that, limit], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeSetMemoryLimitConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeSetMemoryLimitConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_set_memory_limit", argNames: ["that", "limit"], ); @override - Future crateApiJsJsAsyncRuntimeWithOptions( + Future crateApiRuntimeJsAsyncRuntimeWithOptions( {JsBuiltinOptions? builtin, List? additional}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -806,20 +884,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsAsyncRuntime, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsAsyncRuntimeWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsAsyncRuntimeWithOptionsConstMeta, argValues: [builtin, additional], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsAsyncRuntimeWithOptionsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsAsyncRuntimeWithOptionsConstMeta => const TaskConstMeta( debugName: "JsAsyncRuntime_with_options", argNames: ["builtin", "additional"], ); @override - JsResult crateApiJsJsContextEval( + JsResult crateApiRuntimeJsContextEval( {required JsContext that, required String code}) { return handler.executeSync(SyncTask( callFfi: () { @@ -833,19 +911,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsContextEvalConstMeta, + constMeta: kCrateApiRuntimeJsContextEvalConstMeta, argValues: [that, code], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsContextEvalConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiRuntimeJsContextEvalConstMeta => + const TaskConstMeta( debugName: "JsContext_eval", argNames: ["that", "code"], ); @override - JsResult crateApiJsJsContextEvalFile( + JsResult crateApiRuntimeJsContextEvalFile( {required JsContext that, required String path}) { return handler.executeSync(SyncTask( callFfi: () { @@ -859,20 +938,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsContextEvalFileConstMeta, + constMeta: kCrateApiRuntimeJsContextEvalFileConstMeta, argValues: [that, path], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsContextEvalFileConstMeta => + TaskConstMeta get kCrateApiRuntimeJsContextEvalFileConstMeta => const TaskConstMeta( debugName: "JsContext_eval_file", argNames: ["that", "path"], ); @override - JsResult crateApiJsJsContextEvalFileWithOptions( + JsResult crateApiRuntimeJsContextEvalFileWithOptions( {required JsContext that, required String path, required JsEvalOptions options}) { @@ -889,20 +968,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsContextEvalFileWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsContextEvalFileWithOptionsConstMeta, argValues: [that, path, options], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsContextEvalFileWithOptionsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsContextEvalFileWithOptionsConstMeta => const TaskConstMeta( debugName: "JsContext_eval_file_with_options", argNames: ["that", "path", "options"], ); @override - JsResult crateApiJsJsContextEvalWithOptions( + JsResult crateApiRuntimeJsContextEvalWithOptions( {required JsContext that, required String code, required JsEvalOptions options}) { @@ -919,20 +998,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_js_result, decodeErrorData: null, ), - constMeta: kCrateApiJsJsContextEvalWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsContextEvalWithOptionsConstMeta, argValues: [that, code, options], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsContextEvalWithOptionsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsContextEvalWithOptionsConstMeta => const TaskConstMeta( debugName: "JsContext_eval_with_options", argNames: ["that", "code", "options"], ); @override - JsContext crateApiJsJsContextNew({required JsRuntime rt}) { + JsContext crateApiRuntimeJsContextNew({required JsRuntime rt}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -945,19 +1024,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsContext, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsContextNewConstMeta, + constMeta: kCrateApiRuntimeJsContextNewConstMeta, argValues: [rt], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsContextNewConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiRuntimeJsContextNewConstMeta => + const TaskConstMeta( debugName: "JsContext_new", argNames: ["rt"], ); @override - JsAsyncContext crateApiJsJsEngineCoreContext({required JsEngineCore that}) { + JsAsyncContext crateApiEngineJsEngineCoreContext( + {required JsEngineCore that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -970,20 +1051,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsAsyncContext, decodeErrorData: null, ), - constMeta: kCrateApiJsJsEngineCoreContextConstMeta, + constMeta: kCrateApiEngineJsEngineCoreContextConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreContextConstMeta => + TaskConstMeta get kCrateApiEngineJsEngineCoreContextConstMeta => const TaskConstMeta( debugName: "JsEngineCore_context", argNames: ["that"], ); @override - Future crateApiJsJsEngineCoreDispose({required JsEngineCore that}) { + Future crateApiEngineJsEngineCoreDispose({required JsEngineCore that}) { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -996,20 +1077,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsEngineCoreDisposeConstMeta, + constMeta: kCrateApiEngineJsEngineCoreDisposeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreDisposeConstMeta => + TaskConstMeta get kCrateApiEngineJsEngineCoreDisposeConstMeta => const TaskConstMeta( debugName: "JsEngineCore_dispose", argNames: ["that"], ); @override - bool crateApiJsJsEngineCoreDisposed({required JsEngineCore that}) { + bool crateApiEngineJsEngineCoreDisposed({required JsEngineCore that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1021,20 +1102,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsEngineCoreDisposedConstMeta, + constMeta: kCrateApiEngineJsEngineCoreDisposedConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreDisposedConstMeta => + TaskConstMeta get kCrateApiEngineJsEngineCoreDisposedConstMeta => const TaskConstMeta( debugName: "JsEngineCore_disposed", argNames: ["that"], ); @override - Future crateApiJsJsEngineCoreExec( + Future crateApiEngineJsEngineCoreExec( {required JsEngineCore that, required JsAction action}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -1049,19 +1130,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsEngineCoreExecConstMeta, + constMeta: kCrateApiEngineJsEngineCoreExecConstMeta, argValues: [that, action], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreExecConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiEngineJsEngineCoreExecConstMeta => + const TaskConstMeta( debugName: "JsEngineCore_exec", argNames: ["that", "action"], ); @override - JsEngineCore crateApiJsJsEngineCoreNew({required JsAsyncContext context}) { + JsEngineCore crateApiEngineJsEngineCoreNew( + {required JsAsyncContext context}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1074,19 +1157,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsEngineCore, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsEngineCoreNewConstMeta, + constMeta: kCrateApiEngineJsEngineCoreNewConstMeta, argValues: [context], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreNewConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiEngineJsEngineCoreNewConstMeta => + const TaskConstMeta( debugName: "JsEngineCore_new", argNames: ["context"], ); @override - bool crateApiJsJsEngineCoreRunning({required JsEngineCore that}) { + bool crateApiEngineJsEngineCoreRunning({required JsEngineCore that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1098,20 +1182,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsEngineCoreRunningConstMeta, + constMeta: kCrateApiEngineJsEngineCoreRunningConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreRunningConstMeta => + TaskConstMeta get kCrateApiEngineJsEngineCoreRunningConstMeta => const TaskConstMeta( debugName: "JsEngineCore_running", argNames: ["that"], ); @override - Future crateApiJsJsEngineCoreStart( + Future crateApiEngineJsEngineCoreStart( {required JsEngineCore that, required FutureOr Function(JsCallback) bridge}) { return handler.executeNormal(NormalTask( @@ -1128,20 +1212,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsEngineCoreStartConstMeta, + constMeta: kCrateApiEngineJsEngineCoreStartConstMeta, argValues: [that, bridge], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEngineCoreStartConstMeta => + TaskConstMeta get kCrateApiEngineJsEngineCoreStartConstMeta => const TaskConstMeta( debugName: "JsEngineCore_start", argNames: ["that", "bridge"], ); @override - bool crateApiJsJsRuntimeExecutePendingJob({required JsRuntime that}) { + bool crateApiRuntimeJsRuntimeExecutePendingJob({required JsRuntime that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1153,20 +1237,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsRuntimeExecutePendingJobConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeExecutePendingJobConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeExecutePendingJobConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeExecutePendingJobConstMeta => const TaskConstMeta( debugName: "JsRuntime_execute_pending_job", argNames: ["that"], ); @override - bool crateApiJsJsRuntimeIsJobPending({required JsRuntime that}) { + bool crateApiRuntimeJsRuntimeIsJobPending({required JsRuntime that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1178,20 +1262,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeIsJobPendingConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeIsJobPendingConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeIsJobPendingConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeIsJobPendingConstMeta => const TaskConstMeta( debugName: "JsRuntime_is_job_pending", argNames: ["that"], ); @override - MemoryUsage crateApiJsJsRuntimeMemoryUsage({required JsRuntime that}) { + MemoryUsage crateApiRuntimeJsRuntimeMemoryUsage({required JsRuntime that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1204,20 +1288,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMemoryUsage, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeMemoryUsageConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeMemoryUsageConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeMemoryUsageConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeMemoryUsageConstMeta => const TaskConstMeta( debugName: "JsRuntime_memory_usage", argNames: ["that"], ); @override - JsRuntime crateApiJsJsRuntimeNew() { + JsRuntime crateApiRuntimeJsRuntimeNew() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1228,19 +1312,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsRuntime, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsRuntimeNewConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeNewConstMeta, argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeNewConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiRuntimeJsRuntimeNewConstMeta => + const TaskConstMeta( debugName: "JsRuntime_new", argNames: [], ); @override - void crateApiJsJsRuntimeRunGc({required JsRuntime that}) { + void crateApiRuntimeJsRuntimeRunGc({required JsRuntime that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1252,19 +1337,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeRunGcConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeRunGcConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeRunGcConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiRuntimeJsRuntimeRunGcConstMeta => + const TaskConstMeta( debugName: "JsRuntime_run_gc", argNames: ["that"], ); @override - void crateApiJsJsRuntimeSetDumpFlags( + void crateApiRuntimeJsRuntimeSetDumpFlags( {required JsRuntime that, required BigInt flags}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1278,20 +1364,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeSetDumpFlagsConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeSetDumpFlagsConstMeta, argValues: [that, flags], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeSetDumpFlagsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeSetDumpFlagsConstMeta => const TaskConstMeta( debugName: "JsRuntime_set_dump_flags", argNames: ["that", "flags"], ); @override - void crateApiJsJsRuntimeSetGcThreshold( + void crateApiRuntimeJsRuntimeSetGcThreshold( {required JsRuntime that, required BigInt threshold}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1305,20 +1391,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeSetGcThresholdConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeSetGcThresholdConstMeta, argValues: [that, threshold], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeSetGcThresholdConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeSetGcThresholdConstMeta => const TaskConstMeta( debugName: "JsRuntime_set_gc_threshold", argNames: ["that", "threshold"], ); @override - void crateApiJsJsRuntimeSetInfo( + void crateApiRuntimeJsRuntimeSetInfo( {required JsRuntime that, required String info}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1332,19 +1418,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsRuntimeSetInfoConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeSetInfoConstMeta, argValues: [that, info], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeSetInfoConstMeta => const TaskConstMeta( + TaskConstMeta get kCrateApiRuntimeJsRuntimeSetInfoConstMeta => + const TaskConstMeta( debugName: "JsRuntime_set_info", argNames: ["that", "info"], ); @override - void crateApiJsJsRuntimeSetMaxStackSize( + void crateApiRuntimeJsRuntimeSetMaxStackSize( {required JsRuntime that, required BigInt limit}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1358,20 +1445,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeSetMaxStackSizeConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeSetMaxStackSizeConstMeta, argValues: [that, limit], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeSetMaxStackSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeSetMaxStackSizeConstMeta => const TaskConstMeta( debugName: "JsRuntime_set_max_stack_size", argNames: ["that", "limit"], ); @override - void crateApiJsJsRuntimeSetMemoryLimit( + void crateApiRuntimeJsRuntimeSetMemoryLimit( {required JsRuntime that, required BigInt limit}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1385,20 +1472,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_unit, decodeErrorData: null, ), - constMeta: kCrateApiJsJsRuntimeSetMemoryLimitConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeSetMemoryLimitConstMeta, argValues: [that, limit], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeSetMemoryLimitConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeSetMemoryLimitConstMeta => const TaskConstMeta( debugName: "JsRuntime_set_memory_limit", argNames: ["that", "limit"], ); @override - Future crateApiJsJsRuntimeWithOptions( + Future crateApiRuntimeJsRuntimeWithOptions( {JsBuiltinOptions? builtin, List? additional}) { return handler.executeNormal(NormalTask( callFfi: (port_) { @@ -1413,20 +1500,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerJsRuntime, decodeErrorData: sse_decode_AnyhowException, ), - constMeta: kCrateApiJsJsRuntimeWithOptionsConstMeta, + constMeta: kCrateApiRuntimeJsRuntimeWithOptionsConstMeta, argValues: [builtin, additional], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsRuntimeWithOptionsConstMeta => + TaskConstMeta get kCrateApiRuntimeJsRuntimeWithOptionsConstMeta => const TaskConstMeta( debugName: "JsRuntime_with_options", argNames: ["builtin", "additional"], ); @override - PlatformInt64 crateApiJsMemoryUsageArrayCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageArrayCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1438,20 +1526,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageArrayCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageArrayCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageArrayCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageArrayCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_array_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageAtomCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageAtomCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1463,20 +1552,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageAtomCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageAtomCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageAtomCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageAtomCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_atom_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageAtomSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageAtomSize( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1488,20 +1578,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageAtomSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageAtomSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageAtomSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageAtomSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_atom_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageBinaryObjectCount( + PlatformInt64 crateApiRuntimeMemoryUsageBinaryObjectCount( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1514,20 +1604,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageBinaryObjectCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageBinaryObjectCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageBinaryObjectCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageBinaryObjectCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_binary_object_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageBinaryObjectSize( + PlatformInt64 crateApiRuntimeMemoryUsageBinaryObjectSize( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1540,20 +1630,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageBinaryObjectSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageBinaryObjectSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageBinaryObjectSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageBinaryObjectSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_binary_object_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageCFuncCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageCFuncCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1565,20 +1656,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageCFuncCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageCFuncCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageCFuncCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageCFuncCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_c_func_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageFastArrayCount( + PlatformInt64 crateApiRuntimeMemoryUsageFastArrayCount( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1591,20 +1682,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageFastArrayCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageFastArrayCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageFastArrayCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageFastArrayCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_fast_array_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageFastArrayElements( + PlatformInt64 crateApiRuntimeMemoryUsageFastArrayElements( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1617,20 +1708,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageFastArrayElementsConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageFastArrayElementsConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageFastArrayElementsConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageFastArrayElementsConstMeta => const TaskConstMeta( debugName: "MemoryUsage_fast_array_elements", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageJsFuncCodeSize( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncCodeSize( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1643,20 +1734,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageJsFuncCodeSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageJsFuncCodeSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageJsFuncCodeSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageJsFuncCodeSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_js_func_code_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageJsFuncCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1668,20 +1760,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageJsFuncCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageJsFuncCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageJsFuncCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageJsFuncCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_js_func_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageJsFuncPc2LineCount( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncPc2LineCount( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1694,20 +1786,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageJsFuncPc2LineCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageJsFuncPc2LineCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageJsFuncPc2LineCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageJsFuncPc2LineCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_js_func_pc2line_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageJsFuncPc2LineSize( + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncPc2LineSize( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1720,20 +1812,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageJsFuncPc2LineSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageJsFuncPc2LineSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageJsFuncPc2LineSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageJsFuncPc2LineSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_js_func_pc2line_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageJsFuncSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageJsFuncSize( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1745,20 +1838,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageJsFuncSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageJsFuncSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageJsFuncSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageJsFuncSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_js_func_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageMallocCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageMallocCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1770,20 +1864,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageMallocCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageMallocCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageMallocCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageMallocCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_malloc_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageMallocLimit({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageMallocLimit( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1795,20 +1890,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageMallocLimitConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageMallocLimitConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageMallocLimitConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageMallocLimitConstMeta => const TaskConstMeta( debugName: "MemoryUsage_malloc_limit", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageMallocSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageMallocSize( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1820,20 +1916,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageMallocSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageMallocSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageMallocSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageMallocSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_malloc_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageMemoryUsedCount( + PlatformInt64 crateApiRuntimeMemoryUsageMemoryUsedCount( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1846,20 +1942,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageMemoryUsedCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageMemoryUsedCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageMemoryUsedCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageMemoryUsedCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_memory_used_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageMemoryUsedSize( + PlatformInt64 crateApiRuntimeMemoryUsageMemoryUsedSize( {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { @@ -1872,20 +1968,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageMemoryUsedSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageMemoryUsedSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageMemoryUsedSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageMemoryUsedSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_memory_used_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageObjCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageObjCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1897,20 +1994,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageObjCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageObjCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageObjCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageObjCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_obj_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageObjSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageObjSize({required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1922,20 +2019,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageObjSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageObjSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageObjSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageObjSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_obj_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsagePropCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsagePropCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1947,20 +2045,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsagePropCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsagePropCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsagePropCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsagePropCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_prop_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsagePropSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsagePropSize( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1972,20 +2071,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsagePropSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsagePropSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsagePropSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsagePropSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_prop_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageShapeCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageShapeCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -1997,20 +2097,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageShapeCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageShapeCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageShapeCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageShapeCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_shape_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageShapeSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageShapeSize( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -2022,20 +2123,21 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageShapeSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageShapeSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageShapeSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageShapeSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_shape_size", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageStrCount({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageStrCount( + {required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -2047,20 +2149,20 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageStrCountConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageStrCountConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageStrCountConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageStrCountConstMeta => const TaskConstMeta( debugName: "MemoryUsage_str_count", argNames: ["that"], ); @override - PlatformInt64 crateApiJsMemoryUsageStrSize({required MemoryUsage that}) { + PlatformInt64 crateApiRuntimeMemoryUsageStrSize({required MemoryUsage that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); @@ -2072,25 +2174,102 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { decodeSuccessData: sse_decode_i_64, decodeErrorData: null, ), - constMeta: kCrateApiJsMemoryUsageStrSizeConstMeta, + constMeta: kCrateApiRuntimeMemoryUsageStrSizeConstMeta, argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsMemoryUsageStrSizeConstMeta => + TaskConstMeta get kCrateApiRuntimeMemoryUsageStrSizeConstMeta => const TaskConstMeta( debugName: "MemoryUsage_str_size", argNames: ["that"], ); + @override + String crateApiRuntimeMemoryUsageSummary({required MemoryUsage that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMemoryUsage( + that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 67)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiRuntimeMemoryUsageSummaryConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiRuntimeMemoryUsageSummaryConstMeta => + const TaskConstMeta( + debugName: "MemoryUsage_summary", + argNames: ["that"], + ); + + @override + PlatformInt64 crateApiRuntimeMemoryUsageTotalAllocations( + {required MemoryUsage that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMemoryUsage( + that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 68)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_i_64, + decodeErrorData: null, + ), + constMeta: kCrateApiRuntimeMemoryUsageTotalAllocationsConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiRuntimeMemoryUsageTotalAllocationsConstMeta => + const TaskConstMeta( + debugName: "MemoryUsage_total_allocations", + argNames: ["that"], + ); + + @override + PlatformInt64 crateApiRuntimeMemoryUsageTotalMemory( + {required MemoryUsage that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerMemoryUsage( + that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 69)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_i_64, + decodeErrorData: null, + ), + constMeta: kCrateApiRuntimeMemoryUsageTotalMemoryConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiRuntimeMemoryUsageTotalMemoryConstMeta => + const TaskConstMeta( + debugName: "MemoryUsage_total_memory", + argNames: ["that"], + ); + @override Future crateApiInitApp() { return handler.executeNormal(NormalTask( callFfi: (port_) { final serializer = SseSerializer(generalizedFrbRustBinding); pdeCallFfi(generalizedFrbRustBinding, serializer, - funcId: 67, port: port_); + funcId: 70, port: port_); }, codec: SseCodec( decodeSuccessData: sse_decode_unit, @@ -2108,176 +2287,769 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { ); @override - JsBuiltinOptions crateApiJsJsBuiltinOptionsAll() { + JsBuiltinOptions crateApiSourceJsBuiltinOptionsAll() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 68)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 71)!; }, codec: SseCodec( decodeSuccessData: sse_decode_js_builtin_options, decodeErrorData: null, ), - constMeta: kCrateApiJsJsBuiltinOptionsAllConstMeta, + constMeta: kCrateApiSourceJsBuiltinOptionsAllConstMeta, argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsBuiltinOptionsAllConstMeta => + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsAllConstMeta => const TaskConstMeta( debugName: "js_builtin_options_all", argNames: [], ); @override - String crateApiJsJsErrorToString({required JsError that}) { + Future crateApiSourceJsBuiltinOptionsDefault() { + return handler.executeNormal(NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi(generalizedFrbRustBinding, serializer, + funcId: 72, port: port_); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_builtin_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsBuiltinOptionsDefaultConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsDefaultConstMeta => + const TaskConstMeta( + debugName: "js_builtin_options_default", + argNames: [], + ); + + @override + JsBuiltinOptions crateApiSourceJsBuiltinOptionsEssential() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_box_autoadd_js_error(that, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 69)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 73)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_String, + decodeSuccessData: sse_decode_js_builtin_options, decodeErrorData: null, ), - constMeta: kCrateApiJsJsErrorToStringConstMeta, - argValues: [that], + constMeta: kCrateApiSourceJsBuiltinOptionsEssentialConstMeta, + argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsErrorToStringConstMeta => const TaskConstMeta( - debugName: "js_error_to_string", - argNames: ["that"], + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsEssentialConstMeta => + const TaskConstMeta( + debugName: "js_builtin_options_essential", + argNames: [], ); @override - JsEvalOptions crateApiJsJsEvalOptionsNew( - {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}) { + JsBuiltinOptions crateApiSourceJsBuiltinOptionsNode() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_opt_box_autoadd_bool(global, serializer); - sse_encode_opt_box_autoadd_bool(strict, serializer); - sse_encode_opt_box_autoadd_bool(backtraceBarrier, serializer); - sse_encode_opt_box_autoadd_bool(promise, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 70)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 74)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_js_eval_options, + decodeSuccessData: sse_decode_js_builtin_options, decodeErrorData: null, ), - constMeta: kCrateApiJsJsEvalOptionsNewConstMeta, - argValues: [global, strict, backtraceBarrier, promise], + constMeta: kCrateApiSourceJsBuiltinOptionsNodeConstMeta, + argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsEvalOptionsNewConstMeta => const TaskConstMeta( - debugName: "js_eval_options_new", - argNames: ["global", "strict", "backtraceBarrier", "promise"], + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsNodeConstMeta => + const TaskConstMeta( + debugName: "js_builtin_options_node", + argNames: [], ); @override - JsModule crateApiJsJsModuleBytes( - {required String module, required List bytes}) { + JsBuiltinOptions crateApiSourceJsBuiltinOptionsNone() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(module, serializer); - sse_encode_list_prim_u_8_loose(bytes, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 71)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 75)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_js_module, + decodeSuccessData: sse_decode_js_builtin_options, decodeErrorData: null, ), - constMeta: kCrateApiJsJsModuleBytesConstMeta, - argValues: [module, bytes], + constMeta: kCrateApiSourceJsBuiltinOptionsNoneConstMeta, + argValues: [], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsModuleBytesConstMeta => const TaskConstMeta( - debugName: "js_module_bytes", - argNames: ["module", "bytes"], + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsNoneConstMeta => + const TaskConstMeta( + debugName: "js_builtin_options_none", + argNames: [], ); @override - JsModule crateApiJsJsModuleCode( - {required String module, required String code}) { + JsBuiltinOptions crateApiSourceJsBuiltinOptionsWeb() { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(module, serializer); - sse_encode_String(code, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 72)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 76)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_js_module, + decodeSuccessData: sse_decode_js_builtin_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsBuiltinOptionsWebConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsBuiltinOptionsWebConstMeta => + const TaskConstMeta( + debugName: "js_builtin_options_web", + argNames: [], + ); + + @override + bool crateApiSourceJsCodeIsBytes({required JsCode that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_code(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 77)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsCodeIsBytesConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsCodeIsBytesConstMeta => + const TaskConstMeta( + debugName: "js_code_is_bytes", + argNames: ["that"], + ); + + @override + bool crateApiSourceJsCodeIsCode({required JsCode that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_code(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 78)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsCodeIsCodeConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsCodeIsCodeConstMeta => const TaskConstMeta( + debugName: "js_code_is_code", + argNames: ["that"], + ); + + @override + bool crateApiSourceJsCodeIsPath({required JsCode that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_code(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 79)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsCodeIsPathConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsCodeIsPathConstMeta => const TaskConstMeta( + debugName: "js_code_is_path", + argNames: ["that"], + ); + + @override + String crateApiErrorJsErrorCode({required JsError that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_error(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 80)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiErrorJsErrorCodeConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiErrorJsErrorCodeConstMeta => const TaskConstMeta( + debugName: "js_error_code", + argNames: ["that"], + ); + + @override + bool crateApiErrorJsErrorIsRecoverable({required JsError that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_error(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 81)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiErrorJsErrorIsRecoverableConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiErrorJsErrorIsRecoverableConstMeta => + const TaskConstMeta( + debugName: "js_error_is_recoverable", + argNames: ["that"], + ); + + @override + String crateApiErrorJsErrorToString({required JsError that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_error(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 82)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: null, + ), + constMeta: kCrateApiErrorJsErrorToStringConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiErrorJsErrorToStringConstMeta => + const TaskConstMeta( + debugName: "js_error_to_string", + argNames: ["that"], + ); + + @override + Future crateApiSourceJsEvalOptionsDefault() { + return handler.executeNormal(NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi(generalizedFrbRustBinding, serializer, + funcId: 83, port: port_); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_eval_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsEvalOptionsDefaultConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsEvalOptionsDefaultConstMeta => + const TaskConstMeta( + debugName: "js_eval_options_default", + argNames: [], + ); + + @override + JsEvalOptions crateApiSourceJsEvalOptionsDefaults() { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 84)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_eval_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsEvalOptionsDefaultsConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsEvalOptionsDefaultsConstMeta => + const TaskConstMeta( + debugName: "js_eval_options_defaults", + argNames: [], + ); + + @override + JsEvalOptions crateApiSourceJsEvalOptionsModule() { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 85)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_eval_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsEvalOptionsModuleConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsEvalOptionsModuleConstMeta => + const TaskConstMeta( + debugName: "js_eval_options_module", + argNames: [], + ); + + @override + JsEvalOptions crateApiSourceJsEvalOptionsNew( + {bool? global, bool? strict, bool? backtraceBarrier, bool? promise}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_opt_box_autoadd_bool(global, serializer); + sse_encode_opt_box_autoadd_bool(strict, serializer); + sse_encode_opt_box_autoadd_bool(backtraceBarrier, serializer); + sse_encode_opt_box_autoadd_bool(promise, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 86)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_eval_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsEvalOptionsNewConstMeta, + argValues: [global, strict, backtraceBarrier, promise], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsEvalOptionsNewConstMeta => + const TaskConstMeta( + debugName: "js_eval_options_new", + argNames: ["global", "strict", "backtraceBarrier", "promise"], + ); + + @override + JsEvalOptions crateApiSourceJsEvalOptionsWithPromise() { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 87)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_eval_options, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsEvalOptionsWithPromiseConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsEvalOptionsWithPromiseConstMeta => + const TaskConstMeta( + debugName: "js_eval_options_with_promise", + argNames: [], + ); + + @override + JsModule crateApiSourceJsModuleFromBytes( + {required String module, required List bytes}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(module, serializer); + sse_encode_list_prim_u_8_loose(bytes, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 88)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_module, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsModuleFromBytesConstMeta, + argValues: [module, bytes], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsModuleFromBytesConstMeta => + const TaskConstMeta( + debugName: "js_module_from_bytes(dart_style=fromBytes)", + argNames: ["module", "bytes"], + ); + + @override + JsModule crateApiSourceJsModuleFromCode( + {required String module, required String code}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(module, serializer); + sse_encode_String(code, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 89)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_module, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsModuleFromCodeConstMeta, + argValues: [module, code], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsModuleFromCodeConstMeta => + const TaskConstMeta( + debugName: "js_module_from_code(dart_style=fromCode)", + argNames: ["module", "code"], + ); + + @override + JsModule crateApiSourceJsModuleFromPath( + {required String module, required String path}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(module, serializer); + sse_encode_String(path, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 90)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_module, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsModuleFromPathConstMeta, + argValues: [module, path], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsModuleFromPathConstMeta => + const TaskConstMeta( + debugName: "js_module_from_path(dart_style=fromPath)", + argNames: ["module", "path"], + ); + + @override + JsModule crateApiSourceJsModuleNew( + {required String name, required JsCode source}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_String(name, serializer); + sse_encode_box_autoadd_js_code(source, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 91)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_module, + decodeErrorData: null, + ), + constMeta: kCrateApiSourceJsModuleNewConstMeta, + argValues: [name, source], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiSourceJsModuleNewConstMeta => const TaskConstMeta( + debugName: "js_module_new", + argNames: ["name", "source"], + ); + + @override + Future crateApiValueJsValueDefault() { + return handler.executeNormal(NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + pdeCallFfi(generalizedFrbRustBinding, serializer, + funcId: 92, port: port_); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_js_value, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueDefaultConstMeta, + argValues: [], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueDefaultConstMeta => + const TaskConstMeta( + debugName: "js_value_default", + argNames: [], + ); + + @override + bool crateApiValueJsValueIsArray({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 93)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsArrayConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsArrayConstMeta => + const TaskConstMeta( + debugName: "js_value_is_array", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsBoolean({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 94)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsBooleanConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsBooleanConstMeta => + const TaskConstMeta( + debugName: "js_value_is_boolean", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsBytes({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 95)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsBytesConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsBytesConstMeta => + const TaskConstMeta( + debugName: "js_value_is_bytes", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsDate({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 96)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsDateConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsDateConstMeta => const TaskConstMeta( + debugName: "js_value_is_date", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsNone({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 97)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsNoneConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsNoneConstMeta => const TaskConstMeta( + debugName: "js_value_is_none", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsNumber({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 98)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsNumberConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsNumberConstMeta => + const TaskConstMeta( + debugName: "js_value_is_number", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsObject({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 99)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, + decodeErrorData: null, + ), + constMeta: kCrateApiValueJsValueIsObjectConstMeta, + argValues: [that], + apiImpl: this, + )); + } + + TaskConstMeta get kCrateApiValueJsValueIsObjectConstMeta => + const TaskConstMeta( + debugName: "js_value_is_object", + argNames: ["that"], + ); + + @override + bool crateApiValueJsValueIsPrimitive({required JsValue that}) { + return handler.executeSync(SyncTask( + callFfi: () { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 100)!; + }, + codec: SseCodec( + decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsModuleCodeConstMeta, - argValues: [module, code], + constMeta: kCrateApiValueJsValueIsPrimitiveConstMeta, + argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsModuleCodeConstMeta => const TaskConstMeta( - debugName: "js_module_code", - argNames: ["module", "code"], + TaskConstMeta get kCrateApiValueJsValueIsPrimitiveConstMeta => + const TaskConstMeta( + debugName: "js_value_is_primitive", + argNames: ["that"], ); @override - JsModule crateApiJsJsModuleNew( - {required String name, required JsCode source}) { + bool crateApiValueJsValueIsString({required JsValue that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(name, serializer); - sse_encode_box_autoadd_js_code(source, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 73)!; + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 101)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_js_module, + decodeSuccessData: sse_decode_bool, decodeErrorData: null, ), - constMeta: kCrateApiJsJsModuleNewConstMeta, - argValues: [name, source], + constMeta: kCrateApiValueJsValueIsStringConstMeta, + argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsModuleNewConstMeta => const TaskConstMeta( - debugName: "js_module_new", - argNames: ["name", "source"], + TaskConstMeta get kCrateApiValueJsValueIsStringConstMeta => + const TaskConstMeta( + debugName: "js_value_is_string", + argNames: ["that"], ); @override - JsModule crateApiJsJsModulePath( - {required String module, required String path}) { + String crateApiValueJsValueTypeName({required JsValue that}) { return handler.executeSync(SyncTask( callFfi: () { final serializer = SseSerializer(generalizedFrbRustBinding); - sse_encode_String(module, serializer); - sse_encode_String(path, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 74)!; + sse_encode_box_autoadd_js_value(that, serializer); + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 102)!; }, codec: SseCodec( - decodeSuccessData: sse_decode_js_module, + decodeSuccessData: sse_decode_String, decodeErrorData: null, ), - constMeta: kCrateApiJsJsModulePathConstMeta, - argValues: [module, path], + constMeta: kCrateApiValueJsValueTypeNameConstMeta, + argValues: [that], apiImpl: this, )); } - TaskConstMeta get kCrateApiJsJsModulePathConstMeta => const TaskConstMeta( - debugName: "js_module_path", - argNames: ["module", "path"], + TaskConstMeta get kCrateApiValueJsValueTypeNameConstMeta => + const TaskConstMeta( + debugName: "js_value_type_name", + argNames: ["that"], ); Future Function(int, dynamic) @@ -2604,6 +3376,12 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { return dco_decode_js_value(raw); } + @protected + int dco_decode_box_autoadd_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw as int; + } + @protected double dco_decode_f_64(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2660,6 +3438,13 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { id: dco_decode_u_32(raw[1]), moduleName: dco_decode_String(raw[2]), ); + case 7: + return JsAction_CallFunction( + id: dco_decode_u_32(raw[1]), + module: dco_decode_String(raw[2]), + method: dco_decode_String(raw[3]), + params: dco_decode_opt_list_js_value(raw[4]), + ); default: throw Exception("unreachable"); } @@ -2813,6 +3598,44 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { return JsError_Bridge( dco_decode_String(raw[1]), ); + case 9: + return JsError_Conversion( + from: dco_decode_String(raw[1]), + to: dco_decode_String(raw[2]), + message: dco_decode_String(raw[3]), + ); + case 10: + return JsError_Timeout( + operation: dco_decode_String(raw[1]), + timeoutMs: dco_decode_u_64(raw[2]), + ); + case 11: + return JsError_MemoryLimit( + current: dco_decode_u_64(raw[1]), + limit: dco_decode_u_64(raw[2]), + ); + case 12: + return JsError_StackOverflow( + dco_decode_String(raw[1]), + ); + case 13: + return JsError_Syntax( + line: dco_decode_opt_box_autoadd_u_32(raw[1]), + column: dco_decode_opt_box_autoadd_u_32(raw[2]), + message: dco_decode_String(raw[3]), + ); + case 14: + return JsError_Reference( + dco_decode_String(raw[1]), + ); + case 15: + return JsError_Type( + dco_decode_String(raw[1]), + ); + case 16: + return JsError_Cancelled( + dco_decode_String(raw[1]), + ); default: throw Exception("unreachable"); } @@ -2888,13 +3711,29 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { dco_decode_String(raw[1]), ); case 6: + return JsValue_Bytes( + dco_decode_list_prim_u_8_strict(raw[1]), + ); + case 7: return JsValue_Array( dco_decode_list_js_value(raw[1]), ); - case 7: + case 8: return JsValue_Object( dco_decode_Map_String_js_value_None(raw[1]), ); + case 9: + return JsValue_Date( + dco_decode_i_64(raw[1]), + ); + case 10: + return JsValue_Symbol( + dco_decode_String(raw[1]), + ); + case 11: + return JsValue_Function( + dco_decode_String(raw[1]), + ); default: throw Exception("unreachable"); } @@ -2956,6 +3795,12 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { return raw == null ? null : dco_decode_box_autoadd_js_eval_options(raw); } + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_u_32(raw); + } + @protected List? dco_decode_opt_list_js_module(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -3271,6 +4116,12 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { return (sse_decode_js_value(deserializer)); } + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_u_32(deserializer)); + } + @protected double sse_decode_f_64(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3325,6 +4176,16 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { var var_moduleName = sse_decode_String(deserializer); return JsAction_IsModuleDeclared( id: var_id, moduleName: var_moduleName); + case 7: + var var_id = sse_decode_u_32(deserializer); + var var_module = sse_decode_String(deserializer); + var var_method = sse_decode_String(deserializer); + var var_params = sse_decode_opt_list_js_value(deserializer); + return JsAction_CallFunction( + id: var_id, + module: var_module, + method: var_method, + params: var_params); default: throw UnimplementedError(''); } @@ -3490,6 +4351,39 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { case 8: var var_field0 = sse_decode_String(deserializer); return JsError_Bridge(var_field0); + case 9: + var var_from = sse_decode_String(deserializer); + var var_to = sse_decode_String(deserializer); + var var_message = sse_decode_String(deserializer); + return JsError_Conversion( + from: var_from, to: var_to, message: var_message); + case 10: + var var_operation = sse_decode_String(deserializer); + var var_timeoutMs = sse_decode_u_64(deserializer); + return JsError_Timeout( + operation: var_operation, timeoutMs: var_timeoutMs); + case 11: + var var_current = sse_decode_u_64(deserializer); + var var_limit = sse_decode_u_64(deserializer); + return JsError_MemoryLimit(current: var_current, limit: var_limit); + case 12: + var var_field0 = sse_decode_String(deserializer); + return JsError_StackOverflow(var_field0); + case 13: + var var_line = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_column = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_message = sse_decode_String(deserializer); + return JsError_Syntax( + line: var_line, column: var_column, message: var_message); + case 14: + var var_field0 = sse_decode_String(deserializer); + return JsError_Reference(var_field0); + case 15: + var var_field0 = sse_decode_String(deserializer); + return JsError_Type(var_field0); + case 16: + var var_field0 = sse_decode_String(deserializer); + return JsError_Cancelled(var_field0); default: throw UnimplementedError(''); } @@ -3558,11 +4452,23 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { var var_field0 = sse_decode_String(deserializer); return JsValue_String(var_field0); case 6: + var var_field0 = sse_decode_list_prim_u_8_strict(deserializer); + return JsValue_Bytes(var_field0); + case 7: var var_field0 = sse_decode_list_js_value(deserializer); return JsValue_Array(var_field0); - case 7: + case 8: var var_field0 = sse_decode_Map_String_js_value_None(deserializer); return JsValue_Object(var_field0); + case 9: + var var_field0 = sse_decode_i_64(deserializer); + return JsValue_Date(var_field0); + case 10: + var var_field0 = sse_decode_String(deserializer); + return JsValue_Symbol(var_field0); + case 11: + var var_field0 = sse_decode_String(deserializer); + return JsValue_Function(var_field0); default: throw UnimplementedError(''); } @@ -3665,6 +4571,17 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { } } + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_u_32(deserializer)); + } else { + return null; + } + } + @protected List? sse_decode_opt_list_js_module(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -4017,6 +4934,12 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_encode_js_value(self, serializer); } + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_u_32(self, serializer); + } + @protected void sse_encode_f_64(double self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -4073,6 +4996,17 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { sse_encode_i_32(6, serializer); sse_encode_u_32(id, serializer); sse_encode_String(moduleName, serializer); + case JsAction_CallFunction( + id: final id, + module: final module, + method: final method, + params: final params + ): + sse_encode_i_32(7, serializer); + sse_encode_u_32(id, serializer); + sse_encode_String(module, serializer); + sse_encode_String(method, serializer); + sse_encode_opt_list_js_value(params, serializer); } } @@ -4200,6 +5134,47 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { case JsError_Bridge(field0: final field0): sse_encode_i_32(8, serializer); sse_encode_String(field0, serializer); + case JsError_Conversion( + from: final from, + to: final to, + message: final message + ): + sse_encode_i_32(9, serializer); + sse_encode_String(from, serializer); + sse_encode_String(to, serializer); + sse_encode_String(message, serializer); + case JsError_Timeout( + operation: final operation, + timeoutMs: final timeoutMs + ): + sse_encode_i_32(10, serializer); + sse_encode_String(operation, serializer); + sse_encode_u_64(timeoutMs, serializer); + case JsError_MemoryLimit(current: final current, limit: final limit): + sse_encode_i_32(11, serializer); + sse_encode_u_64(current, serializer); + sse_encode_u_64(limit, serializer); + case JsError_StackOverflow(field0: final field0): + sse_encode_i_32(12, serializer); + sse_encode_String(field0, serializer); + case JsError_Syntax( + line: final line, + column: final column, + message: final message + ): + sse_encode_i_32(13, serializer); + sse_encode_opt_box_autoadd_u_32(line, serializer); + sse_encode_opt_box_autoadd_u_32(column, serializer); + sse_encode_String(message, serializer); + case JsError_Reference(field0: final field0): + sse_encode_i_32(14, serializer); + sse_encode_String(field0, serializer); + case JsError_Type(field0: final field0): + sse_encode_i_32(15, serializer); + sse_encode_String(field0, serializer); + case JsError_Cancelled(field0: final field0): + sse_encode_i_32(16, serializer); + sse_encode_String(field0, serializer); } } @@ -4254,12 +5229,24 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { case JsValue_String(field0: final field0): sse_encode_i_32(5, serializer); sse_encode_String(field0, serializer); - case JsValue_Array(field0: final field0): + case JsValue_Bytes(field0: final field0): sse_encode_i_32(6, serializer); + sse_encode_list_prim_u_8_strict(field0, serializer); + case JsValue_Array(field0: final field0): + sse_encode_i_32(7, serializer); sse_encode_list_js_value(field0, serializer); case JsValue_Object(field0: final field0): - sse_encode_i_32(7, serializer); + sse_encode_i_32(8, serializer); sse_encode_Map_String_js_value_None(field0, serializer); + case JsValue_Date(field0: final field0): + sse_encode_i_32(9, serializer); + sse_encode_i_64(field0, serializer); + case JsValue_Symbol(field0: final field0): + sse_encode_i_32(10, serializer); + sse_encode_String(field0, serializer); + case JsValue_Function(field0: final field0): + sse_encode_i_32(11, serializer); + sse_encode_String(field0, serializer); } } @@ -4351,6 +5338,16 @@ class LibFjsApiImpl extends LibFjsApiImplPlatform implements LibFjsApi { } } + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_u_32(self, serializer); + } + } + @protected void sse_encode_opt_list_js_module( List? self, SseSerializer serializer) { @@ -4436,101 +5433,32 @@ class JsAsyncContextImpl extends RustOpaque implements JsAsyncContext { LibFjs.instance.api.rust_arc_decrement_strong_count_JsAsyncContextPtr, ); - /// Evaluates JavaScript code with default options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string()).await?; - /// let async_result = context.eval("await Promise.resolve(42)".to_string()).await?; - /// ``` - Future eval({required String code}) => - LibFjs.instance.api.crateApiJsJsAsyncContextEval(that: this, code: code); - - /// Evaluates JavaScript code from a file with default options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. + /// Evaluates JavaScript code. + Future eval({required String code}) => LibFjs.instance.api + .crateApiRuntimeJsAsyncContextEval(that: this, code: code); + + /// Evaluates JavaScript code from a file. Future evalFile({required String path}) => LibFjs.instance.api - .crateApiJsJsAsyncContextEvalFile(that: this, path: path); + .crateApiRuntimeJsAsyncContextEvalFile(that: this, path: path); - /// Evaluates JavaScript code from a file with custom options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. + /// Evaluates JavaScript code from a file with options. Future evalFileWithOptions( {required String path, required JsEvalOptions options}) => - LibFjs.instance.api.crateApiJsJsAsyncContextEvalFileWithOptions( + LibFjs.instance.api.crateApiRuntimeJsAsyncContextEvalFileWithOptions( that: this, path: path, options: options); - /// Evaluates a specific function from a module asynchronously. - /// - /// # Parameters - /// - /// - `module`: The name of the module containing the function - /// - `method`: The name of the function to call - /// - `params`: Optional parameters to pass to the function - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval_function( - /// "my-module".to_string(), - /// "myFunction".to_string(), - /// Some(vec![JsValue::integer(42)]) - /// ).await?; - /// ``` + /// Evaluates a function from a module. Future evalFunction( {required String module, required String method, List? params}) => - LibFjs.instance.api.crateApiJsJsAsyncContextEvalFunction( + LibFjs.instance.api.crateApiRuntimeJsAsyncContextEvalFunction( that: this, module: module, method: method, params: params); - /// Evaluates JavaScript code with custom options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// This method supports promise evaluation and top-level await. + /// Evaluates JavaScript code with options. Future evalWithOptions( {required String code, required JsEvalOptions options}) => - LibFjs.instance.api.crateApiJsJsAsyncContextEvalWithOptions( + LibFjs.instance.api.crateApiRuntimeJsAsyncContextEvalWithOptions( that: this, code: code, options: options); } @@ -4553,89 +5481,51 @@ class JsAsyncRuntimeImpl extends RustOpaque implements JsAsyncRuntime { LibFjs.instance.api.rust_arc_decrement_strong_count_JsAsyncRuntimePtr, ); - /// Executes a pending job if one is available asynchronously. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. + /// Executes a pending job. Future executePendingJob() => - LibFjs.instance.api.crateApiJsJsAsyncRuntimeExecutePendingJob( + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeExecutePendingJob( that: this, ); - /// Puts the runtime into idle state, waiting for events. - /// - /// This method should be called when the runtime is not actively executing - /// JavaScript code but needs to remain responsive to events. - Future idle() => LibFjs.instance.api.crateApiJsJsAsyncRuntimeIdle( + /// Puts the runtime into idle state. + Future idle() => LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeIdle( that: this, ); - /// Checks if there are pending jobs to be executed asynchronously. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. + /// Checks if there are pending jobs. Future isJobPending() => - LibFjs.instance.api.crateApiJsJsAsyncRuntimeIsJobPending( + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeIsJobPending( that: this, ); - /// Returns the current memory usage statistics asynchronously. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. + /// Returns memory usage statistics. Future memoryUsage() => - LibFjs.instance.api.crateApiJsJsAsyncRuntimeMemoryUsage( + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeMemoryUsage( that: this, ); - /// Forces garbage collection to run immediately asynchronously. - Future runGc() => LibFjs.instance.api.crateApiJsJsAsyncRuntimeRunGc( + /// Forces garbage collection. + Future runGc() => + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeRunGc( that: this, ); - /// Sets the garbage collection threshold asynchronously. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes - Future setGcThreshold({required BigInt threshold}) => LibFjs - .instance.api - .crateApiJsJsAsyncRuntimeSetGcThreshold(that: this, threshold: threshold); + /// Sets the garbage collection threshold. + Future setGcThreshold({required BigInt threshold}) => + LibFjs.instance.api.crateApiRuntimeJsAsyncRuntimeSetGcThreshold( + that: this, threshold: threshold); - /// Sets runtime information for debugging purposes asynchronously. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. + /// Sets runtime info string. Future setInfo({required String info}) => LibFjs.instance.api - .crateApiJsJsAsyncRuntimeSetInfo(that: this, info: info); + .crateApiRuntimeJsAsyncRuntimeSetInfo(that: this, info: info); - /// Sets the maximum stack size for JavaScript execution asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes + /// Sets the maximum stack size. Future setMaxStackSize({required BigInt limit}) => LibFjs.instance.api - .crateApiJsJsAsyncRuntimeSetMaxStackSize(that: this, limit: limit); + .crateApiRuntimeJsAsyncRuntimeSetMaxStackSize(that: this, limit: limit); - /// Sets the memory limit for the runtime asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes + /// Sets the memory limit. Future setMemoryLimit({required BigInt limit}) => LibFjs.instance.api - .crateApiJsJsAsyncRuntimeSetMemoryLimit(that: this, limit: limit); + .crateApiRuntimeJsAsyncRuntimeSetMemoryLimit(that: this, limit: limit); } @sealed @@ -4657,77 +5547,24 @@ class JsContextImpl extends RustOpaque implements JsContext { LibFjs.instance.api.rust_arc_decrement_strong_count_JsContextPtr, ); - /// Evaluates JavaScript code with default options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string())?; - /// ``` + /// Evaluates JavaScript code. JsResult eval({required String code}) => - LibFjs.instance.api.crateApiJsJsContextEval(that: this, code: code); + LibFjs.instance.api.crateApiRuntimeJsContextEval(that: this, code: code); - /// Evaluates JavaScript code from a file with default options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. - JsResult evalFile({required String path}) => - LibFjs.instance.api.crateApiJsJsContextEvalFile(that: this, path: path); + /// Evaluates JavaScript code from a file. + JsResult evalFile({required String path}) => LibFjs.instance.api + .crateApiRuntimeJsContextEvalFile(that: this, path: path); - /// Evaluates JavaScript code from a file with custom options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. + /// Evaluates JavaScript code from a file with options. JsResult evalFileWithOptions( {required String path, required JsEvalOptions options}) => - LibFjs.instance.api.crateApiJsJsContextEvalFileWithOptions( + LibFjs.instance.api.crateApiRuntimeJsContextEvalFileWithOptions( that: this, path: path, options: options); - /// Evaluates JavaScript code with custom options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. - /// Use `JsAsyncContext` for asynchronous operations. + /// Evaluates JavaScript code with options. JsResult evalWithOptions( {required String code, required JsEvalOptions options}) => - LibFjs.instance.api.crateApiJsJsContextEvalWithOptions( + LibFjs.instance.api.crateApiRuntimeJsContextEvalWithOptions( that: this, code: code, options: options); } @@ -4750,92 +5587,37 @@ class JsEngineCoreImpl extends RustOpaque implements JsEngineCore { LibFjs.instance.api.rust_arc_decrement_strong_count_JsEngineCorePtr, ); - /// Returns the asynchronous context used by this engine. - /// - /// # Returns - /// - /// Returns the `JsAsyncContext` instance. + /// Returns the context. JsAsyncContext get context => - LibFjs.instance.api.crateApiJsJsEngineCoreContext( + LibFjs.instance.api.crateApiEngineJsEngineCoreContext( that: this, ); - /// Disposes the engine and cleans up resources. - /// - /// This method marks the engine as disposed and prevents further operations. - /// The actual cleanup happens when all references are dropped. - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed. - Future dispose() => LibFjs.instance.api.crateApiJsJsEngineCoreDispose( + /// Disposes the engine. + Future dispose() => + LibFjs.instance.api.crateApiEngineJsEngineCoreDispose( that: this, ); - /// Checks if the engine has been disposed. - /// - /// # Returns - /// - /// Returns `true` if the engine is disposed, `false` otherwise. - bool get disposed => LibFjs.instance.api.crateApiJsJsEngineCoreDisposed( + /// Returns whether the engine is disposed. + bool get disposed => LibFjs.instance.api.crateApiEngineJsEngineCoreDisposed( that: this, ); - /// Executes an action on the engine. - /// - /// # Parameters - /// - /// - `action`: The action to execute - /// - /// # Errors - /// - /// Returns an error if the engine is disposed or if sending the action fails. + /// Executes an action. Future exec({required JsAction action}) => LibFjs.instance.api - .crateApiJsJsEngineCoreExec(that: this, action: action); + .crateApiEngineJsEngineCoreExec(that: this, action: action); - /// Checks if the engine is currently running. - /// - /// # Returns - /// - /// Returns `true` if the engine is running, `false` otherwise. - bool get running => LibFjs.instance.api.crateApiJsJsEngineCoreRunning( + /// Returns whether the engine is running. + bool get running => LibFjs.instance.api.crateApiEngineJsEngineCoreRunning( that: this, ); - /// Starts the engine event loop with a bridge callback. - /// - /// # Parameters - /// - /// - `bridge`: Callback function for handling communication between JavaScript and Dart - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed or already running. - /// - /// # Examples - /// - /// ```rust - /// engine.start(|callback| { - /// match callback { - /// JsCallback::Initialized => { - /// println!("Engine initialized"); - /// JsCallbackResult::Initialized - /// } - /// JsCallback::Handler(result) => { - /// println!("Action completed: {:?}", result); - /// JsCallbackResult::Handler - /// } - /// JsCallback::Bridge(value) => { - /// println!("Bridge call: {:?}", value); - /// JsCallbackResult::Bridge(JsResult::Ok(value)) - /// } - /// } - /// }).await?; - /// ``` + /// Starts the engine event loop. Future start( {required FutureOr Function(JsCallback) bridge}) => LibFjs.instance.api - .crateApiJsJsEngineCoreStart(that: this, bridge: bridge); + .crateApiEngineJsEngineCoreStart(that: this, bridge: bridge); } @sealed @@ -4857,87 +5639,48 @@ class JsRuntimeImpl extends RustOpaque implements JsRuntime { LibFjs.instance.api.rust_arc_decrement_strong_count_JsRuntimePtr, ); - /// Executes a pending job if one is available. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. + /// Executes a pending job. bool executePendingJob() => - LibFjs.instance.api.crateApiJsJsRuntimeExecutePendingJob( + LibFjs.instance.api.crateApiRuntimeJsRuntimeExecutePendingJob( that: this, ); - /// Checks if there are pending jobs to be executed. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. - bool isJobPending() => LibFjs.instance.api.crateApiJsJsRuntimeIsJobPending( + /// Checks if there are pending jobs. + bool isJobPending() => + LibFjs.instance.api.crateApiRuntimeJsRuntimeIsJobPending( that: this, ); - /// Returns the current memory usage statistics. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. + /// Returns memory usage statistics. MemoryUsage memoryUsage() => - LibFjs.instance.api.crateApiJsJsRuntimeMemoryUsage( + LibFjs.instance.api.crateApiRuntimeJsRuntimeMemoryUsage( that: this, ); - /// Forces garbage collection to run immediately. - void runGc() => LibFjs.instance.api.crateApiJsJsRuntimeRunGc( + /// Forces garbage collection. + void runGc() => LibFjs.instance.api.crateApiRuntimeJsRuntimeRunGc( that: this, ); - /// Sets dump flags for debugging and profiling. - /// - /// # Parameters - /// - /// - `flags`: Bitmask of dump flags + /// Sets dump flags for debugging. void setDumpFlags({required BigInt flags}) => LibFjs.instance.api - .crateApiJsJsRuntimeSetDumpFlags(that: this, flags: flags); + .crateApiRuntimeJsRuntimeSetDumpFlags(that: this, flags: flags); /// Sets the garbage collection threshold. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes void setGcThreshold({required BigInt threshold}) => LibFjs.instance.api - .crateApiJsJsRuntimeSetGcThreshold(that: this, threshold: threshold); + .crateApiRuntimeJsRuntimeSetGcThreshold(that: this, threshold: threshold); - /// Sets runtime information for debugging purposes. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. - void setInfo({required String info}) => - LibFjs.instance.api.crateApiJsJsRuntimeSetInfo(that: this, info: info); + /// Sets runtime info string. + void setInfo({required String info}) => LibFjs.instance.api + .crateApiRuntimeJsRuntimeSetInfo(that: this, info: info); - /// Sets the maximum stack size for JavaScript execution. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes + /// Sets the maximum stack size. void setMaxStackSize({required BigInt limit}) => LibFjs.instance.api - .crateApiJsJsRuntimeSetMaxStackSize(that: this, limit: limit); + .crateApiRuntimeJsRuntimeSetMaxStackSize(that: this, limit: limit); /// Sets the memory limit for the runtime. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes void setMemoryLimit({required BigInt limit}) => LibFjs.instance.api - .crateApiJsJsRuntimeSetMemoryLimit(that: this, limit: limit); + .crateApiRuntimeJsRuntimeSetMemoryLimit(that: this, limit: limit); } @sealed @@ -4959,157 +5702,150 @@ class MemoryUsageImpl extends RustOpaque implements MemoryUsage { LibFjs.instance.api.rust_arc_decrement_strong_count_MemoryUsagePtr, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get arrayCount => - LibFjs.instance.api.crateApiJsMemoryUsageArrayCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageArrayCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get atomCount => - LibFjs.instance.api.crateApiJsMemoryUsageAtomCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageAtomCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get atomSize => - LibFjs.instance.api.crateApiJsMemoryUsageAtomSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageAtomSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get binaryObjectCount => - LibFjs.instance.api.crateApiJsMemoryUsageBinaryObjectCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageBinaryObjectCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get binaryObjectSize => - LibFjs.instance.api.crateApiJsMemoryUsageBinaryObjectSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageBinaryObjectSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get cFuncCount => - LibFjs.instance.api.crateApiJsMemoryUsageCFuncCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageCFuncCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get fastArrayCount => - LibFjs.instance.api.crateApiJsMemoryUsageFastArrayCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageFastArrayCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get fastArrayElements => - LibFjs.instance.api.crateApiJsMemoryUsageFastArrayElements( + LibFjs.instance.api.crateApiRuntimeMemoryUsageFastArrayElements( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get jsFuncCodeSize => - LibFjs.instance.api.crateApiJsMemoryUsageJsFuncCodeSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageJsFuncCodeSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get jsFuncCount => - LibFjs.instance.api.crateApiJsMemoryUsageJsFuncCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageJsFuncCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get jsFuncPc2LineCount => - LibFjs.instance.api.crateApiJsMemoryUsageJsFuncPc2LineCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageJsFuncPc2LineCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get jsFuncPc2LineSize => - LibFjs.instance.api.crateApiJsMemoryUsageJsFuncPc2LineSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageJsFuncPc2LineSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get jsFuncSize => - LibFjs.instance.api.crateApiJsMemoryUsageJsFuncSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageJsFuncSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get mallocCount => - LibFjs.instance.api.crateApiJsMemoryUsageMallocCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageMallocCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get mallocLimit => - LibFjs.instance.api.crateApiJsMemoryUsageMallocLimit( + LibFjs.instance.api.crateApiRuntimeMemoryUsageMallocLimit( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get mallocSize => - LibFjs.instance.api.crateApiJsMemoryUsageMallocSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageMallocSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get memoryUsedCount => - LibFjs.instance.api.crateApiJsMemoryUsageMemoryUsedCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageMemoryUsedCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get memoryUsedSize => - LibFjs.instance.api.crateApiJsMemoryUsageMemoryUsedSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageMemoryUsedSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get objCount => - LibFjs.instance.api.crateApiJsMemoryUsageObjCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageObjCount( that: this, ); - /// Returns the memory usage statistic for the given field. - PlatformInt64 get objSize => LibFjs.instance.api.crateApiJsMemoryUsageObjSize( + PlatformInt64 get objSize => + LibFjs.instance.api.crateApiRuntimeMemoryUsageObjSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get propCount => - LibFjs.instance.api.crateApiJsMemoryUsagePropCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsagePropCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get propSize => - LibFjs.instance.api.crateApiJsMemoryUsagePropSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsagePropSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get shapeCount => - LibFjs.instance.api.crateApiJsMemoryUsageShapeCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageShapeCount( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get shapeSize => - LibFjs.instance.api.crateApiJsMemoryUsageShapeSize( + LibFjs.instance.api.crateApiRuntimeMemoryUsageShapeSize( that: this, ); - /// Returns the memory usage statistic for the given field. PlatformInt64 get strCount => - LibFjs.instance.api.crateApiJsMemoryUsageStrCount( + LibFjs.instance.api.crateApiRuntimeMemoryUsageStrCount( + that: this, + ); + + PlatformInt64 get strSize => + LibFjs.instance.api.crateApiRuntimeMemoryUsageStrSize( + that: this, + ); + + /// Returns a human-readable summary of memory usage. + String summary() => LibFjs.instance.api.crateApiRuntimeMemoryUsageSummary( + that: this, + ); + + /// Returns total allocation count. + PlatformInt64 get totalAllocations => + LibFjs.instance.api.crateApiRuntimeMemoryUsageTotalAllocations( that: this, ); - /// Returns the memory usage statistic for the given field. - PlatformInt64 get strSize => LibFjs.instance.api.crateApiJsMemoryUsageStrSize( + /// Returns total memory used in bytes. + PlatformInt64 get totalMemory => + LibFjs.instance.api.crateApiRuntimeMemoryUsageTotalMemory( that: this, ); } diff --git a/lib/src/frb/frb_generated.io.dart b/lib/src/frb/frb_generated.io.dart index c4f47c6..07ebbaf 100644 --- a/lib/src/frb/frb_generated.io.dart +++ b/lib/src/frb/frb_generated.io.dart @@ -3,7 +3,10 @@ // ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field -import 'api/js.dart'; +import 'api/engine.dart'; +import 'api/error.dart'; +import 'api/runtime.dart'; +import 'api/source.dart'; import 'api/value.dart'; import 'dart:async'; import 'dart:convert'; @@ -181,6 +184,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsValue dco_decode_box_autoadd_js_value(dynamic raw); + @protected + int dco_decode_box_autoadd_u_32(dynamic raw); + @protected double dco_decode_f_64(dynamic raw); @@ -250,6 +256,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsEvalOptions? dco_decode_opt_box_autoadd_js_eval_options(dynamic raw); + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw); + @protected List? dco_decode_opt_list_js_module(dynamic raw); @@ -413,6 +422,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsValue sse_decode_box_autoadd_js_value(SseDeserializer deserializer); + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); + @protected double sse_decode_f_64(SseDeserializer deserializer); @@ -485,6 +497,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { JsEvalOptions? sse_decode_opt_box_autoadd_js_eval_options( SseDeserializer deserializer); + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); + @protected List? sse_decode_opt_list_js_module(SseDeserializer deserializer); @@ -662,6 +677,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_js_value(JsValue self, SseSerializer serializer); + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); + @protected void sse_encode_f_64(double self, SseSerializer serializer); @@ -738,6 +756,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { void sse_encode_opt_box_autoadd_js_eval_options( JsEvalOptions? self, SseSerializer serializer); + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); + @protected void sse_encode_opt_list_js_module( List? self, SseSerializer serializer); diff --git a/lib/src/frb/frb_generated.web.dart b/lib/src/frb/frb_generated.web.dart index af6c889..8ca7c5b 100644 --- a/lib/src/frb/frb_generated.web.dart +++ b/lib/src/frb/frb_generated.web.dart @@ -6,7 +6,10 @@ // Static analysis wrongly picks the IO variant, thus ignore this // ignore_for_file: argument_type_not_assignable -import 'api/js.dart'; +import 'api/engine.dart'; +import 'api/error.dart'; +import 'api/runtime.dart'; +import 'api/source.dart'; import 'api/value.dart'; import 'dart:async'; import 'dart:convert'; @@ -183,6 +186,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsValue dco_decode_box_autoadd_js_value(dynamic raw); + @protected + int dco_decode_box_autoadd_u_32(dynamic raw); + @protected double dco_decode_f_64(dynamic raw); @@ -252,6 +258,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsEvalOptions? dco_decode_opt_box_autoadd_js_eval_options(dynamic raw); + @protected + int? dco_decode_opt_box_autoadd_u_32(dynamic raw); + @protected List? dco_decode_opt_list_js_module(dynamic raw); @@ -415,6 +424,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected JsValue sse_decode_box_autoadd_js_value(SseDeserializer deserializer); + @protected + int sse_decode_box_autoadd_u_32(SseDeserializer deserializer); + @protected double sse_decode_f_64(SseDeserializer deserializer); @@ -487,6 +499,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { JsEvalOptions? sse_decode_opt_box_autoadd_js_eval_options( SseDeserializer deserializer); + @protected + int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer); + @protected List? sse_decode_opt_list_js_module(SseDeserializer deserializer); @@ -664,6 +679,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_js_value(JsValue self, SseSerializer serializer); + @protected + void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer); + @protected void sse_encode_f_64(double self, SseSerializer serializer); @@ -740,6 +758,9 @@ abstract class LibFjsApiImplPlatform extends BaseApiImpl { void sse_encode_opt_box_autoadd_js_eval_options( JsEvalOptions? self, SseSerializer serializer); + @protected + void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer); + @protected void sse_encode_opt_list_js_module( List? self, SseSerializer serializer); diff --git a/libfjs/src/api/engine.rs b/libfjs/src/api/engine.rs new file mode 100644 index 0000000..250b612 --- /dev/null +++ b/libfjs/src/api/engine.rs @@ -0,0 +1,487 @@ +//! # JavaScript Engine Core +//! +//! This module provides the core engine implementation that manages +//! the JavaScript runtime lifecycle, action processing, and bridge communication. + +use crate::api::error::{JsError, JsResult}; +use crate::api::runtime::{result_from_promise, JsAsyncContext}; +use crate::api::source::{get_raw_source_code, JsCode, JsEvalOptions, JsModule}; +use crate::api::value::JsValue; +use anyhow::anyhow; +use flutter_rust_bridge::{frb, DartFnFuture}; +use rquickjs::function::Args; +use rquickjs::{async_with, CatchResultExt, FromJs, Module, Object, Promise}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, RwLock}; +use tokio::sync::Mutex; + +/// Engine state constants +const STATE_CREATED: u8 = 0; +const STATE_RUNNING: u8 = 1; +const STATE_DISPOSED: u8 = 2; + +/// Represents an action that can be executed by the engine. +#[derive(Debug, Clone)] +pub enum JsAction { + /// Evaluate JavaScript code. + Eval { + id: u32, + source: JsCode, + options: Option, + }, + /// Declare a new module. + DeclareNewModule { id: u32, module: JsModule }, + /// Declare multiple modules. + DeclareNewModules { id: u32, modules: Vec }, + /// Clear all dynamic modules. + ClearNewModules { id: u32 }, + /// Evaluate a module. + EvaluateModule { id: u32, module: JsModule }, + /// Get all declared module names. + GetDeclaredModules { id: u32 }, + /// Check if a module is declared. + IsModuleDeclared { id: u32, module_name: String }, + /// Call a function in a module. + CallFunction { + id: u32, + module: String, + method: String, + params: Option>, + }, +} + +/// Result of a JavaScript action execution. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone)] +pub struct JsActionResult { + pub id: u32, + pub result: JsResult, +} + +/// Callback from the JavaScript engine to Dart. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone)] +pub enum JsCallback { + /// Engine has been initialized. + Initialized, + /// Action execution result. + Handler(JsActionResult), + /// Bridge call from JavaScript. + Bridge(JsValue), +} + +/// Result of handling a callback. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone)] +pub enum JsCallbackResult { + /// Initialization acknowledged. + Initialized, + /// Handler acknowledged. + Handler, + /// Bridge call result. + Bridge(JsResult), +} + +/// The core JavaScript engine. +#[frb(opaque)] +pub struct JsEngineCore { + context: JsAsyncContext, + sender: tokio::sync::mpsc::UnboundedSender, + receiver: Arc>>, + state: AtomicU8, +} + +impl JsEngineCore { + /// Creates a new engine core. + #[frb(sync)] + pub fn new(context: &JsAsyncContext) -> anyhow::Result { + let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); + Ok(Self { + context: context.clone(), + sender, + receiver: Arc::new(Mutex::new(receiver)), + state: AtomicU8::new(STATE_CREATED), + }) + } + + /// Returns the context. + #[frb(sync, getter)] + pub fn context(&self) -> JsAsyncContext { + self.context.clone() + } + + /// Returns whether the engine is disposed. + #[frb(sync, getter)] + pub fn disposed(&self) -> bool { + self.state.load(Ordering::Acquire) == STATE_DISPOSED + } + + /// Returns whether the engine is running. + #[frb(sync, getter)] + pub fn running(&self) -> bool { + self.state.load(Ordering::Acquire) == STATE_RUNNING + } + + /// Disposes the engine. + pub async fn dispose(&self) -> anyhow::Result<()> { + let current = self.state.load(Ordering::Acquire); + if current == STATE_DISPOSED { + return Err(anyhow!("Engine is already disposed")); + } + self.state.store(STATE_DISPOSED, Ordering::Release); + Ok(()) + } + + /// Executes an action. + pub async fn exec(&self, action: JsAction) -> anyhow::Result<()> { + let state = self.state.load(Ordering::Acquire); + if state == STATE_DISPOSED { + return Err(anyhow!("Engine is disposed")); + } + if state != STATE_RUNNING { + return Err(anyhow!("Engine is not running")); + } + self.sender + .send(action) + .map_err(|e| anyhow!("Failed to send action: {}", e)) + } + + /// Starts the engine event loop. + pub async fn start( + &self, + bridge: impl Fn(JsCallback) -> DartFnFuture + Sync + Send + 'static, + ) -> anyhow::Result<()> { + let current = self.state.load(Ordering::Acquire); + if current == STATE_DISPOSED { + return Err(anyhow!("Engine is disposed")); + } + if current == STATE_RUNNING { + return Err(anyhow!("Engine is already running")); + } + + // Transition to running state + if self + .state + .compare_exchange(STATE_CREATED, STATE_RUNNING, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return Err(anyhow!("Failed to start engine - invalid state")); + } + + // State guard + struct StateGuard<'a> { + state: &'a AtomicU8, + } + impl<'a> Drop for StateGuard<'a> { + fn drop(&mut self) { + self.state.store(STATE_DISPOSED, Ordering::Release); + } + } + let _guard = StateGuard { state: &self.state }; + + let cb = Arc::new(bridge); + + async_with!(self.context.ctx => |ctx| { + if let Some(attachment) = &self.context.global_attachment { + if let Err(e) = attachment.attach(&ctx) { + return Err(anyhow!("Failed to attach global context: {}", e)); + } + } + if let Err(e) = register_fjs(ctx.clone(), cb.clone()) { + return Err(anyhow!("Failed to register fjs bridge: {}", e)); + } + + cb(JsCallback::Initialized).await; + + loop { + let mut receiver = self.receiver.lock().await; + match receiver.recv().await { + None => return Ok(()), + Some(action) => { + drop(receiver); + let ctx_s = ctx.clone(); + let cb_clone = cb.clone(); + ctx.spawn(async move { + Self::handle_action(ctx_s, cb_clone, action).await; + }); + } + } + } + }) + .await + } + + /// Handles a single action. + async fn handle_action( + ctx: rquickjs::Ctx<'_>, + cb: Arc DartFnFuture + Sync + Send + 'static>, + action: JsAction, + ) { + match action { + JsAction::Eval { id, source, options } => { + let mut options = options.unwrap_or_default(); + options.promise = Some(true); + let res = match get_raw_source_code(source.clone()).await { + Err(e) => JsResult::Err(JsError::io( + source.as_path().map(|s| s.to_string()), + e.to_string(), + )), + Ok(source_code) => { + let res = ctx.eval_with_options(source_code, options.into()); + result_from_promise(&ctx, res).await + } + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::DeclareNewModule { id, module } => { + let res = Self::declare_module(&ctx, module).await; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::DeclareNewModules { id, modules } => { + let mut last_result = JsResult::Ok(JsValue::None); + for module in modules { + let res = Self::declare_module(&ctx, module).await; + if res.is_err() { + last_result = res; + break; + } + } + cb(JsCallback::Handler(JsActionResult { + id, + result: last_result, + })) + .await; + } + + JsAction::EvaluateModule { id, module } => { + let res = match get_raw_source_code(module.source.clone()).await { + Err(e) => JsResult::Err(JsError::io( + module.source.as_path().map(|s| s.to_string()), + e.to_string(), + )), + Ok(source_code) => { + if let Some(storage) = + ctx.userdata::>>>>() + { + storage + .write() + .unwrap() + .insert(module.name.clone(), source_code.clone()); + let res = Module::evaluate(ctx.clone(), module.name, source_code); + result_from_promise(&ctx, res).await + } else { + JsResult::Err(JsError::storage("Module storage not initialized")) + } + } + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::ClearNewModules { id } => { + let res = if let Some(storage) = + ctx.userdata::>>>>() + { + storage.write().unwrap().clear(); + JsResult::Ok(JsValue::None) + } else { + JsResult::Err(JsError::storage("Module storage not initialized")) + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::GetDeclaredModules { id } => { + let res = if let Some(storage) = + ctx.userdata::>>>>() + { + let names: Vec = storage + .read() + .unwrap() + .keys() + .cloned() + .map(JsValue::String) + .collect(); + JsResult::Ok(JsValue::Array(names)) + } else { + JsResult::Err(JsError::storage("Module storage not initialized")) + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::IsModuleDeclared { id, module_name } => { + let res = if let Some(storage) = + ctx.userdata::>>>>() + { + let is_declared = storage.read().unwrap().contains_key(&module_name); + JsResult::Ok(JsValue::Boolean(is_declared)) + } else { + JsResult::Err(JsError::storage("Module storage not initialized")) + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + + JsAction::CallFunction { + id, + module, + method, + params, + } => { + let params = params.unwrap_or_default(); + let res = match Module::import(&ctx, module.clone()).catch(&ctx) { + Ok(promise) => { + match promise.into_future::().await.catch(&ctx) { + Ok(v) if v.is_object() => { + if let Some(obj) = v.as_object() { + let m: rquickjs::Result = obj.get(&method); + match m.catch(&ctx) { + Ok(m) if m.is_function() => { + if let Some(func) = m.as_function() { + let res = func + .call((rquickjs::function::Rest(params),)); + result_from_promise(&ctx, res).await + } else { + JsResult::Err(JsError::module( + Some(module), + Some(method), + "Method is not a function", + )) + } + } + Ok(_) => JsResult::Err(JsError::module( + Some(module), + Some(method), + "Method is not a function", + )), + Err(e) => JsResult::Err(JsError::module( + Some(module), + Some(method), + format!("Failed to get method: {}", e), + )), + } + } else { + JsResult::Err(JsError::module( + Some(module), + None, + "Module is not an object", + )) + } + } + Ok(_) => JsResult::Err(JsError::module( + Some(module), + None, + "Module is not an object", + )), + Err(e) => JsResult::Err(JsError::module( + Some(module), + None, + format!("Failed to import: {}", e), + )), + } + } + Err(e) => JsResult::Err(JsError::module( + Some(module), + None, + format!("Failed to import: {}", e), + )), + }; + cb(JsCallback::Handler(JsActionResult { id, result: res })).await; + } + } + } + + async fn declare_module(ctx: &rquickjs::Ctx<'_>, module: JsModule) -> JsResult { + match get_raw_source_code(module.source.clone()).await { + Err(e) => JsResult::Err(JsError::io( + module.source.as_path().map(|s| s.to_string()), + e.to_string(), + )), + Ok(source_code) => { + if let Some(storage) = ctx.userdata::>>>>() { + storage.write().unwrap().insert(module.name, source_code); + JsResult::Ok(JsValue::None) + } else { + JsResult::Err(JsError::storage("Module storage not initialized")) + } + } + } + } +} + +/// Registers the fjs bridge object. +fn register_fjs<'js>( + ctx: rquickjs::Ctx<'js>, + bridge: Arc DartFnFuture + Sync + Send + 'static>, +) -> rquickjs::CaughtResult<'js, ()> { + let fjs = Object::new(ctx.clone()).catch(&ctx)?; + fjs.set("bridge_call", new_bridge_call(ctx.clone(), bridge)?) + .catch(&ctx)?; + ctx.globals().set("fjs", fjs).catch(&ctx)?; + Ok(()) +} + +/// Creates the bridge_call function. +fn new_bridge_call<'js>( + ctx: rquickjs::Ctx<'js>, + bridge: Arc DartFnFuture + Sync + Send + 'static>, +) -> rquickjs::CaughtResult<'js, rquickjs::Function<'js>> { + let ctx_for_catch = ctx.clone(); + rquickjs::Function::new( + ctx.clone(), + move |args: rquickjs::function::Rest>| -> rquickjs::Result { + if args.0.len() > 1 { + return Err(rquickjs::Error::TooManyArgs { + expected: 1, + given: args.len(), + }); + } + if args.0.is_empty() { + return Err(rquickjs::Error::MissingArgs { + expected: 1, + given: 0, + }); + } + + let arg = args + .0 + .first() + .ok_or_else(|| rquickjs::Error::MissingArgs { + expected: 1, + given: 0, + })?; + + let js_value = JsValue::from_js(&ctx, arg.clone())?; + let bridge_call = bridge.clone(); + let (promise, resolve, reject) = ctx.promise()?; + let ctx_s = ctx.clone(); + + ctx.spawn(async move { + let res = bridge_call(JsCallback::Bridge(js_value)).await; + if let JsCallbackResult::Bridge(res) = res { + match res { + JsResult::Ok(value) => { + let mut args = Args::new(ctx_s.clone(), 1); + if let Err(e) = args.push_arg(value) { + let mut reject_args = Args::new(ctx_s, 1); + let _ = reject_args.push_arg(format!("Internal error: {}", e)); + let _ = reject.call_arg::<()>(reject_args); + return; + } + let _ = resolve.call_arg::<()>(args); + } + JsResult::Err(err) => { + let mut args = Args::new(ctx_s, 1); + if args.push_arg(err.to_string()).is_err() { + return; + } + let _ = reject.call_arg::<()>(args); + } + } + } + }); + Ok(promise) + }, + ) + .catch(&ctx_for_catch) +} diff --git a/libfjs/src/api/error.rs b/libfjs/src/api/error.rs new file mode 100644 index 0000000..06e490e --- /dev/null +++ b/libfjs/src/api/error.rs @@ -0,0 +1,442 @@ +//! # Error Handling +//! +//! This module provides comprehensive error types for the FJS JavaScript runtime. +//! It uses `thiserror` for ergonomic error definitions and provides rich context +//! for debugging and user feedback. + +use flutter_rust_bridge::frb; +use std::fmt; + +/// Represents various types of JavaScript errors. +/// +/// This enum provides detailed error information for different +/// categories of errors that can occur during JavaScript execution. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone)] +pub enum JsError { + /// Promise-related errors (async operation failures) + Promise(String), + /// Module-related errors (import/export failures) + Module { + /// Optional module name where the error occurred + module: Option, + /// Optional method name where the error occurred + method: Option, + /// Error message + message: String, + }, + /// Context attachment errors (global object setup failures) + Context(String), + /// Storage initialization errors (dynamic module storage failures) + Storage(String), + /// File I/O errors (file reading failures) + Io { + /// Optional file path where the error occurred + path: Option, + /// Error message + message: String, + }, + /// JavaScript runtime errors from QuickJS engine + Runtime(String), + /// Generic catch-all errors + Generic(String), + /// Engine lifecycle errors + Engine(String), + /// Bridge communication errors + Bridge(String), + /// Type conversion errors + Conversion { + /// The source type + from: String, + /// The target type + to: String, + /// Error message + message: String, + }, + /// Timeout errors + Timeout { + /// Operation that timed out + operation: String, + /// Timeout duration in milliseconds + timeout_ms: u64, + }, + /// Memory limit exceeded errors + MemoryLimit { + /// Current memory usage in bytes + current: u64, + /// Memory limit in bytes + limit: u64, + }, + /// Stack overflow errors + StackOverflow(String), + /// Syntax errors in JavaScript code + Syntax { + /// Line number where the error occurred + line: Option, + /// Column number where the error occurred + column: Option, + /// Error message + message: String, + }, + /// Reference errors (undefined variables, etc.) + Reference(String), + /// Type errors in JavaScript + Type(String), + /// Cancelled operation errors + Cancelled(String), +} + +impl JsError { + /// Creates a new promise error. + #[frb(ignore)] + pub fn promise>(msg: S) -> Self { + JsError::Promise(msg.into()) + } + + /// Creates a new module error. + #[frb(ignore)] + pub fn module>( + module: Option, + method: Option, + message: S, + ) -> Self { + JsError::Module { + module, + method, + message: message.into(), + } + } + + /// Creates a new context error. + #[frb(ignore)] + pub fn context>(msg: S) -> Self { + JsError::Context(msg.into()) + } + + /// Creates a new storage error. + #[frb(ignore)] + pub fn storage>(msg: S) -> Self { + JsError::Storage(msg.into()) + } + + /// Creates a new I/O error. + #[frb(ignore)] + pub fn io>(path: Option, message: S) -> Self { + JsError::Io { + path, + message: message.into(), + } + } + + /// Creates a new runtime error. + #[frb(ignore)] + pub fn runtime>(msg: S) -> Self { + JsError::Runtime(msg.into()) + } + + /// Creates a new generic error. + #[frb(ignore)] + pub fn generic>(msg: S) -> Self { + JsError::Generic(msg.into()) + } + + /// Creates a new engine error. + #[frb(ignore)] + pub fn engine>(msg: S) -> Self { + JsError::Engine(msg.into()) + } + + /// Creates a new bridge error. + #[frb(ignore)] + pub fn bridge>(msg: S) -> Self { + JsError::Bridge(msg.into()) + } + + /// Creates a new conversion error. + #[frb(ignore)] + pub fn conversion>(from: S, to: S, message: S) -> Self { + JsError::Conversion { + from: from.into(), + to: to.into(), + message: message.into(), + } + } + + /// Creates a new timeout error. + #[frb(ignore)] + pub fn timeout>(operation: S, timeout_ms: u64) -> Self { + JsError::Timeout { + operation: operation.into(), + timeout_ms, + } + } + + /// Creates a new memory limit error. + #[frb(ignore)] + pub fn memory_limit(current: u64, limit: u64) -> Self { + JsError::MemoryLimit { current, limit } + } + + /// Creates a new syntax error. + #[frb(ignore)] + pub fn syntax>(line: Option, column: Option, message: S) -> Self { + JsError::Syntax { + line, + column, + message: message.into(), + } + } + + /// Creates a new reference error. + #[frb(ignore)] + pub fn reference>(msg: S) -> Self { + JsError::Reference(msg.into()) + } + + /// Creates a new type error. + #[frb(ignore)] + pub fn type_error>(msg: S) -> Self { + JsError::Type(msg.into()) + } + + /// Creates a new cancelled error. + #[frb(ignore)] + pub fn cancelled>(msg: S) -> Self { + JsError::Cancelled(msg.into()) + } + + /// Converts the error to a string representation. + #[frb(sync)] + pub fn to_string(&self) -> String { + format!("{}", self) + } + + /// Returns the error code for this error type. + #[frb(sync)] + pub fn code(&self) -> String { + match self { + JsError::Promise(_) => "PROMISE_ERROR".to_string(), + JsError::Module { .. } => "MODULE_ERROR".to_string(), + JsError::Context(_) => "CONTEXT_ERROR".to_string(), + JsError::Storage(_) => "STORAGE_ERROR".to_string(), + JsError::Io { .. } => "IO_ERROR".to_string(), + JsError::Runtime(_) => "RUNTIME_ERROR".to_string(), + JsError::Generic(_) => "GENERIC_ERROR".to_string(), + JsError::Engine(_) => "ENGINE_ERROR".to_string(), + JsError::Bridge(_) => "BRIDGE_ERROR".to_string(), + JsError::Conversion { .. } => "CONVERSION_ERROR".to_string(), + JsError::Timeout { .. } => "TIMEOUT_ERROR".to_string(), + JsError::MemoryLimit { .. } => "MEMORY_LIMIT_ERROR".to_string(), + JsError::StackOverflow(_) => "STACK_OVERFLOW_ERROR".to_string(), + JsError::Syntax { .. } => "SYNTAX_ERROR".to_string(), + JsError::Reference(_) => "REFERENCE_ERROR".to_string(), + JsError::Type(_) => "TYPE_ERROR".to_string(), + JsError::Cancelled(_) => "CANCELLED_ERROR".to_string(), + } + } + + /// Returns whether this error is recoverable. + #[frb(sync)] + pub fn is_recoverable(&self) -> bool { + match self { + JsError::Promise(_) + | JsError::Module { .. } + | JsError::Io { .. } + | JsError::Runtime(_) + | JsError::Generic(_) + | JsError::Bridge(_) + | JsError::Conversion { .. } + | JsError::Timeout { .. } + | JsError::Syntax { .. } + | JsError::Reference(_) + | JsError::Type(_) => true, + JsError::Context(_) + | JsError::Storage(_) + | JsError::Engine(_) + | JsError::MemoryLimit { .. } + | JsError::StackOverflow(_) + | JsError::Cancelled(_) => false, + } + } +} + +impl fmt::Display for JsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + JsError::Promise(msg) => write!(f, "Promise error: {}", msg), + JsError::Module { + module, + method, + message, + } => { + let mut parts = Vec::new(); + if let Some(m) = module { + parts.push(format!("module: {}", m)); + } + if let Some(m) = method { + parts.push(format!("method: {}", m)); + } + parts.push(format!("error: {}", message)); + write!(f, "Module error - {}", parts.join(", ")) + } + JsError::Context(msg) => write!(f, "Context error: {}", msg), + JsError::Storage(msg) => write!(f, "Storage error: {}", msg), + JsError::Io { path, message } => { + if let Some(p) = path { + write!(f, "IO error at {}: {}", p, message) + } else { + write!(f, "IO error: {}", message) + } + } + JsError::Runtime(msg) => write!(f, "Runtime error: {}", msg), + JsError::Generic(msg) => write!(f, "{}", msg), + JsError::Engine(msg) => write!(f, "Engine error: {}", msg), + JsError::Bridge(msg) => write!(f, "Bridge error: {}", msg), + JsError::Conversion { from, to, message } => { + write!(f, "Conversion error ({} -> {}): {}", from, to, message) + } + JsError::Timeout { + operation, + timeout_ms, + } => { + write!( + f, + "Timeout error: {} timed out after {}ms", + operation, timeout_ms + ) + } + JsError::MemoryLimit { current, limit } => { + write!( + f, + "Memory limit exceeded: {} bytes used, {} bytes limit", + current, limit + ) + } + JsError::StackOverflow(msg) => write!(f, "Stack overflow: {}", msg), + JsError::Syntax { + line, + column, + message, + } => { + let mut loc = String::new(); + if let Some(l) = line { + loc.push_str(&format!("line {}", l)); + if let Some(c) = column { + loc.push_str(&format!(", column {}", c)); + } + } + if loc.is_empty() { + write!(f, "Syntax error: {}", message) + } else { + write!(f, "Syntax error at {}: {}", loc, message) + } + } + JsError::Reference(msg) => write!(f, "Reference error: {}", msg), + JsError::Type(msg) => write!(f, "Type error: {}", msg), + JsError::Cancelled(msg) => write!(f, "Cancelled: {}", msg), + } + } +} + +impl std::error::Error for JsError {} + +impl From for JsError { + fn from(err: anyhow::Error) -> Self { + JsError::Generic(err.to_string()) + } +} + +impl From for JsError { + fn from(err: std::io::Error) -> Self { + JsError::Io { + path: None, + message: err.to_string(), + } + } +} + +impl From for JsError { + fn from(err: rquickjs::Error) -> Self { + match &err { + rquickjs::Error::Exception => JsError::Runtime(err.to_string()), + _ => JsError::Runtime(err.to_string()), + } + } +} + +/// Represents the result of a JavaScript operation. +#[frb(dart_metadata = ("freezed"), dart_code = " + bool get isOk => this is JsResult_Ok; + bool get isErr => this is JsResult_Err; + JsValue get ok => (this as JsResult_Ok).field0; + JsError get err => (this as JsResult_Err).field0; +")] +#[derive(Debug, Clone)] +pub enum JsResult { + /// Successful execution result + Ok(super::value::JsValue), + /// Error during execution + Err(JsError), +} + +impl JsResult { + /// Creates a successful result. + #[frb(ignore)] + pub fn ok(value: super::value::JsValue) -> Self { + JsResult::Ok(value) + } + + /// Creates an error result. + #[frb(ignore)] + pub fn err(error: JsError) -> Self { + JsResult::Err(error) + } + + /// Returns true if the result is Ok. + #[frb(ignore)] + pub fn is_ok(&self) -> bool { + matches!(self, JsResult::Ok(_)) + } + + /// Returns true if the result is Err. + #[frb(ignore)] + pub fn is_err(&self) -> bool { + matches!(self, JsResult::Err(_)) + } + + /// Maps the Ok value using the provided function. + #[frb(ignore)] + pub fn map U>(self, f: F) -> Result { + match self { + JsResult::Ok(v) => Ok(f(v)), + JsResult::Err(e) => Err(e), + } + } + + /// Maps the Err value using the provided function. + #[frb(ignore)] + pub fn map_err JsError>(self, f: F) -> JsResult { + match self { + JsResult::Ok(v) => JsResult::Ok(v), + JsResult::Err(e) => JsResult::Err(f(e)), + } + } +} + +impl From> for JsResult { + fn from(result: Result) -> Self { + match result { + Ok(v) => JsResult::Ok(v), + Err(e) => JsResult::Err(e), + } + } +} + +impl From for Result { + fn from(result: JsResult) -> Self { + match result { + JsResult::Ok(v) => Ok(v), + JsResult::Err(e) => Err(e), + } + } +} diff --git a/libfjs/src/api/js.rs b/libfjs/src/api/js.rs deleted file mode 100644 index 62381d1..0000000 --- a/libfjs/src/api/js.rs +++ /dev/null @@ -1,2145 +0,0 @@ -//! # JavaScript Runtime API -//! -//! This module provides the core JavaScript runtime functionality for Flutter integration. -//! It includes support for both synchronous and asynchronous JavaScript execution, -//! module management, and bidirectional communication between Dart and JavaScript. -//! -//! ## Key Components -//! -//! - **Runtime Management**: Configuration and lifecycle management of JavaScript runtimes -//! - **Context Management**: Execution contexts with isolation and state management -//! - **Module System**: Dynamic loading, resolution, and execution of JavaScript modules -//! - **Error Handling**: Comprehensive error types and propagation mechanisms -//! - **Bridge Communication**: Bidirectional communication between Dart and JavaScript -//! -//! ## Thread Safety -//! -//! All runtime types are designed to be thread-safe where appropriate. Async runtimes -//! can be shared across threads, while sync runtimes have more restrictive access patterns. - -use crate::api::module::{ - DynamicModuleLoader, DynamicModuleResolver, GlobalAttachment, ModuleBuilder, -}; -use crate::api::value::JsValue; -use anyhow::anyhow; -use flutter_rust_bridge::{frb, DartFnFuture}; -use rquickjs::function::Args; -use rquickjs::loader::{BuiltinLoader, BuiltinResolver, FileResolver, NativeLoader, ScriptLoader}; -use rquickjs::{async_with, CatchResultExt, FromJs, Module, Object, Promise}; -use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, RwLock}; -use tokio::io::AsyncReadExt; -use tokio::sync::Mutex; - -/// Maximum file size for JavaScript source files (10 MB) -/// -/// This constant limits the maximum size of JavaScript files that can be loaded -/// to prevent memory exhaustion and potential DoS attacks. -const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024; // 10 MB - -/// Memory usage statistics for the JavaScript runtime. -/// -/// This struct provides detailed information about memory consumption -/// within the QuickJS engine, including allocation counts, object counts, -/// and memory usage for different data types. -#[frb(opaque)] -#[derive(Clone)] -pub struct MemoryUsage(rquickjs::qjs::JSMemoryUsage); - -/// Macro to generate getter methods for memory usage statistics. -/// -/// This macro creates synchronized getter methods for all the fields -/// in the QuickJS JSMemoryUsage struct, making them accessible from Dart. -macro_rules! proxy_memory_usage_getter { - ($($name:ident),+) => { - impl MemoryUsage { - $( - /// Returns the memory usage statistic for the given field. - #[frb(sync, getter)] - pub fn $name(&self) -> i64 { self.0.$name } - )+ - } - }; -} - -// Generate getter methods for all memory usage fields -proxy_memory_usage_getter!( - malloc_size, - malloc_limit, - memory_used_size, - malloc_count, - memory_used_count, - atom_count, - atom_size, - str_count, - str_size, - obj_count, - obj_size, - prop_count, - prop_size, - shape_count, - shape_size, - js_func_count, - js_func_size, - js_func_code_size, - js_func_pc2line_count, - js_func_pc2line_size, - c_func_count, - array_count, - fast_array_count, - fast_array_elements, - binary_object_count, - binary_object_size -); - -/// A synchronous JavaScript runtime. -/// -/// This struct provides a synchronous JavaScript execution environment based on QuickJS. -/// It supports module loading, memory management, and garbage collection control. -/// Synchronous runtimes are suitable for simple scripts and non-blocking operations. -#[frb(opaque)] -#[derive(Clone)] -pub struct JsRuntime { - rt: rquickjs::Runtime, - global_attachment: Option, -} - -impl JsRuntime { - /// Creates a new JavaScript runtime with default configuration. - /// - /// # Returns - /// - /// Returns a new `JsRuntime` instance or an error if initialization fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsRuntime::new()?; - /// let context = JsContext::new(&runtime)?; - /// ``` - #[frb(sync)] - pub fn new() -> anyhow::Result { - let runtime = rquickjs::Runtime::new()?; - Ok(Self { - rt: runtime, - global_attachment: None, - }) - } - - /// Creates a new JavaScript runtime with custom builtin modules and additional modules. - /// - /// # Parameters - /// - /// - `builtin`: Optional configuration for builtin Node.js modules - /// - `additional`: Optional list of additional JavaScript modules to load - /// - /// # Returns - /// - /// Returns a new `JsRuntime` instance with the specified configuration. - /// - /// # Examples - /// - /// ```rust - /// let builtin = JsBuiltinOptions::all(); - /// let additional = vec![JsModule::code("my-module", "export const value = 42;")]; - /// let runtime = JsAsyncRuntime::with_options(Some(builtin), Some(additional)).await?; - /// ``` - pub async fn with_options( - builtin: Option, - additional: Option>, - ) -> anyhow::Result { - let runtime = rquickjs::Runtime::new()?; - - // Handle builtin module options - let (module_resolver, module_loader, global_attachment) = - if let Some(builtin_options) = builtin { - let builder = builtin_options.to_module_builder(); - builder.build() - } else { - ModuleBuilder::new().build() - }; - - let mut builtin_resolver = BuiltinResolver::default(); - let mut builtin_loader = BuiltinLoader::default(); - - // Handle additional JS modules - if let Some(additional_modules) = additional { - for module in additional_modules { - let code = get_raw_source_code(module.source).await?; - builtin_resolver = builtin_resolver.with_module(&module.name); - builtin_loader = builtin_loader.with_module(&module.name, code); - } - } - - // Add dynamic module resolver and loader - let dynamic_resolver = DynamicModuleResolver::default(); - let dynamic_loader = DynamicModuleLoader::default(); - - let resolver = ( - module_resolver, - builtin_resolver, - dynamic_resolver, - FileResolver::default(), - ); - let loader = ( - module_loader, - builtin_loader, - dynamic_loader, - NativeLoader::default(), - ScriptLoader::default(), - ); - runtime.set_loader(resolver, loader); - Ok(Self { - rt: runtime, - global_attachment: Some(global_attachment), - }) - } - - /// Sets the memory limit for the runtime. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes - #[frb(sync)] - pub fn set_memory_limit(&self, limit: usize) { - self.rt.set_memory_limit(limit); - } - - /// Sets the maximum stack size for JavaScript execution. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes - #[frb(sync)] - pub fn set_max_stack_size(&self, limit: usize) { - self.rt.set_max_stack_size(limit); - } - - /// Sets the garbage collection threshold. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes - #[frb(sync)] - pub fn set_gc_threshold(&self, threshold: usize) { - self.rt.set_gc_threshold(threshold); - } - - /// Forces garbage collection to run immediately. - #[frb(sync)] - pub fn run_gc(&self) { - self.rt.run_gc(); - } - - /// Returns the current memory usage statistics. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. - #[frb(sync)] - pub fn memory_usage(&self) -> MemoryUsage { - let usage = self.rt.memory_usage(); - MemoryUsage(usage) - } - - /// Checks if there are pending jobs to be executed. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. - #[frb(sync)] - pub fn is_job_pending(&self) -> bool { - self.rt.is_job_pending() - } - - /// Executes a pending job if one is available. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. - #[frb(sync)] - pub fn execute_pending_job(&self) -> anyhow::Result { - self.rt.execute_pending_job().map_err(|e| anyhow!(e)) - } - - /// Sets dump flags for debugging and profiling. - /// - /// # Parameters - /// - /// - `flags`: Bitmask of dump flags - #[frb(sync)] - pub fn set_dump_flags(&self, flags: u64) { - self.rt.set_dump_flags(flags); - } - - /// Sets runtime information for debugging purposes. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. - #[frb(sync)] - pub fn set_info(&self, info: String) -> anyhow::Result<()> { - self.rt.set_info(info)?; - Ok(()) - } -} - -/// A synchronous JavaScript execution context. -/// -/// This struct provides a context for executing JavaScript code synchronously. -/// Each context has its own global object and state but shares the underlying runtime. -/// Contexts are thread-safe for read operations but require exclusive access for execution. -#[frb(opaque)] -#[derive(Clone)] -pub struct JsContext { - ctx: rquickjs::Context, - global_attachment: Option, -} - -impl JsContext { - /// Creates a new JavaScript context from a runtime. - /// - /// # Parameters - /// - /// - `rt`: The runtime to create the context from - /// - /// # Returns - /// - /// Returns a new `JsContext` instance or an error if creation fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsRuntime::new()?; - /// let context = JsContext::new(&runtime)?; - /// let result = context.eval("2 + 2".to_string())?; - /// ``` - #[frb(sync)] - pub fn new(rt: &JsRuntime) -> anyhow::Result { - let context = rquickjs::Context::full(&rt.rt)?; - Ok(Self { - ctx: context, - global_attachment: rt.global_attachment.clone(), - }) - } - - /// Evaluates JavaScript code with default options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string())?; - /// ``` - #[frb(sync)] - pub fn eval(&self, code: String) -> JsResult { - self.eval_with_options(code, JsEvalOptions::default()) - } - - /// Evaluates JavaScript code with custom options. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. - /// Use `JsAsyncContext` for asynchronous operations. - #[frb(sync)] - pub fn eval_with_options(&self, code: String, options: JsEvalOptions) -> JsResult { - if options.promise.unwrap_or(false) { - return JsResult::Err(JsError::promise( - "Promise not supported in sync context".to_string(), - )); - } - self.ctx.with(|ctx| { - if let Some(attachment) = &self.global_attachment { - if let Err(e) = attachment.attach(&ctx) { - return JsResult::Err(JsError::context(format!( - "Failed to attach global context: {}", - e - ))); - } - } - let res = ctx.eval_with_options(code, options.into()); - JsResult::from_result(&ctx, res) - }) - } - - /// Evaluates JavaScript code from a file with default options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. - #[frb(sync)] - pub fn eval_file(&self, path: String) -> JsResult { - self.eval_file_with_options(path, JsEvalOptions::default()) - } - - /// Evaluates JavaScript code from a file with custom options. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// Promise evaluation is not supported in synchronous contexts. - #[frb(sync)] - pub fn eval_file_with_options(&self, path: String, options: JsEvalOptions) -> JsResult { - if options.promise.unwrap_or(false) { - return JsResult::Err(JsError::promise( - "Promise not supported in sync context".to_string(), - )); - } - self.ctx.with(|ctx| { - if let Some(attachment) = &self.global_attachment { - if let Err(e) = attachment.attach(&ctx) { - return JsResult::Err(JsError::context(format!( - "Failed to attach global context: {}", - e - ))); - } - } - let res = ctx.eval_file_with_options(path, options.into()); - JsResult::from_result(&ctx, res) - }) - } -} - -/// An asynchronous JavaScript runtime. -/// -/// This struct provides an asynchronous JavaScript execution environment based on QuickJS. -/// It supports all features of the synchronous runtime plus asynchronous operations, -/// promise handling, and concurrent execution. -#[frb(opaque)] -#[derive(Clone)] -pub struct JsAsyncRuntime { - rt: rquickjs::AsyncRuntime, - global_attachment: Option, -} - -impl JsAsyncRuntime { - /// Creates a new asynchronous JavaScript runtime with default configuration. - /// - /// # Returns - /// - /// Returns a new `JsAsyncRuntime` instance or an error if initialization fails. - #[frb(sync)] - pub fn new() -> anyhow::Result { - let runtime = rquickjs::AsyncRuntime::new()?; - Ok(Self { - rt: runtime, - global_attachment: None, - }) - } - - /// Creates a new asynchronous JavaScript runtime with custom configuration. - /// - /// # Parameters - /// - /// - `builtin`: Optional configuration for builtin Node.js modules - /// - `additional`: Optional list of additional JavaScript modules to load - /// - /// # Returns - /// - /// Returns a new `JsAsyncRuntime` instance with the specified configuration. - /// - /// # Examples - /// - /// ```rust - /// let builtin = JsBuiltinOptions::all(); - /// let additional = vec![JsModule::code("my-module", "export const value = 42;")]; - /// let runtime = JsAsyncRuntime::with_options(Some(builtin), Some(additional)).await?; - /// ``` - pub async fn with_options( - builtin: Option, - additional: Option>, - ) -> anyhow::Result { - let runtime = rquickjs::AsyncRuntime::new()?; - - // Handle builtin module options - let (module_resolver, module_loader, global_attachment) = - if let Some(builtin_options) = builtin { - let builder = builtin_options.to_module_builder(); - builder.build() - } else { - ModuleBuilder::new().build() - }; - - let mut builtin_resolver = BuiltinResolver::default(); - let mut builtin_loader = BuiltinLoader::default(); - - // Handle additional JS modules - if let Some(additional_modules) = additional { - for module in additional_modules { - let code = get_raw_source_code(module.source).await?; - builtin_resolver = builtin_resolver.with_module(&module.name); - builtin_loader = builtin_loader.with_module(&module.name, code); - } - } - - // Add dynamic module resolver and loader - let dynamic_resolver = DynamicModuleResolver::default(); - let dynamic_loader = DynamicModuleLoader::default(); - - let resolver = ( - module_resolver, - builtin_resolver, - dynamic_resolver, - FileResolver::default(), - ); - let loader = ( - module_loader, - builtin_loader, - dynamic_loader, - NativeLoader::default(), - ScriptLoader::default(), - ); - runtime.set_loader(resolver, loader).await; - Ok(Self { - rt: runtime, - global_attachment: Some(global_attachment), - }) - } - - /// Sets the memory limit for the runtime asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum memory limit in bytes - pub async fn set_memory_limit(&self, limit: usize) { - self.rt.set_memory_limit(limit).await; - } - - /// Sets the maximum stack size for JavaScript execution asynchronously. - /// - /// # Parameters - /// - /// - `limit`: Maximum stack size in bytes - pub async fn set_max_stack_size(&self, limit: usize) { - self.rt.set_max_stack_size(limit).await; - } - - /// Sets the garbage collection threshold asynchronously. - /// - /// # Parameters - /// - /// - `threshold`: GC threshold in bytes - pub async fn set_gc_threshold(&self, threshold: usize) { - self.rt.set_gc_threshold(threshold).await; - } - - /// Forces garbage collection to run immediately asynchronously. - pub async fn run_gc(&self) { - self.rt.run_gc().await; - } - - /// Returns the current memory usage statistics asynchronously. - /// - /// # Returns - /// - /// Returns a `MemoryUsage` struct containing detailed memory statistics. - pub async fn memory_usage(&self) -> MemoryUsage { - let usage = self.rt.memory_usage().await; - MemoryUsage(usage) - } - - /// Checks if there are pending jobs to be executed asynchronously. - /// - /// # Returns - /// - /// Returns `true` if there are pending jobs, `false` otherwise. - pub async fn is_job_pending(&self) -> bool { - self.rt.is_job_pending().await - } - - /// Executes a pending job if one is available asynchronously. - /// - /// # Returns - /// - /// Returns `true` if a job was executed, `false` if no jobs were pending. - /// - /// # Errors - /// - /// Returns an error if job execution fails. - pub async fn execute_pending_job(&self) -> anyhow::Result { - self.rt.execute_pending_job().await.map_err(|e| anyhow!(e)) - } - - /// Puts the runtime into idle state, waiting for events. - /// - /// This method should be called when the runtime is not actively executing - /// JavaScript code but needs to remain responsive to events. - pub async fn idle(&self) { - self.rt.idle().await; - } - - /// Sets runtime information for debugging purposes asynchronously. - /// - /// # Parameters - /// - /// - `info`: Information string to set - /// - /// # Errors - /// - /// Returns an error if setting the info fails. - pub async fn set_info(&self, info: String) -> anyhow::Result<()> { - self.rt.set_info(info).await?; - Ok(()) - } -} - -/// An asynchronous JavaScript execution context. -/// -/// This struct provides a context for executing JavaScript code asynchronously. -/// It supports promise handling, top-level await, and concurrent execution. -/// Each context has its own global object and state but shares the underlying runtime. -#[frb(opaque)] -#[derive(Clone)] -pub struct JsAsyncContext { - ctx: rquickjs::AsyncContext, - global_attachment: Option, -} - -impl JsAsyncContext { - /// Creates a new asynchronous JavaScript context from a runtime. - /// - /// # Parameters - /// - /// - `rt`: The asynchronous runtime to create the context from - /// - /// # Returns - /// - /// Returns a new `JsAsyncContext` instance or an error if creation fails. - /// - /// # Examples - /// - /// ```rust - /// let runtime = JsAsyncRuntime::new().await?; - /// let context = JsAsyncContext::from(&runtime).await?; - /// let result = context.eval("await Promise.resolve(42)".to_string()).await?; - /// ``` - pub async fn from(rt: &JsAsyncRuntime) -> anyhow::Result { - let context = rquickjs::AsyncContext::full(&rt.rt).await?; - - // Initialize dynamic module storage - let dynamic_modules = Arc::new(RwLock::new(HashMap::>::new())); - - async_with!(context => |ctx| { - // Add dynamic modules storage to context user data - ctx.store_userdata(dynamic_modules.clone()) - .map_err(|e| anyhow!("Failed to store dynamic modules: {:?}", e)) - }) - .await?; - - Ok(Self { - ctx: context, - global_attachment: rt.global_attachment.clone(), - }) - } - - /// Evaluates JavaScript code with default options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval("Math.random()".to_string()).await?; - /// let async_result = context.eval("await Promise.resolve(42)".to_string()).await?; - /// ``` - pub async fn eval(&self, code: String) -> JsResult { - self.eval_with_options(code, JsEvalOptions::default()).await - } - - /// Evaluates JavaScript code with custom options asynchronously. - /// - /// # Parameters - /// - /// - `code`: The JavaScript code to execute - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Notes - /// - /// This method supports promise evaluation and top-level await. - pub async fn eval_with_options(&self, code: String, options: JsEvalOptions) -> JsResult { - async_with!(self.ctx => |ctx| { - if let Some(attachment) = &self.global_attachment { - if let Err(e) = attachment.clone().attach(&ctx) { - return JsResult::Err(JsError::context(e.to_string())); - } - } - let mut options = options; - options.promise = Some(true); - let res = ctx.eval_with_options(code, options.into()); - JsResult::from_promise_result(&ctx, res).await - }) - .await - } - - /// Evaluates JavaScript code from a file with default options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Errors - /// - /// Returns an error if the file cannot be read or execution fails. - pub async fn eval_file(&self, path: String) -> JsResult { - self.eval_file_with_options(path, JsEvalOptions::default()) - .await - } - - /// Evaluates JavaScript code from a file with custom options asynchronously. - /// - /// # Parameters - /// - /// - `path`: Path to the JavaScript file - /// - `options`: Evaluation options - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - pub async fn eval_file_with_options(&self, path: String, options: JsEvalOptions) -> JsResult { - async_with!(self.ctx => |ctx| { - if let Some(attachment) = &self.global_attachment { - if let Err(e) = attachment.clone().attach(&ctx) { - return JsResult::Err(JsError::context(e.to_string())); - } - } - let mut options = options; - options.promise = Some(true); - let res = ctx.eval_file_with_options(path, options.into()); - JsResult::from_promise_result(&ctx, res).await - }) - .await - } - - /// Evaluates a specific function from a module asynchronously. - /// - /// # Parameters - /// - /// - `module`: The name of the module containing the function - /// - `method`: The name of the function to call - /// - `params`: Optional parameters to pass to the function - /// - /// # Returns - /// - /// Returns the execution result as a `JsResult`. - /// - /// # Examples - /// - /// ```rust - /// let result = context.eval_function( - /// "my-module".to_string(), - /// "myFunction".to_string(), - /// Some(vec![JsValue::integer(42)]) - /// ).await?; - /// ``` - pub async fn eval_function( - &self, - module: String, - method: String, - params: Option>, - ) -> JsResult { - let params = params.unwrap_or_default(); - async_with!(self.ctx => |ctx| { - if let Some(attachment) = &self.global_attachment { - if let Err(e) = attachment.attach(&ctx) { - return JsResult::Err(JsError::context(format!("Failed to attach global context: {}", e))); - } - } - match Module::import(&ctx, module.clone()).catch(&ctx) { - Ok(promise) => { - match promise.into_future::().await.catch(&ctx) { - Ok(v) => { - if !v.is_object() { - return JsResult::Err(JsError::module(Some(module.clone()), None, "Is the module registered correctly?".to_string())); - } - let obj = match v.as_object() { - Some(o) => o, - None => return JsResult::Err(JsError::module(Some(module.clone()), None, "Is the module registered correctly?".to_string())), - }; - let m: rquickjs::Result = obj.get(&method); - match m.catch(&ctx) { - Ok(m) => { - if m.is_function() { - let func = match m.as_function() { - Some(f) => f, - None => return JsResult::Err(JsError::module(Some(module.clone()), Some(method.clone()), "Method not found in the module".to_string())), - }; - let res = func.call((rquickjs::function::Rest(params),)); - JsResult::from_promise_result(&ctx, res).await - } else { - JsResult::Err(JsError::module(Some(module.clone()), Some(method.clone()), "Method not found in the module".to_string())) - } - } - Err(e) => { - JsResult::Err(JsError::module(Some(module.clone()), Some(method.clone()), format!("Failed to get method: {}", e))) - } - } - } - Err(e) => { - JsResult::Err(JsError::module(Some(module.clone()), None, format!("Failed to import module: {}", e))) - } - } - } - Err(e) => JsResult::Err(JsError::module(Some(module.clone()), None, format!("Failed to import module: {}", e))) - } - }) - .await - } -} - -/// Represents an action that can be executed by the JavaScript engine. -/// -/// This enum defines the various operations that can be performed -/// by the JavaScript engine, including code evaluation, module management, -/// and dynamic module operations. -#[derive(Debug, Clone)] -pub enum JsAction { - /// Evaluate JavaScript code with optional evaluation options. - Eval { - /// Unique identifier for this action - id: u32, - /// The source code to evaluate (either inline code or file path) - source: JsCode, - /// Optional evaluation options - options: Option, - }, - /// Declare a new module in the dynamic module storage. - DeclareNewModule { - /// Unique identifier for this action - id: u32, - /// The module to declare - module: JsModule, - }, - /// Declare multiple new modules in the dynamic module storage. - DeclareNewModules { - /// Unique identifier for this action - id: u32, - /// List of modules to declare - modules: Vec, - }, - /// Clear all modules from the dynamic module storage. - ClearNewModules { - /// Unique identifier for this action - id: u32, - }, - /// Evaluate a module and return its result. - EvaluateModule { - /// Unique identifier for this action - id: u32, - /// The module to evaluate - module: JsModule, - }, - /// Get all newly declared modules from the dynamic module storage. - GetDeclaredModules { - /// Unique identifier for this action - id: u32, - }, - /// Check if a specific module is declared in the dynamic module storage. - IsModuleDeclared { - /// Unique identifier for this action - id: u32, - /// The name of the module to check - module_name: String, - }, -} - -/// Represents the result of a JavaScript action execution. -/// -/// This struct contains the result of an action execution along with -/// the action's unique identifier for correlation purposes. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub struct JsActionResult { - /// The unique identifier of the action that produced this result - pub id: u32, - /// The result of the action execution - pub result: JsResult, -} - -/// Represents a callback from the JavaScript engine to Dart. -/// -/// This enum defines the various types of callbacks that can be sent -/// from the JavaScript engine to the Dart side for communication. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub enum JsCallback { - /// Indicates that the engine has been initialized and is ready - Initialized, - /// Indicates the result of an action execution - Handler(JsActionResult), - /// Indicates a bridge call from JavaScript to Dart - Bridge(JsValue), -} - -/// Represents the result of handling a JavaScript callback. -/// -/// This enum defines the possible responses when handling callbacks -/// from the JavaScript engine. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub enum JsCallbackResult { - /// Indicates successful initialization handling - Initialized, - /// Indicates successful action handling - Handler, - /// Indicates the result of a bridge call - Bridge(JsResult), -} - -/// Core JavaScript engine implementation. -/// -/// This struct provides the core functionality for executing JavaScript -/// actions, managing state, and handling communication between Dart and JavaScript. -/// It operates asynchronously and supports concurrent execution of actions. -#[frb(opaque)] -pub struct JsEngineCore { - /// The asynchronous context for JavaScript execution - context: JsAsyncContext, - /// Channel for sending actions to the engine - sender: tokio::sync::mpsc::UnboundedSender, - /// Channel for receiving actions (wrapped in Arc> for thread safety) - receiver: Arc>>, - /// Atomic flag indicating if the engine has been disposed - disposed: AtomicBool, - /// Atomic flag indicating if the engine is currently running - running: AtomicBool, -} - -impl JsEngineCore { - /// Creates a new JavaScript engine core with the given context. - /// - /// # Parameters - /// - /// - `context`: The asynchronous context to use for JavaScript execution - /// - /// # Returns - /// - /// Returns a new `JsEngineCore` instance or an error if creation fails. - #[frb(sync)] - pub fn new(context: &JsAsyncContext) -> anyhow::Result { - let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); - Ok(Self { - context: context.clone(), - sender, - receiver: Arc::new(Mutex::new(receiver)), - disposed: AtomicBool::new(false), - running: AtomicBool::new(false), - }) - } - - /// Returns the asynchronous context used by this engine. - /// - /// # Returns - /// - /// Returns the `JsAsyncContext` instance. - #[frb(sync, getter)] - pub fn context(&self) -> JsAsyncContext { - self.context.clone() - } - - /// Checks if the engine has been disposed. - /// - /// # Returns - /// - /// Returns `true` if the engine is disposed, `false` otherwise. - #[frb(sync, getter)] - pub fn disposed(&self) -> bool { - self.disposed.load(Ordering::Acquire) - } - - /// Checks if the engine is currently running. - /// - /// # Returns - /// - /// Returns `true` if the engine is running, `false` otherwise. - #[frb(sync, getter)] - pub fn running(&self) -> bool { - self.running.load(Ordering::Acquire) - } - - /// Disposes the engine and cleans up resources. - /// - /// This method marks the engine as disposed and prevents further operations. - /// The actual cleanup happens when all references are dropped. - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed. - pub async fn dispose(&self) -> anyhow::Result<()> { - if self.disposed.load(Ordering::Acquire) { - return Err(anyhow!("Engine is disposed")); - } - - // Mark as disposed - self.disposed.store(true, Ordering::Release); - Ok(()) - } - - /// Executes an action on the engine. - /// - /// # Parameters - /// - /// - `action`: The action to execute - /// - /// # Errors - /// - /// Returns an error if the engine is disposed or if sending the action fails. - pub async fn exec(&self, action: JsAction) -> anyhow::Result<()> { - if self.disposed.load(Ordering::Acquire) { - return Err(anyhow!("Engine is disposed")); - } - self.sender - .send(action) - .map_err(|e| anyhow!("Failed to send action: {}", e))?; - Ok(()) - } - - /// Starts the engine event loop with a bridge callback. - /// - /// # Parameters - /// - /// - `bridge`: Callback function for handling communication between JavaScript and Dart - /// - /// # Errors - /// - /// Returns an error if the engine is already disposed or already running. - /// - /// # Examples - /// - /// ```rust - /// engine.start(|callback| { - /// match callback { - /// JsCallback::Initialized => { - /// println!("Engine initialized"); - /// JsCallbackResult::Initialized - /// } - /// JsCallback::Handler(result) => { - /// println!("Action completed: {:?}", result); - /// JsCallbackResult::Handler - /// } - /// JsCallback::Bridge(value) => { - /// println!("Bridge call: {:?}", value); - /// JsCallbackResult::Bridge(JsResult::Ok(value)) - /// } - /// } - /// }).await?; - /// ``` - pub async fn start( - &self, - bridge: impl Fn(JsCallback) -> DartFnFuture + Sync + Send + 'static, - ) -> anyhow::Result<()> { - if self.disposed.load(Ordering::Acquire) { - return Err(anyhow!("Engine is disposed")); - } - if self.running.load(Ordering::Acquire) { - return Err(anyhow!("Engine is already running")); - } - - // Set running flag - use a guard to ensure it's reset on early return - self.running.store(true, Ordering::Release); - - // Guard to ensure flags are properly reset - struct StateGuard<'a> { - running: &'a AtomicBool, - disposed: &'a AtomicBool, - } - - impl<'a> Drop for StateGuard<'a> { - fn drop(&mut self) { - self.running.store(false, Ordering::Release); - self.disposed.store(true, Ordering::Release); - } - } - - let _guard = StateGuard { - running: &self.running, - disposed: &self.disposed, - }; - - let cb = Arc::new(bridge); - - let result = async_with!(self.context.ctx => |ctx| { - if let Some(attachment) = &self.context.global_attachment { - if let Err(e) = attachment.attach(&ctx) { - return Err(anyhow!("Failed to attach global context: {}", e)); - } - } - if let Err(e) = register_fjs(ctx.clone(), cb.clone()) { - return Err(anyhow!("Failed to register fjs bridge: {}", e)); - } - - cb(JsCallback::Initialized).await; - - loop { - let mut receiver = self.receiver.lock().await; - match receiver.recv().await { - None => { - // Channel closed, exit loop - return Ok(()); - }, - Some(ev) => { - drop(receiver); - - let ctx_s = ctx.clone(); - let cb_clone = cb.clone(); - - ctx.spawn(async move { - Self::handle_action(ctx_s, cb_clone, ev).await; - }); - } - } - } - }) - .await; - - result - } - - /// Handles a single action from the event loop. - /// - /// This method processes individual actions and executes them - /// in the JavaScript context, then sends the results back via the bridge. - async fn handle_action( - ctx: rquickjs::Ctx<'_>, - cb: Arc DartFnFuture + Sync + Send + 'static>, - action: JsAction, - ) { - match action { - JsAction::Eval { - id, - source, - options, - } => { - let mut options = options.unwrap_or_default(); - options.promise = Some(true); - let res = match get_raw_source_code(source.clone()).await { - Err(e) => JsResult::Err(JsError::io( - match &source { - JsCode::Path(p) => Some(p.clone()), - JsCode::Code(_) | JsCode::Bytes(_) => None, - }, - e.to_string(), - )), - Ok(source_code) => { - let res = ctx.eval_with_options(source_code, options.into()); - JsResult::from_promise_result(&ctx, res).await - } - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - JsAction::DeclareNewModule { - id, - module: JsModule { name, source }, - } => { - let res = match get_raw_source_code(source.clone()).await { - Err(e) => JsResult::Err(JsError::io( - match &source { - JsCode::Path(p) => Some(p.clone()), - JsCode::Code(_) | JsCode::Bytes(_) => None, - }, - e.to_string(), - )), - Ok(source_code) => { - if let Some(modules_storage) = - ctx.userdata::>>>>() - { - modules_storage - .write() - .unwrap() - .insert(name.clone(), source_code.clone()); - JsResult::Ok(JsValue::None) - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - } - } - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - JsAction::EvaluateModule { - id, - module: JsModule { name, source }, - } => { - let res = match get_raw_source_code(source.clone()).await { - Err(e) => JsResult::Err(JsError::io( - match &source { - JsCode::Path(p) => Some(p.clone()), - JsCode::Code(_) | JsCode::Bytes(_) => None, - }, - e.to_string(), - )), - Ok(source_code) => { - // Ensure module is stored in dynamic module storage - if let Some(modules_storage) = - ctx.userdata::>>>>() - { - modules_storage - .write() - .unwrap() - .insert(name.clone(), source_code.clone()); - - // Evaluate module - let res = Module::evaluate(ctx.clone(), name.clone(), source_code); - JsResult::from_promise_result(&ctx, res).await - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - } - } - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - JsAction::ClearNewModules { id } => { - let res = if let Some(modules_storage) = - ctx.userdata::>>>>() - { - modules_storage.write().unwrap().clear(); - JsResult::Ok(JsValue::None) - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - JsAction::DeclareNewModules { id, modules } => { - let mut last_result = JsResult::Ok(JsValue::None); - for module in modules { - let res = match get_raw_source_code(module.source.clone()).await { - Err(e) => JsResult::Err(JsError::io( - match &module.source { - JsCode::Path(p) => Some(p.clone()), - JsCode::Code(_) | JsCode::Bytes(_) => None, - }, - e.to_string(), - )), - Ok(source_code) => { - if let Some(modules_storage) = - ctx.userdata::>>>>() - { - modules_storage - .write() - .unwrap() - .insert(module.name.clone(), source_code.clone()); - JsResult::Ok(JsValue::None) - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - } - } - }; - if let JsResult::Err(_) = &res { - last_result = res; - break; - } - } - let res = JsActionResult { - id, - result: last_result, - }; - cb(JsCallback::Handler(res)).await; - } - JsAction::GetDeclaredModules { id } => { - let res = if let Some(modules_storage) = - ctx.userdata::>>>>() - { - let modules = modules_storage.read().unwrap(); - let module_names = modules.keys().cloned().map(JsValue::String).collect(); - JsResult::Ok(JsValue::Array(module_names)) - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - JsAction::IsModuleDeclared { id, module_name } => { - let res = if let Some(modules_storage) = - ctx.userdata::>>>>() - { - let modules = modules_storage.read().unwrap(); - let is_declared = modules.contains_key(&module_name); - JsResult::Ok(JsValue::Boolean(is_declared)) - } else { - JsResult::Err(JsError::storage( - "Dynamic modules storage not initialized".to_string(), - )) - }; - let res = JsActionResult { id, result: res }; - cb(JsCallback::Handler(res)).await; - } - } - } -} - -/// Retrieves the raw source code from a JsCode source. -/// -/// This function resolves either inline code or file content -/// and returns the JavaScript source code as a string. -/// -/// # Parameters -/// -/// - `source`: The source to resolve (either inline code or file path) -/// -/// # Returns -/// -/// Returns the JavaScript source code as a string. -/// -/// # Errors -/// -/// Returns an error if: -/// - The file cannot be read -/// - The file size exceeds the maximum allowed size -async fn get_raw_source_code(source: JsCode) -> anyhow::Result> { - let code = match source { - JsCode::Code(code) => code.into_bytes(), - JsCode::Path(path) => { - // Check file size before reading - let metadata = tokio::fs::metadata(&path).await?; - let file_size = metadata.len(); - - if file_size > MAX_FILE_SIZE { - return Err(anyhow!( - "File size exceeds maximum allowed size: {} (size: {} bytes, max: {} bytes)", - path, - file_size, - MAX_FILE_SIZE - )); - } - - let mut f = tokio::fs::File::open(&path).await?; - let mut codes = Vec::with_capacity(file_size as usize); - f.read_to_end(&mut codes).await?; - codes - } - JsCode::Bytes(bytes) => bytes, - }; - Ok(code) -} - -/// Represents the result of a JavaScript operation. -/// -/// This enum provides a type-safe way to handle success and error cases -/// from JavaScript execution, with support for various error types. -#[frb(dart_metadata = ("freezed"), dart_code = " - bool get isOk => this is JsResult_Ok; - bool get isErr => this is JsResult_Err; - JsValue get ok => (this as JsResult_Ok).field0; - JsError get err => (this as JsResult_Err).field0; -")] -#[derive(Debug, Clone)] -pub enum JsResult { - /// Successful execution result - Ok(JsValue), - /// Error during execution - Err(JsError), -} - -/// Represents various types of JavaScript errors. -/// -/// This enum provides detailed error information for different -/// categories of errors that can occur during JavaScript execution. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub enum JsError { - /// Promise-related errors (async operation failures) - Promise(String), - /// Module-related errors (import/export failures) - Module { - /// Optional module name where the error occurred - module: Option, - /// Optional method name where the error occurred - method: Option, - /// Error message - message: String, - }, - /// Context attachment errors (global object setup failures) - Context(String), - /// Storage initialization errors (dynamic module storage failures) - Storage(String), - /// File I/O errors (file reading failures) - Io { - /// Optional file path where the error occurred - path: Option, - /// Error message - message: String, - }, - /// JavaScript runtime errors from QuickJS engine - Runtime(String), - /// Generic catch-all errors - Generic(String), - /// Engine lifecycle errors - Engine(String), - /// Bridge communication errors - Bridge(String), -} - -impl JsError { - /// Creates a new promise error. - #[frb(ignore)] - fn promise(msg: String) -> Self { - JsError::Promise(msg) - } - - /// Creates a new module error. - #[frb(ignore)] - fn module(module: Option, method: Option, message: String) -> Self { - JsError::Module { - module, - method, - message, - } - } - - /// Creates a new context error. - #[frb(ignore)] - fn context(msg: String) -> Self { - JsError::Context(msg) - } - - /// Creates a new storage error. - #[frb(ignore)] - fn storage(msg: String) -> Self { - JsError::Storage(msg) - } - - /// Creates a new I/O error. - #[frb(ignore)] - fn io(path: Option, message: String) -> Self { - JsError::Io { path, message } - } - - /// Creates a new runtime error. - #[frb(ignore)] - fn runtime(msg: String) -> Self { - JsError::Runtime(msg) - } - - /// Creates a new generic error. - #[frb(ignore)] - fn generic(msg: String) -> Self { - JsError::Generic(msg) - } - - /// Converts the error to a string representation. - /// - /// This method provides a human-readable description of the error, - /// including contextual information when available. - /// - /// # Returns - /// - /// Returns a string describing the error. - #[frb(sync)] - pub fn to_string(&self) -> String { - match self { - JsError::Promise(msg) => format!("Promise error: {}", msg), - JsError::Module { - module, - method, - message, - } => { - let mut parts = Vec::new(); - if let Some(m) = module { - parts.push(format!("module: {}", m)); - } - if let Some(m) = method { - parts.push(format!("method: {}", m)); - } - parts.push(format!("error: {}", message)); - format!("Module error - {}", parts.join(", ")) - } - JsError::Context(msg) => format!("Context error: {}", msg), - JsError::Storage(msg) => format!("Storage error: {}", msg), - JsError::Io { path, message } => { - if let Some(p) = path { - format!("IO error at {}: {}", p, message) - } else { - format!("IO error: {}", message) - } - } - JsError::Runtime(msg) => format!("Runtime error: {}", msg), - JsError::Generic(msg) => msg.clone(), - JsError::Engine(msg) => format!("Engine error: {}", msg), - JsError::Bridge(msg) => format!("Bridge error: {}", msg), - } - } -} - -impl JsResult { - /// Creates a new result from a promise execution result. - /// - /// This method handles the conversion from QuickJS promise results - /// to the FJS result type, including error handling. - async fn from_promise_result<'js>( - ctx: &rquickjs::Ctx<'js>, - res: rquickjs::Result>, - ) -> Self { - match res.catch(ctx) { - Ok(promise) => match promise.into_future::().await.catch(ctx) { - Ok(v) => match JsValue::from_js(ctx, v).catch(ctx) { - Ok(v) => JsResult::Ok(v), - Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - }, - Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - }, - Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - } - } - - /// Creates a new result from a synchronous execution result. - /// - /// This method handles the conversion from QuickJS value results - /// to the FJS result type, including error handling. - fn from_result<'js>( - ctx: &rquickjs::Ctx<'js>, - res: rquickjs::Result>, - ) -> Self { - res.catch(ctx) - .map(|v| JsValue::from_js(ctx, v)) - .map_or_else( - |e| JsResult::Err(JsError::runtime(e.to_string())), - |v| match v { - Ok(v) => JsResult::Ok(v), - Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - }, - ) - } -} - -/// Options for JavaScript code evaluation. -/// -/// This struct provides configuration options for how JavaScript -/// code should be executed and evaluated. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub struct JsEvalOptions { - /// Whether the code should be evaluated in global scope. - pub global: Option, - /// Whether strict mode should be enforced. - pub strict: Option, - /// Whether to create a backtrace barrier for error reporting. - pub backtrace_barrier: Option, - /// Whether to enable top-level await support. - pub promise: Option, -} - -impl JsEvalOptions { - /// Creates new evaluation options with the specified parameters. - /// - /// # Parameters - /// - /// - `global`: Whether to evaluate in global scope - /// - `strict`: Whether to enforce strict mode - /// - `backtrace_barrier`: Whether to create backtrace barriers - /// - `promise`: Whether to enable promise support - /// - /// # Returns - /// - /// Returns a new `JsEvalOptions` instance. - #[frb(sync)] - pub fn new( - global: Option, - strict: Option, - backtrace_barrier: Option, - promise: Option, - ) -> Self { - JsEvalOptions { - global, - strict, - backtrace_barrier, - promise, - } - } -} - -impl From for rquickjs::context::EvalOptions { - /// Converts FJS evaluation options to QuickJS evaluation options. - fn from(v: JsEvalOptions) -> Self { - let mut opts = rquickjs::context::EvalOptions::default(); - opts.global = v.global.unwrap_or(true); - opts.strict = v.strict.unwrap_or(true); - opts.backtrace_barrier = v.backtrace_barrier.unwrap_or(false); - opts.promise = v.promise.unwrap_or(false); - opts - } -} - -impl Default for JsEvalOptions { - /// Returns default evaluation options. - /// - /// Default options enable global scope and strict mode, - /// but disable backtrace barriers and promise support. - #[frb(ignore)] - fn default() -> Self { - JsEvalOptions { - global: Some(true), - strict: Some(true), - backtrace_barrier: Some(false), - promise: Some(false), - } - } -} - -/// Options for configuring builtin Node.js modules. -/// -/// This struct provides fine-grained control over which Node.js -/// compatibility modules should be available in the runtime. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone)] -pub struct JsBuiltinOptions { - /// Enable abort functionality - pub abort: Option, - /// Enable assert module - pub assert: Option, - /// Enable async_hooks module - pub async_hooks: Option, - /// Enable buffer module - pub buffer: Option, - /// Enable child_process module - pub child_process: Option, - /// Enable console module - pub console: Option, - /// Enable crypto module - pub crypto: Option, - /// Enable dns module - pub dns: Option, - /// Enable events module - pub events: Option, - /// Enable exceptions module - pub exceptions: Option, - /// Enable fetch functionality - pub fetch: Option, - /// Enable fs module - pub fs: Option, - /// Enable navigator object - pub navigator: Option, - /// Enable net module - pub net: Option, - /// Enable os module - pub os: Option, - /// Enable path module - pub path: Option, - /// Enable perf_hooks module - pub perf_hooks: Option, - /// Enable process module - pub process: Option, - /// Enable stream_web module - pub stream_web: Option, - /// Enable string_decoder module - pub string_decoder: Option, - /// Enable timers module - pub timers: Option, - /// Enable tty module - pub tty: Option, - /// Enable url module - pub url: Option, - /// Enable util module - pub util: Option, - /// Enable zlib module - pub zlib: Option, - /// Enable JSON utilities - pub json: Option, -} - -impl JsBuiltinOptions { - /// Creates builtin options with all modules enabled. - /// - /// # Returns - /// - /// Returns a `JsBuiltinOptions` instance with all available modules enabled. - #[frb(sync)] - pub fn all() -> Self { - JsBuiltinOptions { - abort: Some(true), - assert: Some(true), - async_hooks: Some(true), - buffer: Some(true), - child_process: Some(true), - console: Some(true), - crypto: Some(true), - dns: Some(true), - events: Some(true), - exceptions: Some(true), - fetch: Some(true), - fs: Some(true), - navigator: Some(true), - net: Some(true), - os: Some(true), - path: Some(true), - perf_hooks: Some(true), - process: Some(true), - stream_web: Some(true), - string_decoder: Some(true), - timers: Some(true), - tty: Some(true), - url: Some(true), - util: Some(true), - zlib: Some(true), - json: Some(true), - } - } -} - -impl Default for JsBuiltinOptions { - /// Returns default builtin options (all modules disabled). - /// - /// Default options have all modules set to `None`, meaning they - /// will not be included unless explicitly enabled. - #[frb(ignore)] - fn default() -> Self { - JsBuiltinOptions { - abort: None, - assert: None, - async_hooks: None, - buffer: None, - child_process: None, - console: None, - crypto: None, - dns: None, - events: None, - exceptions: None, - fetch: None, - fs: None, - navigator: None, - net: None, - os: None, - path: None, - perf_hooks: None, - process: None, - stream_web: None, - string_decoder: None, - timers: None, - tty: None, - url: None, - util: None, - zlib: None, - json: None, - } - } -} - -impl JsBuiltinOptions { - /// Converts builtin options to a module builder. - /// - /// This method creates a `ModuleBuilder` with the selected - /// builtin modules enabled according to the options. - #[frb(ignore)] - fn to_module_builder(&self) -> ModuleBuilder { - let mut builder = ModuleBuilder::new(); - - if self.abort.unwrap_or(false) { - builder = builder.with_global(llrt_abort::init); - } - if self.assert.unwrap_or(false) { - builder = builder.with_module(llrt_assert::AssertModule); - } - if self.async_hooks.unwrap_or(false) { - builder = builder - .with_global(llrt_async_hooks::init) - .with_module(llrt_async_hooks::AsyncHooksModule); - } - if self.buffer.unwrap_or(false) { - builder = builder - .with_global(llrt_buffer::init) - .with_module(llrt_buffer::BufferModule); - } - - if self.child_process.unwrap_or(false) { - builder = builder.with_module(llrt_child_process::ChildProcessModule); - } - - if self.console.unwrap_or(false) { - builder = builder - .with_global(llrt_console::init) - .with_module(llrt_console::ConsoleModule); - } - - if self.crypto.unwrap_or(false) { - builder = builder - .with_global(llrt_crypto::init) - .with_module(llrt_crypto::CryptoModule); - } - - if self.dns.unwrap_or(false) { - builder = builder.with_module(llrt_dns::DnsModule); - } - - if self.events.unwrap_or(false) { - builder = builder - .with_global(llrt_events::init) - .with_module(llrt_events::EventsModule); - } - - if self.exceptions.unwrap_or(false) { - builder = builder.with_global(llrt_exceptions::init); - } - - if self.fetch.unwrap_or(false) { - builder = builder.with_global(llrt_fetch::init); - } - - if self.fs.unwrap_or(false) { - builder = builder - .with_module(llrt_fs::FsPromisesModule) - .with_module(llrt_fs::FsModule); - } - - if self.navigator.unwrap_or(false) { - builder = builder.with_global(llrt_navigator::init); - } - - if self.net.unwrap_or(false) { - builder = builder.with_module(llrt_net::NetModule); - } - - #[cfg(not(target_os = "ios"))] - if self.os.unwrap_or(false) { - builder = builder.with_module(llrt_os::OsModule); - } - - if self.path.unwrap_or(false) { - builder = builder.with_module(llrt_path::PathModule); - } - - if self.perf_hooks.unwrap_or(false) { - builder = builder - .with_global(llrt_perf_hooks::init) - .with_module(llrt_perf_hooks::PerfHooksModule); - } - - if self.process.unwrap_or(false) { - builder = builder - .with_global(llrt_process::init) - .with_module(llrt_process::ProcessModule); - } - - if self.stream_web.unwrap_or(false) { - builder = builder - .with_global(llrt_stream_web::init) - .with_module(llrt_stream_web::StreamWebModule); - } - - if self.string_decoder.unwrap_or(false) { - builder = builder.with_module(llrt_string_decoder::StringDecoderModule); - } - - if self.timers.unwrap_or(false) { - builder = builder - .with_global(llrt_timers::init) - .with_module(llrt_timers::TimersModule); - } - - if self.tty.unwrap_or(false) { - builder = builder.with_module(llrt_tty::TtyModule); - } - - if self.url.unwrap_or(false) { - builder = builder - .with_global(llrt_url::init) - .with_module(llrt_url::UrlModule); - } - - if self.util.unwrap_or(false) { - builder = builder - .with_global(llrt_util::init) - .with_module(llrt_util::UtilModule); - } - - if self.zlib.unwrap_or(false) { - builder = builder.with_module(llrt_zlib::ZlibModule); - } - - if self.json.unwrap_or(false) { - builder = builder.with_global(llrt_json::redefine_static_methods); - } - - builder - } -} - -/// Represents a JavaScript module. -/// -/// This struct defines a module with a name and source code, -/// which can be loaded and executed in the JavaScript runtime. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub struct JsModule { - /// The module name (used for imports and identification) - pub name: String, - /// The source code for the module - pub source: JsCode, -} - -/// Represents the source of JavaScript code. -/// -/// This enum provides three ways to specify JavaScript source: -/// inline code as a string, a file path to load code from, or raw bytes. -#[frb(dart_metadata = ("freezed"))] -#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] -pub enum JsCode { - /// Inline JavaScript code - Code(String), - /// File path containing JavaScript code - Path(String), - /// Raw bytes containing JavaScript code (UTF-8 encoded) - Bytes(Vec), -} - -impl JsModule { - /// Creates a new module with the given name and source. - /// - /// # Parameters - /// - /// - `name`: The module name - /// - `source`: The module source code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - #[frb(sync)] - pub fn new(name: String, source: JsCode) -> Self { - JsModule { name, source } - } - - /// Creates a module from inline code. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `code`: The inline JavaScript code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::code( - /// "my-module".to_string(), - /// "export const value = 42;".to_string() - /// ); - /// ``` - #[frb(sync)] - pub fn code(module: String, code: String) -> Self { - JsModule { - name: module, - source: JsCode::Code(code), - } - } - - /// Creates a module from a file path. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `path`: The file path containing JavaScript code - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::path( - /// "my-module".to_string(), - /// "/path/to/module.js".to_string() - /// ); - /// ``` - #[frb(sync)] - pub fn path(module: String, path: String) -> Self { - JsModule { - name: module, - source: JsCode::Path(path), - } - } - - /// Creates a module from raw bytes. - /// - /// # Parameters - /// - /// - `module`: The module name - /// - `bytes`: The raw bytes containing JavaScript code (UTF-8 encoded) - /// - /// # Returns - /// - /// Returns a new `JsModule` instance. - /// - /// # Examples - /// - /// ```rust - /// let module = JsModule::bytes( - /// "my-module".to_string(), - /// vec![101, 120, 112, 111, 114, 116] // "export" - /// ); - /// ``` - #[frb(sync)] - pub fn bytes(module: String, bytes: Vec) -> Self { - JsModule { - name: module, - source: JsCode::Bytes(bytes), - } - } -} - -/// Registers the FJS bridge object in the JavaScript global scope. -/// -/// This function creates a global `fjs` object that provides -/// a bridge function for communication from JavaScript to Dart. -/// -/// # Parameters -/// -/// - `ctx`: The JavaScript context -/// - `bridge`: The bridge callback function -/// -/// # Returns -/// -/// Returns an error if registration fails. -fn register_fjs<'js>( - ctx: rquickjs::Ctx<'js>, - bridge: Arc DartFnFuture + Sync + Send + 'static>, -) -> rquickjs::CaughtResult<'js, ()> { - let fjs = Object::new(ctx.clone()).catch(&ctx)?; - fjs.set("bridge_call", new_bridge_call(ctx.clone(), bridge)?) - .catch(&ctx)?; - ctx.globals().set("fjs", fjs).catch(&ctx)?; - Ok(()) -} - -/// Creates a new bridge call function for JavaScript-to-Dart communication. -/// -/// This function creates a JavaScript function that can be called from -/// JavaScript to communicate with Dart via the bridge. -/// -/// # Parameters -/// -/// - `ctx`: The JavaScript context -/// - `bridge`: The bridge callback function -/// -/// # Returns -/// -/// Returns a new JavaScript function or an error if creation fails. -fn new_bridge_call<'js>( - ctx: rquickjs::Ctx<'js>, - bridge: Arc DartFnFuture + Sync + Send + 'static>, -) -> rquickjs::CaughtResult<'js, rquickjs::Function<'js>> { - let ctx_clone = ctx.clone(); - rquickjs::Function::new( - ctx.clone(), - move |args: rquickjs::function::Rest>| -> rquickjs::Result { - if args.0.len() > 1 { - return Err(rquickjs::Error::TooManyArgs { - expected: 1, - given: args.len(), - }); - } - if args.0.is_empty() { - return Err(rquickjs::Error::MissingArgs { - expected: 1, - given: 0, - }); - } - - let arg = args.0.first().ok_or_else(|| rquickjs::Error::MissingArgs { - expected: 1, - given: 0, - })?; - - let js_value = JsValue::from_js(&ctx, arg.clone())?; - let bridge_call = bridge.clone(); - let (promise, resolve, reject) = ctx.promise()?; - let ctx_s = ctx.clone(); - - ctx.spawn(async move { - let res = bridge_call(JsCallback::Bridge(js_value)).await; - if let JsCallbackResult::Bridge(res) = res { - match res { - JsResult::Ok(value) => { - let mut args = Args::new(ctx_s.clone(), 1); - if let Err(e) = args.push_arg(value) { - let mut reject_args = Args::new(ctx_s, 1); - let _ = reject_args.push_arg(format!("Internal error: {}", e)); - let _ = reject.call_arg::<()>(reject_args); - return; - } - let _ = resolve.call_arg::<()>(args); - } - JsResult::Err(err) => { - let mut args = Args::new(ctx_s, 1); - if let Err(_) = args.push_arg(err.to_string()) { - return; - } - let _ = reject.call_arg::<()>(args); - } - } - } - }); - Ok(promise) - }, - ) - .catch(&ctx_clone) -} diff --git a/libfjs/src/api/mod.rs b/libfjs/src/api/mod.rs index 5c52871..cf19b56 100644 --- a/libfjs/src/api/mod.rs +++ b/libfjs/src/api/mod.rs @@ -3,8 +3,11 @@ //! This module provides the core JavaScript execution API for Flutter integration. //! It contains submodules for different aspects of JavaScript runtime management: //! -//! - **js**: Runtime, context, and execution management +//! - **runtime**: Runtime and context management +//! - **engine**: High-level engine with action processing //! - **value**: Type-safe value conversion between Rust and JavaScript +//! - **error**: Comprehensive error types +//! - **source**: Source code and module definitions //! - **module**: Module system and dynamic loading capabilities //! //! ## Initialization @@ -12,9 +15,20 @@ //! The `init_app()` function sets up the Flutter Rust bridge with default utilities. //! This function should be called once during application initialization. -pub mod js; -pub mod value; +pub mod engine; +pub mod error; pub mod module; +pub mod runtime; +pub mod source; +pub mod value; + +// Re-export main types for convenience +pub use engine::{JsAction, JsActionResult, JsCallback, JsCallbackResult, JsEngineCore}; +pub use error::{JsError, JsResult}; +pub use module::{DynamicModuleLoader, DynamicModuleResolver, GlobalAttachment, ModuleBuilder}; +pub use runtime::{JsAsyncContext, JsAsyncRuntime, JsContext, JsRuntime, MemoryUsage}; +pub use source::{JsBuiltinOptions, JsCode, JsEvalOptions, JsModule}; +pub use value::JsValue; /// Initializes the Flutter Rust bridge with default user utilities. /// diff --git a/libfjs/src/api/module.rs b/libfjs/src/api/module.rs index c781838..32adaaa 100644 --- a/libfjs/src/api/module.rs +++ b/libfjs/src/api/module.rs @@ -21,6 +21,7 @@ //! - **Storage**: Manage dynamic module state //! - **Builders**: Configure runtime module systems +use crate::api::source::JsBuiltinOptions; use flutter_rust_bridge::frb; use llrt_utils::module::ModuleInfo; use rquickjs::loader::{Loader, ModuleLoader, Resolver}; @@ -42,29 +43,32 @@ pub struct DynamicModuleResolver {} impl Resolver for DynamicModuleResolver { /// Resolves a dynamic module name. /// - /// This method simply returns the module name as-is, assuming that - /// the module exists in the dynamic module storage. The actual - /// loading is handled by the `DynamicModuleLoader`. + /// This method checks if the module exists in the dynamic module storage. + /// If found, returns the module name; otherwise returns a resolving error. /// /// # Parameters /// /// - `ctx`: The JavaScript context - /// - `_base`: The base path (not used for dynamic modules) + /// - `base`: The base path for resolution /// - `name`: The module name to resolve /// /// # Returns /// - /// Returns the resolved module name. + /// Returns the resolved module name if found in storage. fn resolve<'js>( &mut self, ctx: &Ctx<'js>, - _base: &str, + base: &str, name: &str, ) -> rquickjs::Result { - if let Some(_modules_storage) = ctx.userdata::>>>>() { - return Ok(name.to_string()); + if let Some(modules_storage) = ctx.userdata::>>>>() { + let modules = modules_storage.read().unwrap(); + if modules.contains_key(name) { + return Ok(name.to_string()); + } } - Ok(name.to_string()) + // Not found in dynamic storage, let other resolvers try + Err(rquickjs::Error::new_resolving(base, name)) } } @@ -158,20 +162,27 @@ impl ModuleNames<'_> { /// Manages global object attachments for JavaScript contexts. /// /// This struct handles the attachment of global objects, functions, - /// and module names to JavaScript contexts. It ensures that global -/// state is properly initialized and maintained across context usage. +/// and module names to JavaScript contexts. Each context will be +/// initialized independently when attach() is called. #[frb(ignore)] #[derive(Debug, Default, Clone)] pub struct GlobalAttachment { - /// Inner implementation with atomic initialization tracking + /// Inner implementation with initialization data inner: Arc, } +/// Marker type to track if a context has been initialized with global attachments. +#[frb(ignore)] +struct GlobalAttachmentInitialized; + +unsafe impl<'js> JsLifetime<'js> for GlobalAttachmentInitialized { + type Changed<'to> = GlobalAttachmentInitialized; +} + /// Inner implementation of global attachment management. /// /// This struct contains the actual data for global attachments, -/// including module names, initialization functions, and an atomic -/// flag to track initialization state. +/// including module names and initialization functions. #[frb(ignore)] #[derive(Debug, Default)] struct GlobalAttachmentInner { @@ -179,8 +190,6 @@ struct GlobalAttachmentInner { names: HashSet, /// List of initialization functions to call functions: Vec) -> rquickjs::Result<()>>, - /// Atomic flag to track if initialization has occurred - initialized: std::sync::atomic::AtomicBool, } impl GlobalAttachment { @@ -234,8 +243,8 @@ impl GlobalAttachment { /// Attaches the global state to a JavaScript context. /// /// This method applies all registered module names and initialization functions - /// to the given context. It uses atomic operations to ensure that initialization - /// only happens once, even if called multiple times. + /// to the given context. It uses context-level userdata to ensure that each + /// context is only initialized once. /// /// # Parameters /// @@ -245,16 +254,14 @@ impl GlobalAttachment { /// /// Returns Ok if attachment succeeds, or an error if initialization fails. pub fn attach(&self, ctx: &Ctx<'_>) -> rquickjs::Result<()> { - // Only initialize once using atomic flag - if self - .inner - .initialized - .swap(true, std::sync::atomic::Ordering::AcqRel) - { - // Already initialized, skip + // Check if this context has already been initialized + if ctx.userdata::().is_some() { return Ok(()); } + // Mark this context as initialized + let _ = ctx.store_userdata(GlobalAttachmentInitialized); + if !self.inner.names.is_empty() { let _ = ctx.store_userdata(ModuleNames::new(self.inner.names.clone())); } @@ -403,3 +410,117 @@ impl ModuleBuilder { ) } } + +impl JsBuiltinOptions { + /// Converts builtin options to a module builder. + #[frb(ignore)] + pub fn to_module_builder(&self) -> ModuleBuilder { + let mut builder = ModuleBuilder::new(); + + if self.abort.unwrap_or(false) { + builder = builder.with_global(llrt_abort::init); + } + if self.assert.unwrap_or(false) { + builder = builder.with_module(llrt_assert::AssertModule); + } + if self.async_hooks.unwrap_or(false) { + builder = builder + .with_global(llrt_async_hooks::init) + .with_module(llrt_async_hooks::AsyncHooksModule); + } + if self.buffer.unwrap_or(false) { + builder = builder + .with_global(llrt_buffer::init) + .with_module(llrt_buffer::BufferModule); + } + if self.child_process.unwrap_or(false) { + builder = builder.with_module(llrt_child_process::ChildProcessModule); + } + if self.console.unwrap_or(false) { + builder = builder + .with_global(llrt_console::init) + .with_module(llrt_console::ConsoleModule); + } + if self.crypto.unwrap_or(false) { + builder = builder + .with_global(llrt_crypto::init) + .with_module(llrt_crypto::CryptoModule); + } + if self.dns.unwrap_or(false) { + builder = builder.with_module(llrt_dns::DnsModule); + } + if self.events.unwrap_or(false) { + builder = builder + .with_global(llrt_events::init) + .with_module(llrt_events::EventsModule); + } + if self.exceptions.unwrap_or(false) { + builder = builder.with_global(llrt_exceptions::init); + } + if self.fetch.unwrap_or(false) { + builder = builder.with_global(llrt_fetch::init); + } + if self.fs.unwrap_or(false) { + builder = builder + .with_module(llrt_fs::FsPromisesModule) + .with_module(llrt_fs::FsModule); + } + if self.navigator.unwrap_or(false) { + builder = builder.with_global(llrt_navigator::init); + } + if self.net.unwrap_or(false) { + builder = builder.with_module(llrt_net::NetModule); + } + #[cfg(not(target_os = "ios"))] + if self.os.unwrap_or(false) { + builder = builder.with_module(llrt_os::OsModule); + } + if self.path.unwrap_or(false) { + builder = builder.with_module(llrt_path::PathModule); + } + if self.perf_hooks.unwrap_or(false) { + builder = builder + .with_global(llrt_perf_hooks::init) + .with_module(llrt_perf_hooks::PerfHooksModule); + } + if self.process.unwrap_or(false) { + builder = builder + .with_global(llrt_process::init) + .with_module(llrt_process::ProcessModule); + } + if self.stream_web.unwrap_or(false) { + builder = builder + .with_global(llrt_stream_web::init) + .with_module(llrt_stream_web::StreamWebModule); + } + if self.string_decoder.unwrap_or(false) { + builder = builder.with_module(llrt_string_decoder::StringDecoderModule); + } + if self.timers.unwrap_or(false) { + builder = builder + .with_global(llrt_timers::init) + .with_module(llrt_timers::TimersModule); + } + if self.tty.unwrap_or(false) { + builder = builder.with_module(llrt_tty::TtyModule); + } + if self.url.unwrap_or(false) { + builder = builder + .with_global(llrt_url::init) + .with_module(llrt_url::UrlModule); + } + if self.util.unwrap_or(false) { + builder = builder + .with_global(llrt_util::init) + .with_module(llrt_util::UtilModule); + } + if self.zlib.unwrap_or(false) { + builder = builder.with_module(llrt_zlib::ZlibModule); + } + if self.json.unwrap_or(false) { + builder = builder.with_global(llrt_json::redefine_static_methods); + } + + builder + } +} diff --git a/libfjs/src/api/runtime.rs b/libfjs/src/api/runtime.rs new file mode 100644 index 0000000..8da9041 --- /dev/null +++ b/libfjs/src/api/runtime.rs @@ -0,0 +1,613 @@ +//! # Runtime and Context Management +//! +//! This module provides the core runtime and context types for JavaScript execution. +//! It includes both synchronous and asynchronous variants with a unified interface. + +use crate::api::error::{JsError, JsResult}; +use crate::api::module::{ + DynamicModuleLoader, DynamicModuleResolver, GlobalAttachment, ModuleBuilder, +}; +use crate::api::source::{get_raw_source_code, JsBuiltinOptions, JsEvalOptions, JsModule}; +use crate::api::value::JsValue; +use flutter_rust_bridge::frb; +use rquickjs::loader::{BuiltinLoader, BuiltinResolver, FileResolver, NativeLoader, ScriptLoader}; +use rquickjs::{async_with, CatchResultExt, FromJs, Module, Promise}; +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +/// Memory usage statistics for the JavaScript runtime. +#[frb(opaque)] +#[derive(Clone)] +pub struct MemoryUsage(pub(crate) rquickjs::qjs::JSMemoryUsage); + +macro_rules! proxy_memory_usage_getter { + ($($name:ident),+) => { + impl MemoryUsage { + $( + #[frb(sync, getter)] + pub fn $name(&self) -> i64 { self.0.$name } + )+ + } + }; +} + +proxy_memory_usage_getter!( + malloc_size, + malloc_limit, + memory_used_size, + malloc_count, + memory_used_count, + atom_count, + atom_size, + str_count, + str_size, + obj_count, + obj_size, + prop_count, + prop_size, + shape_count, + shape_size, + js_func_count, + js_func_size, + js_func_code_size, + js_func_pc2line_count, + js_func_pc2line_size, + c_func_count, + array_count, + fast_array_count, + fast_array_elements, + binary_object_count, + binary_object_size +); + +impl MemoryUsage { + /// Returns total memory used in bytes. + #[frb(sync, getter)] + pub fn total_memory(&self) -> i64 { + self.0.memory_used_size + } + + /// Returns total allocation count. + #[frb(sync, getter)] + pub fn total_allocations(&self) -> i64 { + self.0.malloc_count + } + + /// Returns a human-readable summary of memory usage. + #[frb(sync)] + pub fn summary(&self) -> String { + format!( + "Memory: {} bytes, Objects: {}, Functions: {}, Strings: {}", + self.0.memory_used_size, self.0.obj_count, self.0.js_func_count, self.0.str_count + ) + } +} + +/// A synchronous JavaScript runtime. +#[frb(opaque)] +#[derive(Clone)] +pub struct JsRuntime { + pub(crate) rt: rquickjs::Runtime, + pub(crate) global_attachment: Option, +} + +impl JsRuntime { + /// Creates a new JavaScript runtime with default configuration. + #[frb(sync)] + pub fn new() -> anyhow::Result { + let runtime = rquickjs::Runtime::new()?; + Ok(Self { + rt: runtime, + global_attachment: None, + }) + } + + /// Creates a new JavaScript runtime with custom builtin modules. + pub async fn with_options( + builtin: Option, + additional: Option>, + ) -> anyhow::Result { + let runtime = rquickjs::Runtime::new()?; + let ( + module_resolver, + module_loader, + additional_resolver, + additional_loader, + global_attachment, + ) = Self::build_loaders(builtin, additional).await?; + + let dynamic_resolver = DynamicModuleResolver::default(); + let dynamic_loader = DynamicModuleLoader::default(); + + let resolver = ( + module_resolver, + additional_resolver, + BuiltinResolver::default(), + dynamic_resolver, + FileResolver::default(), + ); + let loader = ( + module_loader, + additional_loader, + BuiltinLoader::default(), + dynamic_loader, + NativeLoader::default(), + ScriptLoader::default(), + ); + runtime.set_loader(resolver, loader); + + Ok(Self { + rt: runtime, + global_attachment: Some(global_attachment), + }) + } + + async fn build_loaders( + builtin: Option, + additional: Option>, + ) -> anyhow::Result<( + crate::api::module::ModuleResolver, + rquickjs::loader::ModuleLoader, + BuiltinResolver, + BuiltinLoader, + GlobalAttachment, + )> { + let (module_resolver, module_loader, global_attachment) = + if let Some(builtin_options) = builtin { + builtin_options.to_module_builder().build() + } else { + ModuleBuilder::new().build() + }; + + let mut additional_resolver = BuiltinResolver::default(); + let mut additional_loader = BuiltinLoader::default(); + + if let Some(additional_modules) = additional { + for module in additional_modules { + let code = get_raw_source_code(module.source).await?; + additional_resolver = additional_resolver.with_module(&module.name); + additional_loader = additional_loader.with_module(&module.name, code); + } + } + + Ok(( + module_resolver, + module_loader, + additional_resolver, + additional_loader, + global_attachment, + )) + } + + /// Sets the memory limit for the runtime. + #[frb(sync)] + pub fn set_memory_limit(&self, limit: usize) { + self.rt.set_memory_limit(limit); + } + + /// Sets the maximum stack size. + #[frb(sync)] + pub fn set_max_stack_size(&self, limit: usize) { + self.rt.set_max_stack_size(limit); + } + + /// Sets the garbage collection threshold. + #[frb(sync)] + pub fn set_gc_threshold(&self, threshold: usize) { + self.rt.set_gc_threshold(threshold); + } + + /// Forces garbage collection. + #[frb(sync)] + pub fn run_gc(&self) { + self.rt.run_gc(); + } + + /// Returns memory usage statistics. + #[frb(sync)] + pub fn memory_usage(&self) -> MemoryUsage { + MemoryUsage(self.rt.memory_usage()) + } + + /// Checks if there are pending jobs. + #[frb(sync)] + pub fn is_job_pending(&self) -> bool { + self.rt.is_job_pending() + } + + /// Executes a pending job. + #[frb(sync)] + pub fn execute_pending_job(&self) -> anyhow::Result { + self.rt + .execute_pending_job() + .map_err(|e| anyhow::anyhow!(e)) + } + + /// Sets dump flags for debugging. + #[frb(sync)] + pub fn set_dump_flags(&self, flags: u64) { + self.rt.set_dump_flags(flags); + } + + /// Sets runtime info string. + #[frb(sync)] + pub fn set_info(&self, info: String) -> anyhow::Result<()> { + self.rt.set_info(info)?; + Ok(()) + } +} + +/// A synchronous JavaScript execution context. +#[frb(opaque)] +#[derive(Clone)] +pub struct JsContext { + pub(crate) ctx: rquickjs::Context, + pub(crate) global_attachment: Option, +} + +impl JsContext { + /// Creates a new context from a runtime. + #[frb(sync)] + pub fn new(rt: &JsRuntime) -> anyhow::Result { + let context = rquickjs::Context::full(&rt.rt)?; + Ok(Self { + ctx: context, + global_attachment: rt.global_attachment.clone(), + }) + } + + /// Evaluates JavaScript code. + #[frb(sync)] + pub fn eval(&self, code: String) -> JsResult { + self.eval_with_options(code, JsEvalOptions::defaults()) + } + + /// Evaluates JavaScript code with options. + #[frb(sync)] + pub fn eval_with_options(&self, code: String, options: JsEvalOptions) -> JsResult { + if options.promise.unwrap_or(false) { + return JsResult::Err(JsError::promise( + "Promise not supported in sync context", + )); + } + self.ctx.with(|ctx| { + if let Some(attachment) = &self.global_attachment { + if let Err(e) = attachment.attach(&ctx) { + return JsResult::Err(JsError::context(format!( + "Failed to attach global context: {}", + e + ))); + } + } + let res = ctx.eval_with_options(code, options.into()); + result_from_sync(&ctx, res) + }) + } + + /// Evaluates JavaScript code from a file. + #[frb(sync)] + pub fn eval_file(&self, path: String) -> JsResult { + self.eval_file_with_options(path, JsEvalOptions::defaults()) + } + + /// Evaluates JavaScript code from a file with options. + #[frb(sync)] + pub fn eval_file_with_options(&self, path: String, options: JsEvalOptions) -> JsResult { + if options.promise.unwrap_or(false) { + return JsResult::Err(JsError::promise( + "Promise not supported in sync context", + )); + } + self.ctx.with(|ctx| { + if let Some(attachment) = &self.global_attachment { + if let Err(e) = attachment.attach(&ctx) { + return JsResult::Err(JsError::context(format!( + "Failed to attach global context: {}", + e + ))); + } + } + let res = ctx.eval_file_with_options(path, options.into()); + result_from_sync(&ctx, res) + }) + } +} + +/// An asynchronous JavaScript runtime. +#[frb(opaque)] +#[derive(Clone)] +pub struct JsAsyncRuntime { + pub(crate) rt: rquickjs::AsyncRuntime, + pub(crate) global_attachment: Option, +} + +impl JsAsyncRuntime { + /// Creates a new async runtime with default configuration. + #[frb(sync)] + pub fn new() -> anyhow::Result { + let runtime = rquickjs::AsyncRuntime::new()?; + Ok(Self { + rt: runtime, + global_attachment: None, + }) + } + + /// Creates a new async runtime with custom configuration. + pub async fn with_options( + builtin: Option, + additional: Option>, + ) -> anyhow::Result { + let runtime = rquickjs::AsyncRuntime::new()?; + let ( + module_resolver, + module_loader, + additional_resolver, + additional_loader, + global_attachment, + ) = JsRuntime::build_loaders(builtin, additional).await?; + + let dynamic_resolver = DynamicModuleResolver::default(); + let dynamic_loader = DynamicModuleLoader::default(); + + let resolver = ( + module_resolver, + additional_resolver, + BuiltinResolver::default(), + dynamic_resolver, + FileResolver::default(), + ); + let loader = ( + module_loader, + additional_loader, + BuiltinLoader::default(), + dynamic_loader, + NativeLoader::default(), + ScriptLoader::default(), + ); + runtime.set_loader(resolver, loader).await; + + Ok(Self { + rt: runtime, + global_attachment: Some(global_attachment), + }) + } + + /// Sets the memory limit. + pub async fn set_memory_limit(&self, limit: usize) { + self.rt.set_memory_limit(limit).await; + } + + /// Sets the maximum stack size. + pub async fn set_max_stack_size(&self, limit: usize) { + self.rt.set_max_stack_size(limit).await; + } + + /// Sets the garbage collection threshold. + pub async fn set_gc_threshold(&self, threshold: usize) { + self.rt.set_gc_threshold(threshold).await; + } + + /// Forces garbage collection. + pub async fn run_gc(&self) { + self.rt.run_gc().await; + } + + /// Returns memory usage statistics. + pub async fn memory_usage(&self) -> MemoryUsage { + MemoryUsage(self.rt.memory_usage().await) + } + + /// Checks if there are pending jobs. + pub async fn is_job_pending(&self) -> bool { + self.rt.is_job_pending().await + } + + /// Executes a pending job. + pub async fn execute_pending_job(&self) -> anyhow::Result { + self.rt + .execute_pending_job() + .await + .map_err(|e| anyhow::anyhow!(e)) + } + + /// Puts the runtime into idle state. + pub async fn idle(&self) { + self.rt.idle().await; + } + + /// Sets runtime info string. + pub async fn set_info(&self, info: String) -> anyhow::Result<()> { + self.rt.set_info(info).await?; + Ok(()) + } +} + +/// An asynchronous JavaScript execution context. +#[frb(opaque)] +#[derive(Clone)] +pub struct JsAsyncContext { + pub(crate) ctx: rquickjs::AsyncContext, + pub(crate) global_attachment: Option, +} + +impl JsAsyncContext { + /// Creates a new async context from a runtime. + pub async fn from(rt: &JsAsyncRuntime) -> anyhow::Result { + let context = rquickjs::AsyncContext::full(&rt.rt).await?; + let dynamic_modules = Arc::new(RwLock::new(HashMap::>::new())); + + async_with!(context => |ctx| { + ctx.store_userdata(dynamic_modules.clone()) + .map_err(|e| anyhow::anyhow!("Failed to store dynamic modules: {:?}", e)) + }) + .await?; + + Ok(Self { + ctx: context, + global_attachment: rt.global_attachment.clone(), + }) + } + + /// Evaluates JavaScript code. + pub async fn eval(&self, code: String) -> JsResult { + self.eval_with_options(code, JsEvalOptions::with_promise()).await + } + + /// Evaluates JavaScript code with options. + pub async fn eval_with_options(&self, code: String, options: JsEvalOptions) -> JsResult { + async_with!(self.ctx => |ctx| { + if let Some(attachment) = &self.global_attachment { + if let Err(e) = attachment.clone().attach(&ctx) { + return JsResult::Err(JsError::context(e.to_string())); + } + } + let mut options = options; + options.promise = Some(true); + let res = ctx.eval_with_options(code, options.into()); + result_from_promise(&ctx, res).await + }) + .await + } + + /// Evaluates JavaScript code from a file. + pub async fn eval_file(&self, path: String) -> JsResult { + self.eval_file_with_options(path, JsEvalOptions::with_promise()).await + } + + /// Evaluates JavaScript code from a file with options. + pub async fn eval_file_with_options(&self, path: String, options: JsEvalOptions) -> JsResult { + async_with!(self.ctx => |ctx| { + if let Some(attachment) = &self.global_attachment { + if let Err(e) = attachment.clone().attach(&ctx) { + return JsResult::Err(JsError::context(e.to_string())); + } + } + let mut options = options; + options.promise = Some(true); + let res = ctx.eval_file_with_options(path, options.into()); + result_from_promise(&ctx, res).await + }) + .await + } + + /// Evaluates a function from a module. + pub async fn eval_function( + &self, + module: String, + method: String, + params: Option>, + ) -> JsResult { + let params = params.unwrap_or_default(); + async_with!(self.ctx => |ctx| { + if let Some(attachment) = &self.global_attachment { + if let Err(e) = attachment.attach(&ctx) { + return JsResult::Err(JsError::context(format!( + "Failed to attach global context: {}", + e + ))); + } + } + + match Module::import(&ctx, module.clone()).catch(&ctx) { + Ok(promise) => { + match promise.into_future::().await.catch(&ctx) { + Ok(v) => { + if !v.is_object() { + return JsResult::Err(JsError::module( + Some(module), + None, + "Module is not an object", + )); + } + let obj = match v.as_object() { + Some(o) => o, + None => { + return JsResult::Err(JsError::module( + Some(module), + None, + "Module is not an object", + )) + } + }; + let m: rquickjs::Result = obj.get(&method); + match m.catch(&ctx) { + Ok(m) => { + if m.is_function() { + let func = match m.as_function() { + Some(f) => f, + None => { + return JsResult::Err(JsError::module( + Some(module), + Some(method), + "Method not found", + )) + } + }; + let res = + func.call((rquickjs::function::Rest(params),)); + result_from_promise(&ctx, res).await + } else { + JsResult::Err(JsError::module( + Some(module), + Some(method), + "Method not found", + )) + } + } + Err(e) => JsResult::Err(JsError::module( + Some(module), + Some(method), + format!("Failed to get method: {}", e), + )), + } + } + Err(e) => JsResult::Err(JsError::module( + Some(module), + None, + format!("Failed to import module: {}", e), + )), + } + } + Err(e) => JsResult::Err(JsError::module( + Some(module), + None, + format!("Failed to import module: {}", e), + )), + } + }) + .await + } +} + +/// Helper function to convert sync result. +fn result_from_sync<'js>( + ctx: &rquickjs::Ctx<'js>, + res: rquickjs::Result>, +) -> JsResult { + res.catch(ctx) + .map(|v| JsValue::from_js(ctx, v)) + .map_or_else( + |e| JsResult::Err(JsError::runtime(e.to_string())), + |v| match v { + Ok(v) => JsResult::Ok(v), + Err(e) => JsResult::Err(JsError::runtime(e.to_string())), + }, + ) +} + +/// Helper function to convert promise result. +pub(crate) async fn result_from_promise<'js>( + ctx: &rquickjs::Ctx<'js>, + res: rquickjs::Result>, +) -> JsResult { + match res.catch(ctx) { + Ok(promise) => match promise.into_future::().await.catch(ctx) { + Ok(v) => match JsValue::from_js(ctx, v).catch(ctx) { + Ok(v) => JsResult::Ok(v), + Err(e) => JsResult::Err(JsError::runtime(e.to_string())), + }, + Err(e) => JsResult::Err(JsError::runtime(e.to_string())), + }, + Err(e) => JsResult::Err(JsError::runtime(e.to_string())), + } +} diff --git a/libfjs/src/api/source.rs b/libfjs/src/api/source.rs new file mode 100644 index 0000000..d62beff --- /dev/null +++ b/libfjs/src/api/source.rs @@ -0,0 +1,440 @@ +//! # JavaScript Source Code Types +//! +//! This module provides types for representing JavaScript source code, +//! modules, and evaluation options. + +use flutter_rust_bridge::frb; + +/// Maximum file size for JavaScript source files (10 MB) +pub const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024; + +/// Represents the source of JavaScript code. +/// +/// This enum provides three ways to specify JavaScript source: +/// inline code as a string, a file path to load code from, or raw bytes. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub enum JsCode { + /// Inline JavaScript code as a string + Code(String), + /// File path containing JavaScript code + Path(String), + /// Raw bytes containing JavaScript code (UTF-8 encoded) + Bytes(Vec), +} + +impl JsCode { + /// Creates inline code source. + #[frb(ignore)] + pub fn code(code: String) -> Self { + JsCode::Code(code) + } + + /// Creates file path source. + #[frb(ignore)] + pub fn path(path: String) -> Self { + JsCode::Path(path) + } + + /// Creates bytes source. + #[frb(ignore)] + pub fn bytes(bytes: Vec) -> Self { + JsCode::Bytes(bytes) + } + + /// Returns the file path if this is a Path variant. + #[frb(ignore)] + pub fn as_path(&self) -> Option<&str> { + match self { + JsCode::Path(p) => Some(p), + _ => None, + } + } + + /// Returns true if this is a Path variant. + #[frb(sync)] + pub fn is_path(&self) -> bool { + matches!(self, JsCode::Path(_)) + } + + /// Returns true if this is a Code variant. + #[frb(sync)] + pub fn is_code(&self) -> bool { + matches!(self, JsCode::Code(_)) + } + + /// Returns true if this is a Bytes variant. + #[frb(sync)] + pub fn is_bytes(&self) -> bool { + matches!(self, JsCode::Bytes(_)) + } +} + +/// Represents a JavaScript module. +/// +/// This struct defines a module with a name and source code, +/// which can be loaded and executed in the JavaScript runtime. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] +pub struct JsModule { + /// The module name (used for imports and identification) + pub name: String, + /// The source code for the module + pub source: JsCode, +} + +impl JsModule { + /// Creates a new module with the given name and source. + #[frb(sync)] + pub fn new(name: String, source: JsCode) -> Self { + JsModule { name, source } + } + + /// Creates a module from inline code. + #[frb(ignore)] + pub fn code(module: String, code: String) -> Self { + JsModule { + name: module, + source: JsCode::Code(code), + } + } + + /// Creates a module from a file path. + #[frb(ignore)] + pub fn path(module: String, path: String) -> Self { + JsModule { + name: module, + source: JsCode::Path(path), + } + } + + /// Creates a module from raw bytes. + #[frb(ignore)] + pub fn bytes(module: String, bytes: Vec) -> Self { + JsModule { + name: module, + source: JsCode::Bytes(bytes), + } + } + + /// Creates a module from inline code string. + #[frb(sync, name = "fromCode")] + pub fn from_code(module: String, code: String) -> Self { + JsModule { + name: module, + source: JsCode::Code(code), + } + } + + /// Creates a module from a file path string. + #[frb(sync, name = "fromPath")] + pub fn from_path(module: String, path: String) -> Self { + JsModule { + name: module, + source: JsCode::Path(path), + } + } + + /// Creates a module from raw bytes. + #[frb(sync, name = "fromBytes")] + pub fn from_bytes(module: String, bytes: Vec) -> Self { + JsModule { + name: module, + source: JsCode::Bytes(bytes), + } + } +} + +/// Options for JavaScript code evaluation. +/// +/// This struct provides configuration options for how JavaScript +/// code should be executed and evaluated. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone, Default)] +pub struct JsEvalOptions { + /// Whether the code should be evaluated in global scope. + pub global: Option, + /// Whether strict mode should be enforced. + pub strict: Option, + /// Whether to create a backtrace barrier for error reporting. + pub backtrace_barrier: Option, + /// Whether to enable top-level await support. + pub promise: Option, +} + +impl JsEvalOptions { + /// Creates new evaluation options with the specified parameters. + #[frb(sync)] + pub fn new( + global: Option, + strict: Option, + backtrace_barrier: Option, + promise: Option, + ) -> Self { + JsEvalOptions { + global, + strict, + backtrace_barrier, + promise, + } + } + + /// Creates options with default values (global scope, strict mode). + #[frb(sync)] + pub fn defaults() -> Self { + JsEvalOptions { + global: Some(true), + strict: Some(true), + backtrace_barrier: Some(false), + promise: Some(false), + } + } + + /// Creates options with promise support enabled. + #[frb(sync)] + pub fn with_promise() -> Self { + JsEvalOptions { + global: Some(true), + strict: Some(true), + backtrace_barrier: Some(false), + promise: Some(true), + } + } + + /// Creates options for module evaluation. + #[frb(sync)] + pub fn module() -> Self { + JsEvalOptions { + global: Some(false), // Module scope + strict: Some(true), + backtrace_barrier: Some(false), + promise: Some(true), + } + } +} + +impl From for rquickjs::context::EvalOptions { + fn from(v: JsEvalOptions) -> Self { + let mut opts = rquickjs::context::EvalOptions::default(); + opts.global = v.global.unwrap_or(true); + opts.strict = v.strict.unwrap_or(true); + opts.backtrace_barrier = v.backtrace_barrier.unwrap_or(false); + opts.promise = v.promise.unwrap_or(false); + opts + } +} + +/// Options for configuring builtin Node.js modules. +/// +/// This struct provides fine-grained control over which Node.js +/// compatibility modules should be available in the runtime. +#[frb(dart_metadata = ("freezed"))] +#[derive(Debug, Clone, Default)] +pub struct JsBuiltinOptions { + /// Enable abort functionality + pub abort: Option, + /// Enable assert module + pub assert: Option, + /// Enable async_hooks module + pub async_hooks: Option, + /// Enable buffer module + pub buffer: Option, + /// Enable child_process module + pub child_process: Option, + /// Enable console module + pub console: Option, + /// Enable crypto module + pub crypto: Option, + /// Enable dns module + pub dns: Option, + /// Enable events module + pub events: Option, + /// Enable exceptions module + pub exceptions: Option, + /// Enable fetch functionality + pub fetch: Option, + /// Enable fs module + pub fs: Option, + /// Enable navigator object + pub navigator: Option, + /// Enable net module + pub net: Option, + /// Enable os module + pub os: Option, + /// Enable path module + pub path: Option, + /// Enable perf_hooks module + pub perf_hooks: Option, + /// Enable process module + pub process: Option, + /// Enable stream_web module + pub stream_web: Option, + /// Enable string_decoder module + pub string_decoder: Option, + /// Enable timers module + pub timers: Option, + /// Enable tty module + pub tty: Option, + /// Enable url module + pub url: Option, + /// Enable util module + pub util: Option, + /// Enable zlib module + pub zlib: Option, + /// Enable JSON utilities + pub json: Option, +} + +impl JsBuiltinOptions { + /// Creates builtin options with all modules enabled. + #[frb(sync)] + pub fn all() -> Self { + JsBuiltinOptions { + abort: Some(true), + assert: Some(true), + async_hooks: Some(true), + buffer: Some(true), + child_process: Some(true), + console: Some(true), + crypto: Some(true), + dns: Some(true), + events: Some(true), + exceptions: Some(true), + fetch: Some(true), + fs: Some(true), + navigator: Some(true), + net: Some(true), + os: Some(true), + path: Some(true), + perf_hooks: Some(true), + process: Some(true), + stream_web: Some(true), + string_decoder: Some(true), + timers: Some(true), + tty: Some(true), + url: Some(true), + util: Some(true), + zlib: Some(true), + json: Some(true), + } + } + + /// Creates builtin options with no modules enabled. + #[frb(sync)] + pub fn none() -> Self { + JsBuiltinOptions::default() + } + + /// Creates builtin options with essential modules only. + /// Includes: console, timers, buffer, util, json + #[frb(sync)] + pub fn essential() -> Self { + JsBuiltinOptions { + console: Some(true), + timers: Some(true), + buffer: Some(true), + util: Some(true), + json: Some(true), + ..Default::default() + } + } + + /// Creates builtin options for web-like environment. + /// Includes: console, timers, fetch, url, crypto, stream_web + #[frb(sync)] + pub fn web() -> Self { + JsBuiltinOptions { + console: Some(true), + timers: Some(true), + fetch: Some(true), + url: Some(true), + crypto: Some(true), + stream_web: Some(true), + navigator: Some(true), + exceptions: Some(true), + json: Some(true), + ..Default::default() + } + } + + /// Creates builtin options for Node.js-like environment. + /// Includes most modules except OS-specific ones. + #[frb(sync)] + pub fn node() -> Self { + JsBuiltinOptions { + abort: Some(true), + assert: Some(true), + async_hooks: Some(true), + buffer: Some(true), + console: Some(true), + crypto: Some(true), + dns: Some(true), + events: Some(true), + exceptions: Some(true), + fs: Some(true), + path: Some(true), + perf_hooks: Some(true), + process: Some(true), + stream_web: Some(true), + string_decoder: Some(true), + timers: Some(true), + url: Some(true), + util: Some(true), + json: Some(true), + ..Default::default() + } + } +} + +/// Retrieves the raw source code from a JsCode source. +#[frb(ignore)] +pub async fn get_raw_source_code(source: JsCode) -> anyhow::Result> { + let code = match source { + JsCode::Code(code) => code.into_bytes(), + JsCode::Path(path) => { + // Check file size before reading + let metadata = tokio::fs::metadata(&path).await?; + let file_size = metadata.len(); + + if file_size > MAX_FILE_SIZE { + return Err(anyhow::anyhow!( + "File size exceeds maximum allowed size: {} (size: {} bytes, max: {} bytes)", + path, + file_size, + MAX_FILE_SIZE + )); + } + + // Use tokio::fs::read directly for better efficiency + tokio::fs::read(&path).await? + } + JsCode::Bytes(bytes) => bytes, + }; + Ok(code) +} + +/// Synchronously retrieves the raw source code from a JsCode source. +#[frb(ignore)] +pub fn get_raw_source_code_sync(source: JsCode) -> anyhow::Result> { + let code = match source { + JsCode::Code(code) => code.into_bytes(), + JsCode::Path(path) => { + // Check file size before reading + let metadata = std::fs::metadata(&path)?; + let file_size = metadata.len(); + + if file_size > MAX_FILE_SIZE { + return Err(anyhow::anyhow!( + "File size exceeds maximum allowed size: {} (size: {} bytes, max: {} bytes)", + path, + file_size, + MAX_FILE_SIZE + )); + } + + std::fs::read(&path)? + } + JsCode::Bytes(bytes) => bytes, + }; + Ok(code) +} diff --git a/libfjs/src/api/value.rs b/libfjs/src/api/value.rs index 74928f9..bcdbb43 100644 --- a/libfjs/src/api/value.rs +++ b/libfjs/src/api/value.rs @@ -11,8 +11,10 @@ //! - **BigInt Support**: Safe handling of large integers //! - **Type Safety**: Compile-time and runtime type checking //! - **Zero-copy**: Efficient conversion where possible +//! - **ArrayBuffer/TypedArray**: Binary data support use flutter_rust_bridge::frb; +use rquickjs::function::Constructor; use rquickjs::{Ctx, FromAtom, FromJs, IntoJs, Null, Type}; use std::collections::HashMap; @@ -21,29 +23,10 @@ use std::collections::HashMap; /// This enum provides a comprehensive representation of all JavaScript value types, /// enabling safe and efficient conversion between JavaScript and Rust/Dart values. /// Each variant corresponds to a specific JavaScript type. -/// -/// ## Variants -/// -/// - `None`: Represents `null` or `undefined` in JavaScript -/// - `Boolean`: Represents JavaScript boolean values -/// - `Integer`: Represents JavaScript numbers that fit in 64-bit integers -/// - `Float`: Represents JavaScript floating-point numbers -/// - `Bigint`: Represents JavaScript BigInt values (stored as strings for precision) -/// - `String`: Represents JavaScript string values -/// - `Array`: Represents JavaScript arrays with nested value support -/// - `Object`: Represents JavaScript objects with string keys and arbitrary values -/// -/// ## Examples -/// -/// ```rust -/// // Creating values -/// let num = JsValue::Integer(42); -/// let str = JsValue::String("hello".to_string()); -/// let arr = JsValue::Array(vec![JsValue::Integer(1), JsValue::Integer(2)]); -/// ``` -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] #[frb(dart_metadata = ("freezed"), dart_code = r#" + /// Creates a JsValue from any Dart object. static JsValue from(Object? any) { if (any == null) { return const JsValue.none(); @@ -57,6 +40,8 @@ use std::collections::HashMap; return JsValue.bigint(any.toString()); } else if (any is String) { return JsValue.string(any); + } else if (any is Uint8List) { + return JsValue.bytes(any); } else if (any is List) { return JsValue.array(any.map((e) => from(e)).toList()); } else if (any is Map) { @@ -68,6 +53,7 @@ use std::collections::HashMap; } } + /// Gets the underlying Dart value. dynamic get value => when( none: () => null, boolean: (v) => v, @@ -75,25 +61,36 @@ use std::collections::HashMap; float: (v) => v, bigint: (v) => BigInt.parse(v), string: (v) => v, + bytes: (v) => v, array: (v) => v.map((e) => e.value).toList(), object: (v) => v.map((key, value) => MapEntry(key, value.value)), + date: (ms) => DateTime.fromMillisecondsSinceEpoch(ms.toInt()), + symbol: (v) => v, + function: (v) => v, ); - bool get isNone => this is JsValue_None; - - bool get isBoolean => this is JsValue_Boolean; - - bool get isInteger => this is JsValue_Integer; - - bool get isFloat => this is JsValue_Float; - - bool get isBigint => this is JsValue_Bigint; - - bool get isString => this is JsValue_String; + /// Safe casting methods + bool? get asBoolean => this is JsValue_Boolean ? (this as JsValue_Boolean).field0 : null; + int? get asInteger => this is JsValue_Integer ? (this as JsValue_Integer).field0 : null; + double? get asFloat => this is JsValue_Float ? (this as JsValue_Float).field0 : null; + String? get asBigint => this is JsValue_Bigint ? (this as JsValue_Bigint).field0 : null; + String? get asString => this is JsValue_String ? (this as JsValue_String).field0 : null; + Uint8List? get asBytes => this is JsValue_Bytes ? (this as JsValue_Bytes).field0 : null; + List? get asArray => this is JsValue_Array ? (this as JsValue_Array).field0 : null; + Map? get asObject => this is JsValue_Object ? (this as JsValue_Object).field0 : null; - bool get isArray => this is JsValue_Array; - - bool get isObject => this is JsValue_Object; + /// Converts to num if possible. + num? get asNum { + if (this is JsValue_Integer) return (this as JsValue_Integer).field0; + if (this is JsValue_Float) return (this as JsValue_Float).field0; + if (this is JsValue_Bigint) { + final bigint = BigInt.parse((this as JsValue_Bigint).field0); + if (bigint >= BigInt.from(-9007199254740991) && bigint <= BigInt.from(9007199254740991)) { + return bigint.toInt(); + } + } + return null; + } "#)] pub enum JsValue { /// Represents null or undefined values in JavaScript @@ -108,43 +105,185 @@ pub enum JsValue { Bigint(String), /// Represents string values String(String), + /// Represents binary data (ArrayBuffer/TypedArray) + Bytes(Vec), /// Represents arrays with nested value support Array(Vec), /// Represents objects with string keys and arbitrary values Object(HashMap), + /// Represents Date objects (milliseconds since epoch) + Date(i64), + /// Represents Symbol values (description) + Symbol(String), + /// Represents function references (serialized name/id) + Function(String), +} + +impl Default for JsValue { + fn default() -> Self { + JsValue::None + } +} + +impl JsValue { + /// Creates a None value. + #[frb(ignore)] + pub fn none() -> Self { + JsValue::None + } + + /// Creates a boolean value. + #[frb(ignore)] + pub fn boolean(v: bool) -> Self { + JsValue::Boolean(v) + } + + /// Creates an integer value. + #[frb(ignore)] + pub fn integer(v: i64) -> Self { + JsValue::Integer(v) + } + + /// Creates a float value. + #[frb(ignore)] + pub fn float(v: f64) -> Self { + JsValue::Float(v) + } + + /// Creates a bigint value from a string. + #[frb(ignore)] + pub fn bigint>(v: S) -> Self { + JsValue::Bigint(v.into()) + } + + /// Creates a string value. + #[frb(ignore)] + pub fn string>(v: S) -> Self { + JsValue::String(v.into()) + } + + /// Creates a bytes value. + #[frb(ignore)] + pub fn bytes(v: Vec) -> Self { + JsValue::Bytes(v) + } + + /// Creates an array value. + #[frb(ignore)] + pub fn array(v: Vec) -> Self { + JsValue::Array(v) + } + + /// Creates an object value. + #[frb(ignore)] + pub fn object(v: HashMap) -> Self { + JsValue::Object(v) + } + + /// Creates a date value from milliseconds since epoch. + #[frb(ignore)] + pub fn date(ms: i64) -> Self { + JsValue::Date(ms) + } + + /// Returns true if the value is None. + #[frb(sync)] + pub fn is_none(&self) -> bool { + matches!(self, JsValue::None) + } + + /// Returns true if the value is a boolean. + #[frb(sync)] + pub fn is_boolean(&self) -> bool { + matches!(self, JsValue::Boolean(_)) + } + + /// Returns true if the value is a number (integer, float, or bigint). + #[frb(sync)] + pub fn is_number(&self) -> bool { + matches!( + self, + JsValue::Integer(_) | JsValue::Float(_) | JsValue::Bigint(_) + ) + } + + /// Returns true if the value is a string. + #[frb(sync)] + pub fn is_string(&self) -> bool { + matches!(self, JsValue::String(_)) + } + + /// Returns true if the value is an array. + #[frb(sync)] + pub fn is_array(&self) -> bool { + matches!(self, JsValue::Array(_)) + } + + /// Returns true if the value is an object. + #[frb(sync)] + pub fn is_object(&self) -> bool { + matches!(self, JsValue::Object(_)) + } + + /// Returns true if the value is a Date. + #[frb(sync)] + pub fn is_date(&self) -> bool { + matches!(self, JsValue::Date(_)) + } + + /// Returns true if the value is bytes (binary data). + #[frb(sync)] + pub fn is_bytes(&self) -> bool { + matches!(self, JsValue::Bytes(_)) + } + + /// Returns true if the value is a primitive type. + #[frb(sync)] + pub fn is_primitive(&self) -> bool { + matches!( + self, + JsValue::None + | JsValue::Boolean(_) + | JsValue::Integer(_) + | JsValue::Float(_) + | JsValue::Bigint(_) + | JsValue::String(_) + ) + } + + /// Returns the type name of this value. + #[frb(sync)] + pub fn type_name(&self) -> String { + match self { + JsValue::None => "null".to_string(), + JsValue::Boolean(_) => "boolean".to_string(), + JsValue::Integer(_) => "number".to_string(), + JsValue::Float(_) => "number".to_string(), + JsValue::Bigint(_) => "bigint".to_string(), + JsValue::String(_) => "string".to_string(), + JsValue::Bytes(_) => "ArrayBuffer".to_string(), + JsValue::Array(_) => "Array".to_string(), + JsValue::Object(_) => "Object".to_string(), + JsValue::Date(_) => "Date".to_string(), + JsValue::Symbol(_) => "symbol".to_string(), + JsValue::Function(_) => "function".to_string(), + } + } } impl<'js> FromJs<'js> for JsValue { /// Converts a JavaScript value to a JsValue enum. - /// - /// This method handles type conversion from QuickJS values to the FJS - /// JsValue representation, preserving type information and handling - /// complex nested structures. - /// - /// # Parameters - /// - /// - `ctx`: The JavaScript context - /// - `value`: The QuickJS value to convert - /// - /// # Returns - /// - /// Returns the converted JsValue or a conversion error. - /// - /// # Notes - /// - /// - BigInt values are converted to strings to preserve precision - /// - Function, Symbol, and other unsupported types are converted to None - /// - Arrays and Objects are recursively converted - #[frb(ignore)] fn from_js(ctx: &Ctx<'js>, value: rquickjs::Value<'js>) -> rquickjs::Result { let v = match value.type_of() { Type::String => { - let s = value.as_string() + let s = value + .as_string() .ok_or_else(|| rquickjs::Error::new_from_js("value", "String"))?; JsValue::String(s.to_string()?) } Type::Array => { - let arr = value.as_array() + let arr = value + .as_array() .ok_or_else(|| rquickjs::Error::new_from_js("value", "Array"))?; let mut vec = Vec::with_capacity(arr.len()); for item in arr.iter() { @@ -155,8 +294,30 @@ impl<'js> FromJs<'js> for JsValue { JsValue::Array(vec) } Type::Object => { - let obj = value.as_object() + let obj = value + .as_object() .ok_or_else(|| rquickjs::Error::new_from_js("value", "Object"))?; + + // Check for ArrayBuffer + if let Some(ab) = rquickjs::ArrayBuffer::from_object(obj.clone()) { + let bytes: Vec = ab.as_bytes().map(|b| b.to_vec()).unwrap_or_default(); + return Ok(JsValue::Bytes(bytes)); + } + + // Check for Date object by looking at constructor name + if let Ok(constructor) = obj.get::<_, rquickjs::Function>("constructor") { + if let Ok(name) = constructor.get::<_, String>("name") { + if name == "Date" { + if let Ok(get_time) = obj.get::<_, rquickjs::Function>("getTime") { + if let Ok(ms) = get_time.call::<_, f64>(()) { + return Ok(JsValue::Date(ms as i64)); + } + } + } + } + } + + // Regular object let mut map = HashMap::new(); for prop in obj.props() { let (k, v) = prop?; @@ -166,35 +327,85 @@ impl<'js> FromJs<'js> for JsValue { JsValue::Object(map) } Type::Int => { - let i = value.as_int() + let i = value + .as_int() .ok_or_else(|| rquickjs::Error::new_from_js("value", "Int"))?; JsValue::Integer(i as i64) } Type::Bool => { - let b = value.as_bool() + let b = value + .as_bool() .ok_or_else(|| rquickjs::Error::new_from_js("value", "Bool"))?; JsValue::Boolean(b) } Type::Float => { - let f = value.as_float() + let f = value + .as_float() .ok_or_else(|| rquickjs::Error::new_from_js("value", "Float"))?; JsValue::Float(f) } Type::BigInt => { - // Convert BigInt to string to avoid precision loss - // eval a JS expression to convert BigInt to string - let bigint_ref = value.as_ref(); - let code = format!("(function(v){{ return String(v); }})"); - let converter: rquickjs::Function = ctx.eval(code)?; - let result: rquickjs::String = converter.call((bigint_ref,))?; - JsValue::Bigint(result.to_string()?) + // Convert BigInt using native rquickjs API + if let Some(bigint) = value.as_big_int() { + // Try to convert to i64 first, if it fails, use string representation + match bigint.clone().to_i64() { + Ok(v) => JsValue::Bigint(v.to_string()), + Err(_) => { + // For very large BigInts, use JSON.stringify approach + let global = ctx.globals(); + if let Ok(json) = global.get::<_, rquickjs::Object>("JSON") { + if let Ok(stringify) = + json.get::<_, rquickjs::Function>("stringify") + { + if let Ok(s) = stringify.call::<_, rquickjs::String>((value,)) + { + return Ok(JsValue::Bigint(s.to_string()?)); + } + } + } + // Fallback + JsValue::Bigint("0".to_string()) + } + } + } else { + JsValue::None + } + } + Type::Symbol => { + // Get symbol description using native rquickjs Symbol API + if let Some(symbol) = value.as_symbol() { + match symbol.description() { + Ok(desc) => { + if desc.is_undefined() { + JsValue::Symbol(String::new()) + } else if let Some(s) = desc.as_string() { + JsValue::Symbol(s.to_string().unwrap_or_default()) + } else { + JsValue::Symbol(String::new()) + } + } + Err(_) => JsValue::Symbol(String::new()), + } + } else { + JsValue::Symbol(String::new()) + } + } + Type::Function => { + // Serialize function name if available + if let Some(func) = value.as_function() { + if let Ok(name) = func.get::<_, String>("name") { + JsValue::Function(name) + } else { + JsValue::Function("".to_string()) + } + } else { + JsValue::None + } } Type::Uninitialized | Type::Undefined | Type::Null - | Type::Symbol | Type::Constructor - | Type::Function | Type::Promise | Type::Exception | Type::Module @@ -206,49 +417,116 @@ impl<'js> FromJs<'js> for JsValue { impl<'js> IntoJs<'js> for JsValue { /// Converts a JsValue to a JavaScript value. - /// - /// This method handles type conversion from the FJS JsValue representation - /// to QuickJS values, enabling data to be passed to JavaScript code. - /// - /// # Parameters - /// - /// - `ctx`: The JavaScript context - /// - /// # Returns - /// - /// Returns the converted JavaScript value or a conversion error. - /// - /// # Notes - /// - /// - BigInt values are parsed from strings to create proper JavaScript BigInts - /// - Arrays and Objects are recursively converted - /// - Null values are converted to JavaScript null - #[frb(ignore)] fn into_js(self, ctx: &Ctx<'js>) -> rquickjs::Result> { match self { - JsValue::String(v) => rquickjs::String::from_str(ctx.clone(), &v)?.into_js(ctx), + JsValue::None => Null.into_js(ctx), + JsValue::Boolean(v) => Ok(rquickjs::Value::new_bool(ctx.clone(), v)), JsValue::Integer(v) => Ok(rquickjs::Value::new_number(ctx.clone(), v as _)), + JsValue::Float(v) => Ok(rquickjs::Value::new_float(ctx.clone(), v)), + JsValue::Bigint(v) => { + let value = rquickjs::String::from_str(ctx.clone(), &v)?.into_js(ctx)?; + rquickjs::BigInt::from_value(value).into_js(ctx) + } + JsValue::String(v) => rquickjs::String::from_str(ctx.clone(), &v)?.into_js(ctx), + JsValue::Bytes(v) => { + let ab = rquickjs::ArrayBuffer::new(ctx.clone(), v)?; + ab.into_js(ctx) + } JsValue::Array(v) => { - let x = rquickjs::Array::new(ctx.clone())?; - for (i, v) in v.into_iter().enumerate() { - x.set(i, v.into_js(ctx)?)?; + let arr = rquickjs::Array::new(ctx.clone())?; + for (i, item) in v.into_iter().enumerate() { + arr.set(i, item.into_js(ctx)?)?; } - x.into_js(ctx) + arr.into_js(ctx) } JsValue::Object(v) => { - let x = rquickjs::Object::new(ctx.clone())?; - for kv in v.into_iter() { - x.set(kv.0, kv.1.into_js(ctx)?)?; + let obj = rquickjs::Object::new(ctx.clone())?; + for (k, val) in v.into_iter() { + obj.set(k, val.into_js(ctx)?)?; } - x.into_js(ctx) + obj.into_js(ctx) } - JsValue::Boolean(v) => Ok(rquickjs::Value::new_bool(ctx.clone(), v)), - JsValue::Float(v) => Ok(rquickjs::Value::new_float(ctx.clone(), v)), - JsValue::Bigint(v) => { - let value = rquickjs::String::from_str(ctx.clone(), &v)?.into_js(ctx)?; - rquickjs::BigInt::from_value(value).into_js(ctx) + JsValue::Date(ms) => { + // Create a Date object using the constructor + let global = ctx.globals(); + let date_constructor: Constructor = global.get("Date")?; + let date = date_constructor.construct::<_, rquickjs::Value>((ms as f64,))?; + Ok(date) } - JsValue::None => Null.into_js(ctx), + JsValue::Symbol(desc) => { + let global = ctx.globals(); + let symbol_constructor: rquickjs::Function = global.get("Symbol")?; + let symbol = symbol_constructor.call::<_, rquickjs::Value>((desc,))?; + Ok(symbol) + } + JsValue::Function(_) => { + // Cannot recreate functions, return undefined + Ok(rquickjs::Value::new_undefined(ctx.clone())) + } + } + } +} + +// Implement From traits for common types +impl From for JsValue { + fn from(v: bool) -> Self { + JsValue::Boolean(v) + } +} + +impl From for JsValue { + fn from(v: i32) -> Self { + JsValue::Integer(v as i64) + } +} + +impl From for JsValue { + fn from(v: i64) -> Self { + JsValue::Integer(v) + } +} + +impl From for JsValue { + fn from(v: f64) -> Self { + JsValue::Float(v) + } +} + +impl From for JsValue { + fn from(v: String) -> Self { + JsValue::String(v) + } +} + +impl From<&str> for JsValue { + fn from(v: &str) -> Self { + JsValue::String(v.to_string()) + } +} + +impl From> for JsValue { + fn from(v: Vec) -> Self { + JsValue::Bytes(v) + } +} + +impl> From> for JsValue { + fn from(v: Vec) -> Self { + JsValue::Array(v.into_iter().map(|x| x.into()).collect()) + } +} + +impl> From> for JsValue { + fn from(v: Option) -> Self { + match v { + Some(v) => v.into(), + None => JsValue::None, } } } + +impl From<()> for JsValue { + fn from(_: ()) -> Self { + JsValue::None + } +} diff --git a/libfjs/src/frb_generated.rs b/libfjs/src/frb_generated.rs index 4eabfca..5752784 100644 --- a/libfjs/src/frb_generated.rs +++ b/libfjs/src/frb_generated.rs @@ -25,7 +25,8 @@ // Section: imports -use crate::api::js::*; +use crate::api::engine::*; +use crate::api::runtime::*; use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable}; use flutter_rust_bridge::{Handler, IntoIntoDart}; @@ -38,7 +39,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.11.1"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 2034567146; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 869436497; // Section: executor @@ -46,7 +47,7 @@ flutter_rust_bridge::frb_generated_default_handler!(); // Section: wire_funcs -fn wire__crate__api__js__JsAsyncContext_eval_impl( +fn wire__crate__api__runtime__JsAsyncContext_eval_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -94,7 +95,8 @@ fn wire__crate__api__js__JsAsyncContext_eval_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncContext::eval(&*api_that_guard, api_code).await, + crate::api::runtime::JsAsyncContext::eval(&*api_that_guard, api_code) + .await, )?; Ok(output_ok) })() @@ -104,7 +106,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_impl( }, ) } -fn wire__crate__api__js__JsAsyncContext_eval_file_impl( +fn wire__crate__api__runtime__JsAsyncContext_eval_file_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -152,8 +154,11 @@ fn wire__crate__api__js__JsAsyncContext_eval_file_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncContext::eval_file(&*api_that_guard, api_path) - .await, + crate::api::runtime::JsAsyncContext::eval_file( + &*api_that_guard, + api_path, + ) + .await, )?; Ok(output_ok) })() @@ -163,7 +168,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_file_impl( }, ) } -fn wire__crate__api__js__JsAsyncContext_eval_file_with_options_impl( +fn wire__crate__api__runtime__JsAsyncContext_eval_file_with_options_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -189,7 +194,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_file_with_options_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); let api_path = ::sse_decode(&mut deserializer); - let api_options = ::sse_decode(&mut deserializer); + let api_options = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, ()>( @@ -212,7 +217,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_file_with_options_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncContext::eval_file_with_options( + crate::api::runtime::JsAsyncContext::eval_file_with_options( &*api_that_guard, api_path, api_options, @@ -227,7 +232,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_file_with_options_impl( }, ) } -fn wire__crate__api__js__JsAsyncContext_eval_function_impl( +fn wire__crate__api__runtime__JsAsyncContext_eval_function_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -278,7 +283,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_function_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncContext::eval_function( + crate::api::runtime::JsAsyncContext::eval_function( &*api_that_guard, api_module, api_method, @@ -294,7 +299,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_function_impl( }, ) } -fn wire__crate__api__js__JsAsyncContext_eval_with_options_impl( +fn wire__crate__api__runtime__JsAsyncContext_eval_with_options_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -320,7 +325,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_with_options_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); let api_code = ::sse_decode(&mut deserializer); - let api_options = ::sse_decode(&mut deserializer); + let api_options = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, ()>( @@ -343,7 +348,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_with_options_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncContext::eval_with_options( + crate::api::runtime::JsAsyncContext::eval_with_options( &*api_that_guard, api_code, api_options, @@ -358,7 +363,7 @@ fn wire__crate__api__js__JsAsyncContext_eval_with_options_impl( }, ) } -fn wire__crate__api__js__JsAsyncContext_from_impl( +fn wire__crate__api__runtime__JsAsyncContext_from_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -402,7 +407,7 @@ fn wire__crate__api__js__JsAsyncContext_from_impl( } let api_rt_guard = api_rt_guard.unwrap(); let output_ok = - crate::api::js::JsAsyncContext::from(&*api_rt_guard).await?; + crate::api::runtime::JsAsyncContext::from(&*api_rt_guard).await?; Ok(output_ok) })() .await, @@ -411,7 +416,7 @@ fn wire__crate__api__js__JsAsyncContext_from_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_execute_pending_job_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_execute_pending_job_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -457,9 +462,10 @@ fn wire__crate__api__js__JsAsyncRuntime_execute_pending_job_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::js::JsAsyncRuntime::execute_pending_job(&*api_that_guard) - .await?; + let output_ok = crate::api::runtime::JsAsyncRuntime::execute_pending_job( + &*api_that_guard, + ) + .await?; Ok(output_ok) })() .await, @@ -468,7 +474,7 @@ fn wire__crate__api__js__JsAsyncRuntime_execute_pending_job_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_idle_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_idle_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -515,7 +521,7 @@ fn wire__crate__api__js__JsAsyncRuntime_idle_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsAsyncRuntime::idle(&*api_that_guard).await; + crate::api::runtime::JsAsyncRuntime::idle(&*api_that_guard).await; })?; Ok(output_ok) })() @@ -525,7 +531,7 @@ fn wire__crate__api__js__JsAsyncRuntime_idle_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_is_job_pending_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_is_job_pending_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -572,7 +578,8 @@ fn wire__crate__api__js__JsAsyncRuntime_is_job_pending_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncRuntime::is_job_pending(&*api_that_guard).await, + crate::api::runtime::JsAsyncRuntime::is_job_pending(&*api_that_guard) + .await, )?; Ok(output_ok) })() @@ -582,7 +589,7 @@ fn wire__crate__api__js__JsAsyncRuntime_is_job_pending_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_memory_usage_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_memory_usage_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -629,7 +636,8 @@ fn wire__crate__api__js__JsAsyncRuntime_memory_usage_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::JsAsyncRuntime::memory_usage(&*api_that_guard).await, + crate::api::runtime::JsAsyncRuntime::memory_usage(&*api_that_guard) + .await, )?; Ok(output_ok) })() @@ -639,7 +647,7 @@ fn wire__crate__api__js__JsAsyncRuntime_memory_usage_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_new_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_new_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -663,14 +671,14 @@ fn wire__crate__api__js__JsAsyncRuntime_new_impl( deserializer.end(); transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || { - let output_ok = crate::api::js::JsAsyncRuntime::new()?; + let output_ok = crate::api::runtime::JsAsyncRuntime::new()?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsAsyncRuntime_run_gc_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_run_gc_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -717,7 +725,7 @@ fn wire__crate__api__js__JsAsyncRuntime_run_gc_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsAsyncRuntime::run_gc(&*api_that_guard).await; + crate::api::runtime::JsAsyncRuntime::run_gc(&*api_that_guard).await; })?; Ok(output_ok) })() @@ -727,7 +735,7 @@ fn wire__crate__api__js__JsAsyncRuntime_run_gc_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_set_gc_threshold_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_set_gc_threshold_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -775,7 +783,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_gc_threshold_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsAsyncRuntime::set_gc_threshold( + crate::api::runtime::JsAsyncRuntime::set_gc_threshold( &*api_that_guard, api_threshold, ) @@ -789,7 +797,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_gc_threshold_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_set_info_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_set_info_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -836,9 +844,11 @@ fn wire__crate__api__js__JsAsyncRuntime_set_info_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - crate::api::js::JsAsyncRuntime::set_info(&*api_that_guard, api_info) - .await?; + let output_ok = crate::api::runtime::JsAsyncRuntime::set_info( + &*api_that_guard, + api_info, + ) + .await?; Ok(output_ok) })() .await, @@ -847,7 +857,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_info_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_set_max_stack_size_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_set_max_stack_size_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -895,7 +905,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_max_stack_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsAsyncRuntime::set_max_stack_size( + crate::api::runtime::JsAsyncRuntime::set_max_stack_size( &*api_that_guard, api_limit, ) @@ -909,7 +919,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_max_stack_size_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_set_memory_limit_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_set_memory_limit_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -957,7 +967,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_memory_limit_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsAsyncRuntime::set_memory_limit( + crate::api::runtime::JsAsyncRuntime::set_memory_limit( &*api_that_guard, api_limit, ) @@ -971,7 +981,7 @@ fn wire__crate__api__js__JsAsyncRuntime_set_memory_limit_impl( }, ) } -fn wire__crate__api__js__JsAsyncRuntime_with_options_impl( +fn wire__crate__api__runtime__JsAsyncRuntime_with_options_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -994,14 +1004,14 @@ fn wire__crate__api__js__JsAsyncRuntime_with_options_impl( let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_builtin = - >::sse_decode(&mut deserializer); + >::sse_decode(&mut deserializer); let api_additional = - >>::sse_decode(&mut deserializer); + >>::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || async move { - let output_ok = crate::api::js::JsAsyncRuntime::with_options( + let output_ok = crate::api::runtime::JsAsyncRuntime::with_options( api_builtin, api_additional, ) @@ -1014,7 +1024,7 @@ fn wire__crate__api__js__JsAsyncRuntime_with_options_impl( }, ) } -fn wire__crate__api__js__JsContext_eval_impl( +fn wire__crate__api__runtime__JsContext_eval_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1055,7 +1065,7 @@ fn wire__crate__api__js__JsContext_eval_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsContext::eval( + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::JsContext::eval( &*api_that_guard, api_code, ))?; @@ -1064,7 +1074,7 @@ fn wire__crate__api__js__JsContext_eval_impl( }, ) } -fn wire__crate__api__js__JsContext_eval_file_impl( +fn wire__crate__api__runtime__JsContext_eval_file_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1105,7 +1115,7 @@ fn wire__crate__api__js__JsContext_eval_file_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsContext::eval_file( + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::JsContext::eval_file( &*api_that_guard, api_path, ))?; @@ -1114,7 +1124,7 @@ fn wire__crate__api__js__JsContext_eval_file_impl( }, ) } -fn wire__crate__api__js__JsContext_eval_file_with_options_impl( +fn wire__crate__api__runtime__JsContext_eval_file_with_options_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1139,7 +1149,7 @@ fn wire__crate__api__js__JsContext_eval_file_with_options_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); let api_path = ::sse_decode(&mut deserializer); - let api_options = ::sse_decode(&mut deserializer); + let api_options = ::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { let mut api_that_guard = None; @@ -1157,7 +1167,7 @@ fn wire__crate__api__js__JsContext_eval_file_with_options_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsContext::eval_file_with_options( + Result::<_, ()>::Ok(crate::api::runtime::JsContext::eval_file_with_options( &*api_that_guard, api_path, api_options, @@ -1167,7 +1177,7 @@ fn wire__crate__api__js__JsContext_eval_file_with_options_impl( }, ) } -fn wire__crate__api__js__JsContext_eval_with_options_impl( +fn wire__crate__api__runtime__JsContext_eval_with_options_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1192,7 +1202,7 @@ fn wire__crate__api__js__JsContext_eval_with_options_impl( flutter_rust_bridge::for_generated::RustAutoOpaqueInner, >>::sse_decode(&mut deserializer); let api_code = ::sse_decode(&mut deserializer); - let api_options = ::sse_decode(&mut deserializer); + let api_options = ::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { let mut api_that_guard = None; @@ -1209,17 +1219,18 @@ fn wire__crate__api__js__JsContext_eval_with_options_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsContext::eval_with_options( - &*api_that_guard, - api_code, - api_options, - ))?; + let output_ok = + Result::<_, ()>::Ok(crate::api::runtime::JsContext::eval_with_options( + &*api_that_guard, + api_code, + api_options, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsContext_new_impl( +fn wire__crate__api__runtime__JsContext_new_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1260,14 +1271,14 @@ fn wire__crate__api__js__JsContext_new_impl( } } let api_rt_guard = api_rt_guard.unwrap(); - let output_ok = crate::api::js::JsContext::new(&*api_rt_guard)?; + let output_ok = crate::api::runtime::JsContext::new(&*api_rt_guard)?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsEngineCore_context_impl( +fn wire__crate__api__engine__JsEngineCore_context_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1307,14 +1318,15 @@ fn wire__crate__api__js__JsEngineCore_context_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsEngineCore::context(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::engine::JsEngineCore::context( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsEngineCore_dispose_impl( +fn wire__crate__api__engine__JsEngineCore_dispose_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1361,7 +1373,7 @@ fn wire__crate__api__js__JsEngineCore_dispose_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::js::JsEngineCore::dispose(&*api_that_guard).await?; + crate::api::engine::JsEngineCore::dispose(&*api_that_guard).await?; Ok(output_ok) })() .await, @@ -1370,7 +1382,7 @@ fn wire__crate__api__js__JsEngineCore_dispose_impl( }, ) } -fn wire__crate__api__js__JsEngineCore_disposed_impl( +fn wire__crate__api__engine__JsEngineCore_disposed_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1410,14 +1422,15 @@ fn wire__crate__api__js__JsEngineCore_disposed_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsEngineCore::disposed(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::engine::JsEngineCore::disposed( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsEngineCore_exec_impl( +fn wire__crate__api__engine__JsEngineCore_exec_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1442,7 +1455,7 @@ fn wire__crate__api__js__JsEngineCore_exec_impl( let api_that = , >>::sse_decode(&mut deserializer); - let api_action = ::sse_decode(&mut deserializer); + let api_action = ::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( @@ -1465,7 +1478,7 @@ fn wire__crate__api__js__JsEngineCore_exec_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::js::JsEngineCore::exec(&*api_that_guard, api_action) + crate::api::engine::JsEngineCore::exec(&*api_that_guard, api_action) .await?; Ok(output_ok) })() @@ -1475,7 +1488,7 @@ fn wire__crate__api__js__JsEngineCore_exec_impl( }, ) } -fn wire__crate__api__js__JsEngineCore_new_impl( +fn wire__crate__api__engine__JsEngineCore_new_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1518,14 +1531,14 @@ fn wire__crate__api__js__JsEngineCore_new_impl( } } let api_context_guard = api_context_guard.unwrap(); - let output_ok = crate::api::js::JsEngineCore::new(&*api_context_guard)?; + let output_ok = crate::api::engine::JsEngineCore::new(&*api_context_guard)?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsEngineCore_running_impl( +fn wire__crate__api__engine__JsEngineCore_running_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1565,14 +1578,15 @@ fn wire__crate__api__js__JsEngineCore_running_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsEngineCore::running(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::engine::JsEngineCore::running( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsEngineCore_start_impl( +fn wire__crate__api__engine__JsEngineCore_start_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -1623,7 +1637,7 @@ fn wire__crate__api__js__JsEngineCore_start_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::js::JsEngineCore::start(&*api_that_guard, api_bridge) + crate::api::engine::JsEngineCore::start(&*api_that_guard, api_bridge) .await?; Ok(output_ok) })() @@ -1633,7 +1647,7 @@ fn wire__crate__api__js__JsEngineCore_start_impl( }, ) } -fn wire__crate__api__js__JsRuntime_execute_pending_job_impl( +fn wire__crate__api__runtime__JsRuntime_execute_pending_job_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1675,14 +1689,14 @@ fn wire__crate__api__js__JsRuntime_execute_pending_job_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::js::JsRuntime::execute_pending_job(&*api_that_guard)?; + crate::api::runtime::JsRuntime::execute_pending_job(&*api_that_guard)?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsRuntime_is_job_pending_impl( +fn wire__crate__api__runtime__JsRuntime_is_job_pending_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1722,15 +1736,15 @@ fn wire__crate__api__js__JsRuntime_is_job_pending_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsRuntime::is_job_pending( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::JsRuntime::is_job_pending(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_memory_usage_impl( +fn wire__crate__api__runtime__JsRuntime_memory_usage_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1770,14 +1784,15 @@ fn wire__crate__api__js__JsRuntime_memory_usage_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsRuntime::memory_usage(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::JsRuntime::memory_usage( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_new_impl( +fn wire__crate__api__runtime__JsRuntime_new_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1801,14 +1816,14 @@ fn wire__crate__api__js__JsRuntime_new_impl( deserializer.end(); transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || { - let output_ok = crate::api::js::JsRuntime::new()?; + let output_ok = crate::api::runtime::JsRuntime::new()?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsRuntime_run_gc_impl( +fn wire__crate__api__runtime__JsRuntime_run_gc_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1849,14 +1864,14 @@ fn wire__crate__api__js__JsRuntime_run_gc_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsRuntime::run_gc(&*api_that_guard); + crate::api::runtime::JsRuntime::run_gc(&*api_that_guard); })?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_set_dump_flags_impl( +fn wire__crate__api__runtime__JsRuntime_set_dump_flags_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1898,14 +1913,14 @@ fn wire__crate__api__js__JsRuntime_set_dump_flags_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsRuntime::set_dump_flags(&*api_that_guard, api_flags); + crate::api::runtime::JsRuntime::set_dump_flags(&*api_that_guard, api_flags); })?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_set_gc_threshold_impl( +fn wire__crate__api__runtime__JsRuntime_set_gc_threshold_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1947,14 +1962,17 @@ fn wire__crate__api__js__JsRuntime_set_gc_threshold_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsRuntime::set_gc_threshold(&*api_that_guard, api_threshold); + crate::api::runtime::JsRuntime::set_gc_threshold( + &*api_that_guard, + api_threshold, + ); })?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_set_info_impl( +fn wire__crate__api__runtime__JsRuntime_set_info_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -1997,14 +2015,14 @@ fn wire__crate__api__js__JsRuntime_set_info_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = - crate::api::js::JsRuntime::set_info(&*api_that_guard, api_info)?; + crate::api::runtime::JsRuntime::set_info(&*api_that_guard, api_info)?; Ok(output_ok) })(), ) }, ) } -fn wire__crate__api__js__JsRuntime_set_max_stack_size_impl( +fn wire__crate__api__runtime__JsRuntime_set_max_stack_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2046,14 +2064,14 @@ fn wire__crate__api__js__JsRuntime_set_max_stack_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsRuntime::set_max_stack_size(&*api_that_guard, api_limit); + crate::api::runtime::JsRuntime::set_max_stack_size(&*api_that_guard, api_limit); })?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_set_memory_limit_impl( +fn wire__crate__api__runtime__JsRuntime_set_memory_limit_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2095,14 +2113,14 @@ fn wire__crate__api__js__JsRuntime_set_memory_limit_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok({ - crate::api::js::JsRuntime::set_memory_limit(&*api_that_guard, api_limit); + crate::api::runtime::JsRuntime::set_memory_limit(&*api_that_guard, api_limit); })?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__JsRuntime_with_options_impl( +fn wire__crate__api__runtime__JsRuntime_with_options_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, @@ -2125,16 +2143,18 @@ fn wire__crate__api__js__JsRuntime_with_options_impl( let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let api_builtin = - >::sse_decode(&mut deserializer); + >::sse_decode(&mut deserializer); let api_additional = - >>::sse_decode(&mut deserializer); + >>::sse_decode(&mut deserializer); deserializer.end(); move |context| async move { transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( (move || async move { - let output_ok = - crate::api::js::JsRuntime::with_options(api_builtin, api_additional) - .await?; + let output_ok = crate::api::runtime::JsRuntime::with_options( + api_builtin, + api_additional, + ) + .await?; Ok(output_ok) })() .await, @@ -2143,7 +2163,7 @@ fn wire__crate__api__js__JsRuntime_with_options_impl( }, ) } -fn wire__crate__api__js__MemoryUsage_array_count_impl( +fn wire__crate__api__runtime__MemoryUsage_array_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2183,15 +2203,15 @@ fn wire__crate__api__js__MemoryUsage_array_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::array_count( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::array_count(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_atom_count_impl( +fn wire__crate__api__runtime__MemoryUsage_atom_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2231,14 +2251,15 @@ fn wire__crate__api__js__MemoryUsage_atom_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::atom_count(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::atom_count( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_atom_size_impl( +fn wire__crate__api__runtime__MemoryUsage_atom_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2278,14 +2299,15 @@ fn wire__crate__api__js__MemoryUsage_atom_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::atom_size(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::atom_size( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_binary_object_count_impl( +fn wire__crate__api__runtime__MemoryUsage_binary_object_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2326,14 +2348,14 @@ fn wire__crate__api__js__MemoryUsage_binary_object_count_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::binary_object_count(&*api_that_guard), + crate::api::runtime::MemoryUsage::binary_object_count(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_binary_object_size_impl( +fn wire__crate__api__runtime__MemoryUsage_binary_object_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2374,14 +2396,14 @@ fn wire__crate__api__js__MemoryUsage_binary_object_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::binary_object_size(&*api_that_guard), + crate::api::runtime::MemoryUsage::binary_object_size(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_c_func_count_impl( +fn wire__crate__api__runtime__MemoryUsage_c_func_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2421,15 +2443,15 @@ fn wire__crate__api__js__MemoryUsage_c_func_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::c_func_count( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::c_func_count(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_fast_array_count_impl( +fn wire__crate__api__runtime__MemoryUsage_fast_array_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2470,14 +2492,14 @@ fn wire__crate__api__js__MemoryUsage_fast_array_count_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::fast_array_count(&*api_that_guard), + crate::api::runtime::MemoryUsage::fast_array_count(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_fast_array_elements_impl( +fn wire__crate__api__runtime__MemoryUsage_fast_array_elements_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2518,14 +2540,14 @@ fn wire__crate__api__js__MemoryUsage_fast_array_elements_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::fast_array_elements(&*api_that_guard), + crate::api::runtime::MemoryUsage::fast_array_elements(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_js_func_code_size_impl( +fn wire__crate__api__runtime__MemoryUsage_js_func_code_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2566,14 +2588,14 @@ fn wire__crate__api__js__MemoryUsage_js_func_code_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::js_func_code_size(&*api_that_guard), + crate::api::runtime::MemoryUsage::js_func_code_size(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_js_func_count_impl( +fn wire__crate__api__runtime__MemoryUsage_js_func_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2613,15 +2635,15 @@ fn wire__crate__api__js__MemoryUsage_js_func_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::js_func_count( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::js_func_count(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_js_func_pc2line_count_impl( +fn wire__crate__api__runtime__MemoryUsage_js_func_pc2line_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2662,14 +2684,14 @@ fn wire__crate__api__js__MemoryUsage_js_func_pc2line_count_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::js_func_pc2line_count(&*api_that_guard), + crate::api::runtime::MemoryUsage::js_func_pc2line_count(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_js_func_pc2line_size_impl( +fn wire__crate__api__runtime__MemoryUsage_js_func_pc2line_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2710,14 +2732,14 @@ fn wire__crate__api__js__MemoryUsage_js_func_pc2line_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::js_func_pc2line_size(&*api_that_guard), + crate::api::runtime::MemoryUsage::js_func_pc2line_size(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_js_func_size_impl( +fn wire__crate__api__runtime__MemoryUsage_js_func_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2757,15 +2779,15 @@ fn wire__crate__api__js__MemoryUsage_js_func_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::js_func_size( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::js_func_size(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_malloc_count_impl( +fn wire__crate__api__runtime__MemoryUsage_malloc_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2805,15 +2827,15 @@ fn wire__crate__api__js__MemoryUsage_malloc_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::malloc_count( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::malloc_count(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_malloc_limit_impl( +fn wire__crate__api__runtime__MemoryUsage_malloc_limit_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2853,15 +2875,15 @@ fn wire__crate__api__js__MemoryUsage_malloc_limit_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::malloc_limit( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::malloc_limit(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_malloc_size_impl( +fn wire__crate__api__runtime__MemoryUsage_malloc_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2901,15 +2923,15 @@ fn wire__crate__api__js__MemoryUsage_malloc_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::malloc_size( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::malloc_size(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_memory_used_count_impl( +fn wire__crate__api__runtime__MemoryUsage_memory_used_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2950,14 +2972,14 @@ fn wire__crate__api__js__MemoryUsage_memory_used_count_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::memory_used_count(&*api_that_guard), + crate::api::runtime::MemoryUsage::memory_used_count(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_memory_used_size_impl( +fn wire__crate__api__runtime__MemoryUsage_memory_used_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -2998,14 +3020,14 @@ fn wire__crate__api__js__MemoryUsage_memory_used_size_impl( } let api_that_guard = api_that_guard.unwrap(); let output_ok = Result::<_, ()>::Ok( - crate::api::js::MemoryUsage::memory_used_size(&*api_that_guard), + crate::api::runtime::MemoryUsage::memory_used_size(&*api_that_guard), )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_obj_count_impl( +fn wire__crate__api__runtime__MemoryUsage_obj_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3045,14 +3067,15 @@ fn wire__crate__api__js__MemoryUsage_obj_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::obj_count(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::obj_count( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_obj_size_impl( +fn wire__crate__api__runtime__MemoryUsage_obj_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3092,14 +3115,15 @@ fn wire__crate__api__js__MemoryUsage_obj_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::obj_size(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::obj_size( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_prop_count_impl( +fn wire__crate__api__runtime__MemoryUsage_prop_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3139,14 +3163,15 @@ fn wire__crate__api__js__MemoryUsage_prop_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::prop_count(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::prop_count( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_prop_size_impl( +fn wire__crate__api__runtime__MemoryUsage_prop_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3186,14 +3211,15 @@ fn wire__crate__api__js__MemoryUsage_prop_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::prop_size(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::prop_size( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_shape_count_impl( +fn wire__crate__api__runtime__MemoryUsage_shape_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3233,15 +3259,15 @@ fn wire__crate__api__js__MemoryUsage_shape_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = Result::<_, ()>::Ok(crate::api::js::MemoryUsage::shape_count( - &*api_that_guard, - ))?; + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::shape_count(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_shape_size_impl( +fn wire__crate__api__runtime__MemoryUsage_shape_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3281,14 +3307,15 @@ fn wire__crate__api__js__MemoryUsage_shape_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::shape_size(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::shape_size( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_str_count_impl( +fn wire__crate__api__runtime__MemoryUsage_str_count_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3328,14 +3355,15 @@ fn wire__crate__api__js__MemoryUsage_str_count_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::str_count(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::str_count( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__MemoryUsage_str_size_impl( +fn wire__crate__api__runtime__MemoryUsage_str_size_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, @@ -3375,24 +3403,24 @@ fn wire__crate__api__js__MemoryUsage_str_size_impl( } } let api_that_guard = api_that_guard.unwrap(); - let output_ok = - Result::<_, ()>::Ok(crate::api::js::MemoryUsage::str_size(&*api_that_guard))?; + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::str_size( + &*api_that_guard, + ))?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__init_app_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, +fn wire__crate__api__runtime__MemoryUsage_summary_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "init_app", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + debug_name: "MemoryUsage_summary", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, move || { let message = unsafe { @@ -3404,26 +3432,41 @@ fn wire__crate__api__init_app_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); deserializer.end(); - move |context| { - transform_result_sse::<_, ()>((move || { - let output_ok = Result::<_, ()>::Ok({ - crate::api::init_app(); - })?; - Ok(output_ok) - })()) - } + transform_result_sse::<_, ()>((move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok(crate::api::runtime::MemoryUsage::summary( + &*api_that_guard, + ))?; + Ok(output_ok) + })()) }, ) } -fn wire__crate__api__js__js_builtin_options_all_impl( +fn wire__crate__api__runtime__MemoryUsage_total_allocations_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_builtin_options_all", + debug_name: "MemoryUsage_total_allocations", port: None, mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, @@ -3437,22 +3480,41 @@ fn wire__crate__api__js__js_builtin_options_all_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsBuiltinOptions::all())?; + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::total_allocations(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__js_error_to_string_impl( +fn wire__crate__api__runtime__MemoryUsage_total_memory_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_error_to_string", + debug_name: "MemoryUsage_total_memory", port: None, mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, @@ -3466,25 +3528,44 @@ fn wire__crate__api__js__js_error_to_string_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_that = ::sse_decode(&mut deserializer); + let api_that = , + >>::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsError::to_string(&api_that))?; + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![ + flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + ), + ]); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = Result::<_, ()>::Ok( + crate::api::runtime::MemoryUsage::total_memory(&*api_that_guard), + )?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__js_eval_options_new_impl( +fn wire__crate__api__init_app_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_eval_options_new", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + debug_name: "init_app", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { @@ -3496,31 +3577,26 @@ fn wire__crate__api__js__js_eval_options_new_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_global = >::sse_decode(&mut deserializer); - let api_strict = >::sse_decode(&mut deserializer); - let api_backtrace_barrier = >::sse_decode(&mut deserializer); - let api_promise = >::sse_decode(&mut deserializer); deserializer.end(); - transform_result_sse::<_, ()>((move || { - let output_ok = Result::<_, ()>::Ok(crate::api::js::JsEvalOptions::new( - api_global, - api_strict, - api_backtrace_barrier, - api_promise, - ))?; - Ok(output_ok) - })()) + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok({ + crate::api::init_app(); + })?; + Ok(output_ok) + })()) + } }, ) } -fn wire__crate__api__js__js_module_bytes_impl( +fn wire__crate__api__source__js_builtin_options_all_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_module_bytes", + debug_name: "js_builtin_options_all", port: None, mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, @@ -3534,27 +3610,25 @@ fn wire__crate__api__js__js_module_bytes_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_module = ::sse_decode(&mut deserializer); - let api_bytes = >::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsModule::bytes(api_module, api_bytes))?; + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::all())?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__js_module_code_impl( +fn wire__crate__api__source__js_builtin_options_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, -) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_module_code", - port: None, - mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + debug_name: "js_builtin_options_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, }, move || { let message = unsafe { @@ -3566,25 +3640,25 @@ fn wire__crate__api__js__js_module_code_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_module = ::sse_decode(&mut deserializer); - let api_code = ::sse_decode(&mut deserializer); deserializer.end(); - transform_result_sse::<_, ()>((move || { - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsModule::code(api_module, api_code))?; - Ok(output_ok) - })()) + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::default())?; + Ok(output_ok) + })()) + } }, ) } -fn wire__crate__api__js__js_module_new_impl( +fn wire__crate__api__source__js_builtin_options_essential_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_module_new", + debug_name: "js_builtin_options_essential", port: None, mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, @@ -3598,25 +3672,23 @@ fn wire__crate__api__js__js_module_new_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_name = ::sse_decode(&mut deserializer); - let api_source = ::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsModule::new(api_name, api_source))?; + Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::essential())?; Ok(output_ok) })()) }, ) } -fn wire__crate__api__js__js_module_path_impl( +fn wire__crate__api__source__js_builtin_options_node_impl( ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, rust_vec_len_: i32, data_len_: i32, ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "js_module_path", + debug_name: "js_builtin_options_node", port: None, mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, }, @@ -3630,31 +3702,903 @@ fn wire__crate__api__js__js_module_path_impl( }; let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); - let api_module = ::sse_decode(&mut deserializer); - let api_path = ::sse_decode(&mut deserializer); deserializer.end(); transform_result_sse::<_, ()>((move || { - let output_ok = - Result::<_, ()>::Ok(crate::api::js::JsModule::path(api_module, api_path))?; + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::node())?; Ok(output_ok) })()) }, ) } +fn wire__crate__api__source__js_builtin_options_none_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_builtin_options_none", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::none())?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_builtin_options_web_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_builtin_options_web", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsBuiltinOptions::web())?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_code_is_bytes_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_code_is_bytes", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsCode::is_bytes(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_code_is_code_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_code_is_code", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsCode::is_code(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_code_is_path_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_code_is_path", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsCode::is_path(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__error__js_error_code_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_error_code", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::error::JsError::code(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__error__js_error_is_recoverable_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_error_is_recoverable", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::error::JsError::is_recoverable(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__error__js_error_to_string_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_error_to_string", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::error::JsError::to_string(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_eval_options_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_eval_options_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsEvalOptions::default())?; + Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__source__js_eval_options_defaults_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_eval_options_defaults", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsEvalOptions::defaults())?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_eval_options_module_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_eval_options_module", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsEvalOptions::module())?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_eval_options_new_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_eval_options_new", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_global = >::sse_decode(&mut deserializer); + let api_strict = >::sse_decode(&mut deserializer); + let api_backtrace_barrier = >::sse_decode(&mut deserializer); + let api_promise = >::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsEvalOptions::new( + api_global, + api_strict, + api_backtrace_barrier, + api_promise, + ))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_eval_options_with_promise_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_eval_options_with_promise", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsEvalOptions::with_promise())?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_module_from_bytes_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_module_from_bytes(dart_style=fromBytes)", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_module = ::sse_decode(&mut deserializer); + let api_bytes = >::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsModule::from_bytes( + api_module, api_bytes, + ))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_module_from_code_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_module_from_code(dart_style=fromCode)", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_module = ::sse_decode(&mut deserializer); + let api_code = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsModule::from_code( + api_module, api_code, + ))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_module_from_path_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_module_from_path(dart_style=fromPath)", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_module = ::sse_decode(&mut deserializer); + let api_path = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::source::JsModule::from_path( + api_module, api_path, + ))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__source__js_module_new_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_module_new", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_name = ::sse_decode(&mut deserializer); + let api_source = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::source::JsModule::new(api_name, api_source))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_default_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_default", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + deserializer.end(); + move |context| { + transform_result_sse::<_, ()>((move || { + let output_ok = Result::<_, ()>::Ok(crate::api::value::JsValue::default())?; + Ok(output_ok) + })()) + } + }, + ) +} +fn wire__crate__api__value__js_value_is_array_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_array", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_array(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_boolean_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_boolean", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_boolean(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_bytes_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_bytes", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_bytes(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_date_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_date", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_date(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_none_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_none", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_none(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_number_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_number", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_number(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_object_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_object", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_object(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_primitive_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_primitive", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_primitive(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_is_string_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_is_string", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::is_string(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} +fn wire__crate__api__value__js_value_type_name_impl( + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "js_value_type_name", + port: None, + mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = ::sse_decode(&mut deserializer); + deserializer.end(); + transform_result_sse::<_, ()>((move || { + let output_ok = + Result::<_, ()>::Ok(crate::api::value::JsValue::type_name(&api_that))?; + Ok(output_ok) + })()) + }, + ) +} + +// Section: related_funcs + +fn decode_DartFn_Inputs_js_callback_Output_js_callback_result_AnyhowException( + dart_opaque: flutter_rust_bridge::DartOpaque, +) -> impl Fn( + crate::api::engine::JsCallback, +) -> flutter_rust_bridge::DartFnFuture { + use flutter_rust_bridge::IntoDart; -// Section: related_funcs - -fn decode_DartFn_Inputs_js_callback_Output_js_callback_result_AnyhowException( - dart_opaque: flutter_rust_bridge::DartOpaque, -) -> impl Fn( - crate::api::js::JsCallback, -) -> flutter_rust_bridge::DartFnFuture { - use flutter_rust_bridge::IntoDart; - async fn body( dart_opaque: flutter_rust_bridge::DartOpaque, - arg0: crate::api::js::JsCallback, - ) -> crate::api::js::JsCallbackResult { + arg0: crate::api::engine::JsCallback, + ) -> crate::api::engine::JsCallbackResult { let args = vec![arg0.into_into_dart().into_dart()]; let message = FLUTTER_RUST_BRIDGE_HANDLER .dart_fn_invoke(dart_opaque, args) @@ -3663,7 +4607,7 @@ fn decode_DartFn_Inputs_js_callback_Output_js_callback_result_AnyhowException( let mut deserializer = flutter_rust_bridge::for_generated::SseDeserializer::new(message); let action = deserializer.cursor.read_u8().unwrap(); let ans = match action { - 0 => std::result::Result::Ok(::sse_decode( + 0 => std::result::Result::Ok(::sse_decode( &mut deserializer, )), 1 => std::result::Result::Err( @@ -3676,7 +4620,7 @@ fn decode_DartFn_Inputs_js_callback_Output_js_callback_result_AnyhowException( ans } - move |arg0: crate::api::js::JsCallback| { + move |arg0: crate::api::engine::JsCallback| { flutter_rust_bridge::for_generated::convert_into_dart_fn_future(body( dart_opaque.clone(), arg0, @@ -3884,17 +4828,17 @@ impl SseDecode for isize { } } -impl SseDecode for crate::api::js::JsAction { +impl SseDecode for crate::api::engine::JsAction { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { let mut var_id = ::sse_decode(deserializer); - let mut var_source = ::sse_decode(deserializer); + let mut var_source = ::sse_decode(deserializer); let mut var_options = - >::sse_decode(deserializer); - return crate::api::js::JsAction::Eval { + >::sse_decode(deserializer); + return crate::api::engine::JsAction::Eval { id: var_id, source: var_source, options: var_options, @@ -3902,44 +4846,57 @@ impl SseDecode for crate::api::js::JsAction { } 1 => { let mut var_id = ::sse_decode(deserializer); - let mut var_module = ::sse_decode(deserializer); - return crate::api::js::JsAction::DeclareNewModule { + let mut var_module = ::sse_decode(deserializer); + return crate::api::engine::JsAction::DeclareNewModule { id: var_id, module: var_module, }; } 2 => { let mut var_id = ::sse_decode(deserializer); - let mut var_modules = >::sse_decode(deserializer); - return crate::api::js::JsAction::DeclareNewModules { + let mut var_modules = >::sse_decode(deserializer); + return crate::api::engine::JsAction::DeclareNewModules { id: var_id, modules: var_modules, }; } 3 => { let mut var_id = ::sse_decode(deserializer); - return crate::api::js::JsAction::ClearNewModules { id: var_id }; + return crate::api::engine::JsAction::ClearNewModules { id: var_id }; } 4 => { let mut var_id = ::sse_decode(deserializer); - let mut var_module = ::sse_decode(deserializer); - return crate::api::js::JsAction::EvaluateModule { + let mut var_module = ::sse_decode(deserializer); + return crate::api::engine::JsAction::EvaluateModule { id: var_id, module: var_module, }; } 5 => { let mut var_id = ::sse_decode(deserializer); - return crate::api::js::JsAction::GetDeclaredModules { id: var_id }; + return crate::api::engine::JsAction::GetDeclaredModules { id: var_id }; } 6 => { let mut var_id = ::sse_decode(deserializer); let mut var_moduleName = ::sse_decode(deserializer); - return crate::api::js::JsAction::IsModuleDeclared { + return crate::api::engine::JsAction::IsModuleDeclared { id: var_id, module_name: var_moduleName, }; } + 7 => { + let mut var_id = ::sse_decode(deserializer); + let mut var_module = ::sse_decode(deserializer); + let mut var_method = ::sse_decode(deserializer); + let mut var_params = + >>::sse_decode(deserializer); + return crate::api::engine::JsAction::CallFunction { + id: var_id, + module: var_module, + method: var_method, + params: var_params, + }; + } _ => { unimplemented!(""); } @@ -3947,19 +4904,19 @@ impl SseDecode for crate::api::js::JsAction { } } -impl SseDecode for crate::api::js::JsActionResult { +impl SseDecode for crate::api::engine::JsActionResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_id = ::sse_decode(deserializer); - let mut var_result = ::sse_decode(deserializer); - return crate::api::js::JsActionResult { + let mut var_result = ::sse_decode(deserializer); + return crate::api::engine::JsActionResult { id: var_id, result: var_result, }; } } -impl SseDecode for crate::api::js::JsBuiltinOptions { +impl SseDecode for crate::api::source::JsBuiltinOptions { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_abort = >::sse_decode(deserializer); @@ -3988,7 +4945,7 @@ impl SseDecode for crate::api::js::JsBuiltinOptions { let mut var_util = >::sse_decode(deserializer); let mut var_zlib = >::sse_decode(deserializer); let mut var_json = >::sse_decode(deserializer); - return crate::api::js::JsBuiltinOptions { + return crate::api::source::JsBuiltinOptions { abort: var_abort, assert: var_assert_, async_hooks: var_asyncHooks, @@ -4019,21 +4976,21 @@ impl SseDecode for crate::api::js::JsBuiltinOptions { } } -impl SseDecode for crate::api::js::JsCallback { +impl SseDecode for crate::api::engine::JsCallback { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { - return crate::api::js::JsCallback::Initialized; + return crate::api::engine::JsCallback::Initialized; } 1 => { - let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsCallback::Handler(var_field0); + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::engine::JsCallback::Handler(var_field0); } 2 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsCallback::Bridge(var_field0); + return crate::api::engine::JsCallback::Bridge(var_field0); } _ => { unimplemented!(""); @@ -4042,20 +4999,20 @@ impl SseDecode for crate::api::js::JsCallback { } } -impl SseDecode for crate::api::js::JsCallbackResult { +impl SseDecode for crate::api::engine::JsCallbackResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { - return crate::api::js::JsCallbackResult::Initialized; + return crate::api::engine::JsCallbackResult::Initialized; } 1 => { - return crate::api::js::JsCallbackResult::Handler; + return crate::api::engine::JsCallbackResult::Handler; } 2 => { - let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsCallbackResult::Bridge(var_field0); + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::engine::JsCallbackResult::Bridge(var_field0); } _ => { unimplemented!(""); @@ -4064,22 +5021,22 @@ impl SseDecode for crate::api::js::JsCallbackResult { } } -impl SseDecode for crate::api::js::JsCode { +impl SseDecode for crate::api::source::JsCode { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsCode::Code(var_field0); + return crate::api::source::JsCode::Code(var_field0); } 1 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsCode::Path(var_field0); + return crate::api::source::JsCode::Path(var_field0); } 2 => { let mut var_field0 = >::sse_decode(deserializer); - return crate::api::js::JsCode::Bytes(var_field0); + return crate::api::source::JsCode::Bytes(var_field0); } _ => { unimplemented!(""); @@ -4088,20 +5045,20 @@ impl SseDecode for crate::api::js::JsCode { } } -impl SseDecode for crate::api::js::JsError { +impl SseDecode for crate::api::error::JsError { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Promise(var_field0); + return crate::api::error::JsError::Promise(var_field0); } 1 => { let mut var_module = >::sse_decode(deserializer); let mut var_method = >::sse_decode(deserializer); let mut var_message = ::sse_decode(deserializer); - return crate::api::js::JsError::Module { + return crate::api::error::JsError::Module { module: var_module, method: var_method, message: var_message, @@ -4109,35 +5066,87 @@ impl SseDecode for crate::api::js::JsError { } 2 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Context(var_field0); + return crate::api::error::JsError::Context(var_field0); } 3 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Storage(var_field0); + return crate::api::error::JsError::Storage(var_field0); } 4 => { let mut var_path = >::sse_decode(deserializer); let mut var_message = ::sse_decode(deserializer); - return crate::api::js::JsError::Io { + return crate::api::error::JsError::Io { path: var_path, message: var_message, }; } 5 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Runtime(var_field0); + return crate::api::error::JsError::Runtime(var_field0); } 6 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Generic(var_field0); + return crate::api::error::JsError::Generic(var_field0); } 7 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Engine(var_field0); + return crate::api::error::JsError::Engine(var_field0); } 8 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsError::Bridge(var_field0); + return crate::api::error::JsError::Bridge(var_field0); + } + 9 => { + let mut var_from = ::sse_decode(deserializer); + let mut var_to = ::sse_decode(deserializer); + let mut var_message = ::sse_decode(deserializer); + return crate::api::error::JsError::Conversion { + from: var_from, + to: var_to, + message: var_message, + }; + } + 10 => { + let mut var_operation = ::sse_decode(deserializer); + let mut var_timeoutMs = ::sse_decode(deserializer); + return crate::api::error::JsError::Timeout { + operation: var_operation, + timeout_ms: var_timeoutMs, + }; + } + 11 => { + let mut var_current = ::sse_decode(deserializer); + let mut var_limit = ::sse_decode(deserializer); + return crate::api::error::JsError::MemoryLimit { + current: var_current, + limit: var_limit, + }; + } + 12 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::error::JsError::StackOverflow(var_field0); + } + 13 => { + let mut var_line = >::sse_decode(deserializer); + let mut var_column = >::sse_decode(deserializer); + let mut var_message = ::sse_decode(deserializer); + return crate::api::error::JsError::Syntax { + line: var_line, + column: var_column, + message: var_message, + }; + } + 14 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::error::JsError::Reference(var_field0); + } + 15 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::error::JsError::Type(var_field0); + } + 16 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::error::JsError::Cancelled(var_field0); } _ => { unimplemented!(""); @@ -4146,14 +5155,14 @@ impl SseDecode for crate::api::js::JsError { } } -impl SseDecode for crate::api::js::JsEvalOptions { +impl SseDecode for crate::api::source::JsEvalOptions { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_global = >::sse_decode(deserializer); let mut var_strict = >::sse_decode(deserializer); let mut var_backtraceBarrier = >::sse_decode(deserializer); let mut var_promise = >::sse_decode(deserializer); - return crate::api::js::JsEvalOptions { + return crate::api::source::JsEvalOptions { global: var_global, strict: var_strict, backtrace_barrier: var_backtraceBarrier, @@ -4162,30 +5171,30 @@ impl SseDecode for crate::api::js::JsEvalOptions { } } -impl SseDecode for crate::api::js::JsModule { +impl SseDecode for crate::api::source::JsModule { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_name = ::sse_decode(deserializer); - let mut var_source = ::sse_decode(deserializer); - return crate::api::js::JsModule { + let mut var_source = ::sse_decode(deserializer); + return crate::api::source::JsModule { name: var_name, source: var_source, }; } } -impl SseDecode for crate::api::js::JsResult { +impl SseDecode for crate::api::error::JsResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut tag_ = ::sse_decode(deserializer); match tag_ { 0 => { let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsResult::Ok(var_field0); + return crate::api::error::JsResult::Ok(var_field0); } 1 => { - let mut var_field0 = ::sse_decode(deserializer); - return crate::api::js::JsResult::Err(var_field0); + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::error::JsResult::Err(var_field0); } _ => { unimplemented!(""); @@ -4223,16 +5232,32 @@ impl SseDecode for crate::api::value::JsValue { return crate::api::value::JsValue::String(var_field0); } 6 => { + let mut var_field0 = >::sse_decode(deserializer); + return crate::api::value::JsValue::Bytes(var_field0); + } + 7 => { let mut var_field0 = >::sse_decode(deserializer); return crate::api::value::JsValue::Array(var_field0); } - 7 => { + 8 => { let mut var_field0 = >::sse_decode( deserializer, ); return crate::api::value::JsValue::Object(var_field0); } + 9 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::value::JsValue::Date(var_field0); + } + 10 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::value::JsValue::Symbol(var_field0); + } + 11 => { + let mut var_field0 = ::sse_decode(deserializer); + return crate::api::value::JsValue::Function(var_field0); + } _ => { unimplemented!(""); } @@ -4240,13 +5265,13 @@ impl SseDecode for crate::api::value::JsValue { } } -impl SseDecode for Vec { +impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut len_ = ::sse_decode(deserializer); let mut ans_ = vec![]; for idx_ in 0..len_ { - ans_.push(::sse_decode(deserializer)); + ans_.push(::sse_decode(deserializer)); } return ans_; } @@ -4312,33 +5337,50 @@ impl SseDecode for Option { } } -impl SseDecode for Option { +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode( + deserializer, + )); + } else { + return None; + } + } +} + +impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); + return Some(::sse_decode( + deserializer, + )); } else { return None; } } } -impl SseDecode for Option { +impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { if (::sse_decode(deserializer)) { - return Some(::sse_decode(deserializer)); + return Some(::sse_decode(deserializer)); } else { return None; } } } -impl SseDecode for Option> { +impl SseDecode for Option> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { if (::sse_decode(deserializer)) { - return Some(>::sse_decode(deserializer)); + return Some(>::sse_decode( + deserializer, + )); } else { return None; } @@ -4414,77 +5456,109 @@ fn pde_ffi_dispatcher_primary_impl( ) { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 1 => wire__crate__api__js__JsAsyncContext_eval_impl(port, ptr, rust_vec_len, data_len), - 2 => wire__crate__api__js__JsAsyncContext_eval_file_impl(port, ptr, rust_vec_len, data_len), - 3 => wire__crate__api__js__JsAsyncContext_eval_file_with_options_impl( + 1 => wire__crate__api__runtime__JsAsyncContext_eval_impl(port, ptr, rust_vec_len, data_len), + 2 => wire__crate__api__runtime__JsAsyncContext_eval_file_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 3 => wire__crate__api__runtime__JsAsyncContext_eval_file_with_options_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 4 => wire__crate__api__runtime__JsAsyncContext_eval_function_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 5 => wire__crate__api__runtime__JsAsyncContext_eval_with_options_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 6 => wire__crate__api__runtime__JsAsyncContext_from_impl(port, ptr, rust_vec_len, data_len), + 7 => wire__crate__api__runtime__JsAsyncRuntime_execute_pending_job_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 8 => wire__crate__api__runtime__JsAsyncRuntime_idle_impl(port, ptr, rust_vec_len, data_len), + 9 => wire__crate__api__runtime__JsAsyncRuntime_is_job_pending_impl( port, ptr, rust_vec_len, data_len, ), - 4 => wire__crate__api__js__JsAsyncContext_eval_function_impl( + 10 => wire__crate__api__runtime__JsAsyncRuntime_memory_usage_impl( port, ptr, rust_vec_len, data_len, ), - 5 => wire__crate__api__js__JsAsyncContext_eval_with_options_impl( + 12 => { + wire__crate__api__runtime__JsAsyncRuntime_run_gc_impl(port, ptr, rust_vec_len, data_len) + } + 13 => wire__crate__api__runtime__JsAsyncRuntime_set_gc_threshold_impl( port, ptr, rust_vec_len, data_len, ), - 6 => wire__crate__api__js__JsAsyncContext_from_impl(port, ptr, rust_vec_len, data_len), - 7 => wire__crate__api__js__JsAsyncRuntime_execute_pending_job_impl( + 14 => wire__crate__api__runtime__JsAsyncRuntime_set_info_impl( port, ptr, rust_vec_len, data_len, ), - 8 => wire__crate__api__js__JsAsyncRuntime_idle_impl(port, ptr, rust_vec_len, data_len), - 9 => wire__crate__api__js__JsAsyncRuntime_is_job_pending_impl( + 15 => wire__crate__api__runtime__JsAsyncRuntime_set_max_stack_size_impl( port, ptr, rust_vec_len, data_len, ), - 10 => wire__crate__api__js__JsAsyncRuntime_memory_usage_impl( + 16 => wire__crate__api__runtime__JsAsyncRuntime_set_memory_limit_impl( port, ptr, rust_vec_len, data_len, ), - 12 => wire__crate__api__js__JsAsyncRuntime_run_gc_impl(port, ptr, rust_vec_len, data_len), - 13 => wire__crate__api__js__JsAsyncRuntime_set_gc_threshold_impl( + 17 => wire__crate__api__runtime__JsAsyncRuntime_with_options_impl( port, ptr, rust_vec_len, data_len, ), - 14 => wire__crate__api__js__JsAsyncRuntime_set_info_impl(port, ptr, rust_vec_len, data_len), - 15 => wire__crate__api__js__JsAsyncRuntime_set_max_stack_size_impl( + 24 => { + wire__crate__api__engine__JsEngineCore_dispose_impl(port, ptr, rust_vec_len, data_len) + } + 26 => wire__crate__api__engine__JsEngineCore_exec_impl(port, ptr, rust_vec_len, data_len), + 29 => wire__crate__api__engine__JsEngineCore_start_impl(port, ptr, rust_vec_len, data_len), + 40 => wire__crate__api__runtime__JsRuntime_with_options_impl( port, ptr, rust_vec_len, data_len, ), - 16 => wire__crate__api__js__JsAsyncRuntime_set_memory_limit_impl( + 70 => wire__crate__api__init_app_impl(port, ptr, rust_vec_len, data_len), + 72 => wire__crate__api__source__js_builtin_options_default_impl( port, ptr, rust_vec_len, data_len, ), - 17 => wire__crate__api__js__JsAsyncRuntime_with_options_impl( + 83 => wire__crate__api__source__js_eval_options_default_impl( port, ptr, rust_vec_len, data_len, ), - 24 => wire__crate__api__js__JsEngineCore_dispose_impl(port, ptr, rust_vec_len, data_len), - 26 => wire__crate__api__js__JsEngineCore_exec_impl(port, ptr, rust_vec_len, data_len), - 29 => wire__crate__api__js__JsEngineCore_start_impl(port, ptr, rust_vec_len, data_len), - 40 => wire__crate__api__js__JsRuntime_with_options_impl(port, ptr, rust_vec_len, data_len), - 67 => wire__crate__api__init_app_impl(port, ptr, rust_vec_len, data_len), + 92 => wire__crate__api__value__js_value_default_impl(port, ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -4497,73 +5571,148 @@ fn pde_ffi_dispatcher_sync_impl( ) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse { // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { - 11 => wire__crate__api__js__JsAsyncRuntime_new_impl(ptr, rust_vec_len, data_len), - 18 => wire__crate__api__js__JsContext_eval_impl(ptr, rust_vec_len, data_len), - 19 => wire__crate__api__js__JsContext_eval_file_impl(ptr, rust_vec_len, data_len), - 20 => { - wire__crate__api__js__JsContext_eval_file_with_options_impl(ptr, rust_vec_len, data_len) + 11 => wire__crate__api__runtime__JsAsyncRuntime_new_impl(ptr, rust_vec_len, data_len), + 18 => wire__crate__api__runtime__JsContext_eval_impl(ptr, rust_vec_len, data_len), + 19 => wire__crate__api__runtime__JsContext_eval_file_impl(ptr, rust_vec_len, data_len), + 20 => wire__crate__api__runtime__JsContext_eval_file_with_options_impl( + ptr, + rust_vec_len, + data_len, + ), + 21 => { + wire__crate__api__runtime__JsContext_eval_with_options_impl(ptr, rust_vec_len, data_len) } - 21 => wire__crate__api__js__JsContext_eval_with_options_impl(ptr, rust_vec_len, data_len), - 22 => wire__crate__api__js__JsContext_new_impl(ptr, rust_vec_len, data_len), - 23 => wire__crate__api__js__JsEngineCore_context_impl(ptr, rust_vec_len, data_len), - 25 => wire__crate__api__js__JsEngineCore_disposed_impl(ptr, rust_vec_len, data_len), - 27 => wire__crate__api__js__JsEngineCore_new_impl(ptr, rust_vec_len, data_len), - 28 => wire__crate__api__js__JsEngineCore_running_impl(ptr, rust_vec_len, data_len), - 30 => wire__crate__api__js__JsRuntime_execute_pending_job_impl(ptr, rust_vec_len, data_len), - 31 => wire__crate__api__js__JsRuntime_is_job_pending_impl(ptr, rust_vec_len, data_len), - 32 => wire__crate__api__js__JsRuntime_memory_usage_impl(ptr, rust_vec_len, data_len), - 33 => wire__crate__api__js__JsRuntime_new_impl(ptr, rust_vec_len, data_len), - 34 => wire__crate__api__js__JsRuntime_run_gc_impl(ptr, rust_vec_len, data_len), - 35 => wire__crate__api__js__JsRuntime_set_dump_flags_impl(ptr, rust_vec_len, data_len), - 36 => wire__crate__api__js__JsRuntime_set_gc_threshold_impl(ptr, rust_vec_len, data_len), - 37 => wire__crate__api__js__JsRuntime_set_info_impl(ptr, rust_vec_len, data_len), - 38 => wire__crate__api__js__JsRuntime_set_max_stack_size_impl(ptr, rust_vec_len, data_len), - 39 => wire__crate__api__js__JsRuntime_set_memory_limit_impl(ptr, rust_vec_len, data_len), - 41 => wire__crate__api__js__MemoryUsage_array_count_impl(ptr, rust_vec_len, data_len), - 42 => wire__crate__api__js__MemoryUsage_atom_count_impl(ptr, rust_vec_len, data_len), - 43 => wire__crate__api__js__MemoryUsage_atom_size_impl(ptr, rust_vec_len, data_len), - 44 => { - wire__crate__api__js__MemoryUsage_binary_object_count_impl(ptr, rust_vec_len, data_len) + 22 => wire__crate__api__runtime__JsContext_new_impl(ptr, rust_vec_len, data_len), + 23 => wire__crate__api__engine__JsEngineCore_context_impl(ptr, rust_vec_len, data_len), + 25 => wire__crate__api__engine__JsEngineCore_disposed_impl(ptr, rust_vec_len, data_len), + 27 => wire__crate__api__engine__JsEngineCore_new_impl(ptr, rust_vec_len, data_len), + 28 => wire__crate__api__engine__JsEngineCore_running_impl(ptr, rust_vec_len, data_len), + 30 => wire__crate__api__runtime__JsRuntime_execute_pending_job_impl( + ptr, + rust_vec_len, + data_len, + ), + 31 => wire__crate__api__runtime__JsRuntime_is_job_pending_impl(ptr, rust_vec_len, data_len), + 32 => wire__crate__api__runtime__JsRuntime_memory_usage_impl(ptr, rust_vec_len, data_len), + 33 => wire__crate__api__runtime__JsRuntime_new_impl(ptr, rust_vec_len, data_len), + 34 => wire__crate__api__runtime__JsRuntime_run_gc_impl(ptr, rust_vec_len, data_len), + 35 => wire__crate__api__runtime__JsRuntime_set_dump_flags_impl(ptr, rust_vec_len, data_len), + 36 => { + wire__crate__api__runtime__JsRuntime_set_gc_threshold_impl(ptr, rust_vec_len, data_len) } - 45 => { - wire__crate__api__js__MemoryUsage_binary_object_size_impl(ptr, rust_vec_len, data_len) + 37 => wire__crate__api__runtime__JsRuntime_set_info_impl(ptr, rust_vec_len, data_len), + 38 => wire__crate__api__runtime__JsRuntime_set_max_stack_size_impl( + ptr, + rust_vec_len, + data_len, + ), + 39 => { + wire__crate__api__runtime__JsRuntime_set_memory_limit_impl(ptr, rust_vec_len, data_len) } - 46 => wire__crate__api__js__MemoryUsage_c_func_count_impl(ptr, rust_vec_len, data_len), - 47 => wire__crate__api__js__MemoryUsage_fast_array_count_impl(ptr, rust_vec_len, data_len), - 48 => { - wire__crate__api__js__MemoryUsage_fast_array_elements_impl(ptr, rust_vec_len, data_len) + 41 => wire__crate__api__runtime__MemoryUsage_array_count_impl(ptr, rust_vec_len, data_len), + 42 => wire__crate__api__runtime__MemoryUsage_atom_count_impl(ptr, rust_vec_len, data_len), + 43 => wire__crate__api__runtime__MemoryUsage_atom_size_impl(ptr, rust_vec_len, data_len), + 44 => wire__crate__api__runtime__MemoryUsage_binary_object_count_impl( + ptr, + rust_vec_len, + data_len, + ), + 45 => wire__crate__api__runtime__MemoryUsage_binary_object_size_impl( + ptr, + rust_vec_len, + data_len, + ), + 46 => wire__crate__api__runtime__MemoryUsage_c_func_count_impl(ptr, rust_vec_len, data_len), + 47 => wire__crate__api__runtime__MemoryUsage_fast_array_count_impl( + ptr, + rust_vec_len, + data_len, + ), + 48 => wire__crate__api__runtime__MemoryUsage_fast_array_elements_impl( + ptr, + rust_vec_len, + data_len, + ), + 49 => wire__crate__api__runtime__MemoryUsage_js_func_code_size_impl( + ptr, + rust_vec_len, + data_len, + ), + 50 => { + wire__crate__api__runtime__MemoryUsage_js_func_count_impl(ptr, rust_vec_len, data_len) } - 49 => wire__crate__api__js__MemoryUsage_js_func_code_size_impl(ptr, rust_vec_len, data_len), - 50 => wire__crate__api__js__MemoryUsage_js_func_count_impl(ptr, rust_vec_len, data_len), - 51 => wire__crate__api__js__MemoryUsage_js_func_pc2line_count_impl( + 51 => wire__crate__api__runtime__MemoryUsage_js_func_pc2line_count_impl( + ptr, + rust_vec_len, + data_len, + ), + 52 => wire__crate__api__runtime__MemoryUsage_js_func_pc2line_size_impl( + ptr, + rust_vec_len, + data_len, + ), + 53 => wire__crate__api__runtime__MemoryUsage_js_func_size_impl(ptr, rust_vec_len, data_len), + 54 => wire__crate__api__runtime__MemoryUsage_malloc_count_impl(ptr, rust_vec_len, data_len), + 55 => wire__crate__api__runtime__MemoryUsage_malloc_limit_impl(ptr, rust_vec_len, data_len), + 56 => wire__crate__api__runtime__MemoryUsage_malloc_size_impl(ptr, rust_vec_len, data_len), + 57 => wire__crate__api__runtime__MemoryUsage_memory_used_count_impl( + ptr, + rust_vec_len, + data_len, + ), + 58 => wire__crate__api__runtime__MemoryUsage_memory_used_size_impl( + ptr, + rust_vec_len, + data_len, + ), + 59 => wire__crate__api__runtime__MemoryUsage_obj_count_impl(ptr, rust_vec_len, data_len), + 60 => wire__crate__api__runtime__MemoryUsage_obj_size_impl(ptr, rust_vec_len, data_len), + 61 => wire__crate__api__runtime__MemoryUsage_prop_count_impl(ptr, rust_vec_len, data_len), + 62 => wire__crate__api__runtime__MemoryUsage_prop_size_impl(ptr, rust_vec_len, data_len), + 63 => wire__crate__api__runtime__MemoryUsage_shape_count_impl(ptr, rust_vec_len, data_len), + 64 => wire__crate__api__runtime__MemoryUsage_shape_size_impl(ptr, rust_vec_len, data_len), + 65 => wire__crate__api__runtime__MemoryUsage_str_count_impl(ptr, rust_vec_len, data_len), + 66 => wire__crate__api__runtime__MemoryUsage_str_size_impl(ptr, rust_vec_len, data_len), + 67 => wire__crate__api__runtime__MemoryUsage_summary_impl(ptr, rust_vec_len, data_len), + 68 => wire__crate__api__runtime__MemoryUsage_total_allocations_impl( ptr, rust_vec_len, data_len, ), - 52 => { - wire__crate__api__js__MemoryUsage_js_func_pc2line_size_impl(ptr, rust_vec_len, data_len) + 69 => wire__crate__api__runtime__MemoryUsage_total_memory_impl(ptr, rust_vec_len, data_len), + 71 => wire__crate__api__source__js_builtin_options_all_impl(ptr, rust_vec_len, data_len), + 73 => { + wire__crate__api__source__js_builtin_options_essential_impl(ptr, rust_vec_len, data_len) + } + 74 => wire__crate__api__source__js_builtin_options_node_impl(ptr, rust_vec_len, data_len), + 75 => wire__crate__api__source__js_builtin_options_none_impl(ptr, rust_vec_len, data_len), + 76 => wire__crate__api__source__js_builtin_options_web_impl(ptr, rust_vec_len, data_len), + 77 => wire__crate__api__source__js_code_is_bytes_impl(ptr, rust_vec_len, data_len), + 78 => wire__crate__api__source__js_code_is_code_impl(ptr, rust_vec_len, data_len), + 79 => wire__crate__api__source__js_code_is_path_impl(ptr, rust_vec_len, data_len), + 80 => wire__crate__api__error__js_error_code_impl(ptr, rust_vec_len, data_len), + 81 => wire__crate__api__error__js_error_is_recoverable_impl(ptr, rust_vec_len, data_len), + 82 => wire__crate__api__error__js_error_to_string_impl(ptr, rust_vec_len, data_len), + 84 => wire__crate__api__source__js_eval_options_defaults_impl(ptr, rust_vec_len, data_len), + 85 => wire__crate__api__source__js_eval_options_module_impl(ptr, rust_vec_len, data_len), + 86 => wire__crate__api__source__js_eval_options_new_impl(ptr, rust_vec_len, data_len), + 87 => { + wire__crate__api__source__js_eval_options_with_promise_impl(ptr, rust_vec_len, data_len) } - 53 => wire__crate__api__js__MemoryUsage_js_func_size_impl(ptr, rust_vec_len, data_len), - 54 => wire__crate__api__js__MemoryUsage_malloc_count_impl(ptr, rust_vec_len, data_len), - 55 => wire__crate__api__js__MemoryUsage_malloc_limit_impl(ptr, rust_vec_len, data_len), - 56 => wire__crate__api__js__MemoryUsage_malloc_size_impl(ptr, rust_vec_len, data_len), - 57 => wire__crate__api__js__MemoryUsage_memory_used_count_impl(ptr, rust_vec_len, data_len), - 58 => wire__crate__api__js__MemoryUsage_memory_used_size_impl(ptr, rust_vec_len, data_len), - 59 => wire__crate__api__js__MemoryUsage_obj_count_impl(ptr, rust_vec_len, data_len), - 60 => wire__crate__api__js__MemoryUsage_obj_size_impl(ptr, rust_vec_len, data_len), - 61 => wire__crate__api__js__MemoryUsage_prop_count_impl(ptr, rust_vec_len, data_len), - 62 => wire__crate__api__js__MemoryUsage_prop_size_impl(ptr, rust_vec_len, data_len), - 63 => wire__crate__api__js__MemoryUsage_shape_count_impl(ptr, rust_vec_len, data_len), - 64 => wire__crate__api__js__MemoryUsage_shape_size_impl(ptr, rust_vec_len, data_len), - 65 => wire__crate__api__js__MemoryUsage_str_count_impl(ptr, rust_vec_len, data_len), - 66 => wire__crate__api__js__MemoryUsage_str_size_impl(ptr, rust_vec_len, data_len), - 68 => wire__crate__api__js__js_builtin_options_all_impl(ptr, rust_vec_len, data_len), - 69 => wire__crate__api__js__js_error_to_string_impl(ptr, rust_vec_len, data_len), - 70 => wire__crate__api__js__js_eval_options_new_impl(ptr, rust_vec_len, data_len), - 71 => wire__crate__api__js__js_module_bytes_impl(ptr, rust_vec_len, data_len), - 72 => wire__crate__api__js__js_module_code_impl(ptr, rust_vec_len, data_len), - 73 => wire__crate__api__js__js_module_new_impl(ptr, rust_vec_len, data_len), - 74 => wire__crate__api__js__js_module_path_impl(ptr, rust_vec_len, data_len), + 88 => wire__crate__api__source__js_module_from_bytes_impl(ptr, rust_vec_len, data_len), + 89 => wire__crate__api__source__js_module_from_code_impl(ptr, rust_vec_len, data_len), + 90 => wire__crate__api__source__js_module_from_path_impl(ptr, rust_vec_len, data_len), + 91 => wire__crate__api__source__js_module_new_impl(ptr, rust_vec_len, data_len), + 93 => wire__crate__api__value__js_value_is_array_impl(ptr, rust_vec_len, data_len), + 94 => wire__crate__api__value__js_value_is_boolean_impl(ptr, rust_vec_len, data_len), + 95 => wire__crate__api__value__js_value_is_bytes_impl(ptr, rust_vec_len, data_len), + 96 => wire__crate__api__value__js_value_is_date_impl(ptr, rust_vec_len, data_len), + 97 => wire__crate__api__value__js_value_is_none_impl(ptr, rust_vec_len, data_len), + 98 => wire__crate__api__value__js_value_is_number_impl(ptr, rust_vec_len, data_len), + 99 => wire__crate__api__value__js_value_is_object_impl(ptr, rust_vec_len, data_len), + 100 => wire__crate__api__value__js_value_is_primitive_impl(ptr, rust_vec_len, data_len), + 101 => wire__crate__api__value__js_value_is_string_impl(ptr, rust_vec_len, data_len), + 102 => wire__crate__api__value__js_value_type_name_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -4661,10 +5810,10 @@ impl flutter_rust_bridge::IntoIntoDart> for MemoryUsage } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsAction { +impl flutter_rust_bridge::IntoDart for crate::api::engine::JsAction { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsAction::Eval { + crate::api::engine::JsAction::Eval { id, source, options, @@ -4675,50 +5824,65 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsAction { options.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsAction::DeclareNewModule { id, module } => [ + crate::api::engine::JsAction::DeclareNewModule { id, module } => [ 1.into_dart(), id.into_into_dart().into_dart(), module.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsAction::DeclareNewModules { id, modules } => [ + crate::api::engine::JsAction::DeclareNewModules { id, modules } => [ 2.into_dart(), id.into_into_dart().into_dart(), modules.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsAction::ClearNewModules { id } => { + crate::api::engine::JsAction::ClearNewModules { id } => { [3.into_dart(), id.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsAction::EvaluateModule { id, module } => [ + crate::api::engine::JsAction::EvaluateModule { id, module } => [ 4.into_dart(), id.into_into_dart().into_dart(), module.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsAction::GetDeclaredModules { id } => { + crate::api::engine::JsAction::GetDeclaredModules { id } => { [5.into_dart(), id.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsAction::IsModuleDeclared { id, module_name } => [ + crate::api::engine::JsAction::IsModuleDeclared { id, module_name } => [ 6.into_dart(), id.into_into_dart().into_dart(), module_name.into_into_dart().into_dart(), ] .into_dart(), + crate::api::engine::JsAction::CallFunction { + id, + module, + method, + params, + } => [ + 7.into_dart(), + id.into_into_dart().into_dart(), + module.into_into_dart().into_dart(), + method.into_into_dart().into_dart(), + params.into_into_dart().into_dart(), + ] + .into_dart(), _ => { unimplemented!(""); } } } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsAction {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsAction { - fn into_into_dart(self) -> crate::api::js::JsAction { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::engine::JsAction {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::engine::JsAction +{ + fn into_into_dart(self) -> crate::api::engine::JsAction { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsActionResult { +impl flutter_rust_bridge::IntoDart for crate::api::engine::JsActionResult { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.id.into_into_dart().into_dart(), @@ -4728,18 +5892,18 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsActionResult { } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::api::js::JsActionResult + for crate::api::engine::JsActionResult { } -impl flutter_rust_bridge::IntoIntoDart - for crate::api::js::JsActionResult +impl flutter_rust_bridge::IntoIntoDart + for crate::api::engine::JsActionResult { - fn into_into_dart(self) -> crate::api::js::JsActionResult { + fn into_into_dart(self) -> crate::api::engine::JsActionResult { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsBuiltinOptions { +impl flutter_rust_bridge::IntoDart for crate::api::source::JsBuiltinOptions { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.abort.into_into_dart().into_dart(), @@ -4773,25 +5937,25 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsBuiltinOptions { } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::api::js::JsBuiltinOptions + for crate::api::source::JsBuiltinOptions { } -impl flutter_rust_bridge::IntoIntoDart - for crate::api::js::JsBuiltinOptions +impl flutter_rust_bridge::IntoIntoDart + for crate::api::source::JsBuiltinOptions { - fn into_into_dart(self) -> crate::api::js::JsBuiltinOptions { + fn into_into_dart(self) -> crate::api::source::JsBuiltinOptions { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsCallback { +impl flutter_rust_bridge::IntoDart for crate::api::engine::JsCallback { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsCallback::Initialized => [0.into_dart()].into_dart(), - crate::api::js::JsCallback::Handler(field0) => { + crate::api::engine::JsCallback::Initialized => [0.into_dart()].into_dart(), + crate::api::engine::JsCallback::Handler(field0) => { [1.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsCallback::Bridge(field0) => { + crate::api::engine::JsCallback::Bridge(field0) => { [2.into_dart(), field0.into_into_dart().into_dart()].into_dart() } _ => { @@ -4800,19 +5964,24 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsCallback { } } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsCallback {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsCallback { - fn into_into_dart(self) -> crate::api::js::JsCallback { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::engine::JsCallback +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::engine::JsCallback +{ + fn into_into_dart(self) -> crate::api::engine::JsCallback { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsCallbackResult { +impl flutter_rust_bridge::IntoDart for crate::api::engine::JsCallbackResult { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsCallbackResult::Initialized => [0.into_dart()].into_dart(), - crate::api::js::JsCallbackResult::Handler => [1.into_dart()].into_dart(), - crate::api::js::JsCallbackResult::Bridge(field0) => { + crate::api::engine::JsCallbackResult::Initialized => [0.into_dart()].into_dart(), + crate::api::engine::JsCallbackResult::Handler => [1.into_dart()].into_dart(), + crate::api::engine::JsCallbackResult::Bridge(field0) => { [2.into_dart(), field0.into_into_dart().into_dart()].into_dart() } _ => { @@ -4822,27 +5991,27 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsCallbackResult { } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::api::js::JsCallbackResult + for crate::api::engine::JsCallbackResult { } -impl flutter_rust_bridge::IntoIntoDart - for crate::api::js::JsCallbackResult +impl flutter_rust_bridge::IntoIntoDart + for crate::api::engine::JsCallbackResult { - fn into_into_dart(self) -> crate::api::js::JsCallbackResult { + fn into_into_dart(self) -> crate::api::engine::JsCallbackResult { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsCode { +impl flutter_rust_bridge::IntoDart for crate::api::source::JsCode { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsCode::Code(field0) => { + crate::api::source::JsCode::Code(field0) => { [0.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsCode::Path(field0) => { + crate::api::source::JsCode::Path(field0) => { [1.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsCode::Bytes(field0) => { + crate::api::source::JsCode::Bytes(field0) => { [2.into_dart(), field0.into_into_dart().into_dart()].into_dart() } _ => { @@ -4851,20 +6020,20 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsCode { } } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsCode {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsCode { - fn into_into_dart(self) -> crate::api::js::JsCode { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::source::JsCode {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::source::JsCode { + fn into_into_dart(self) -> crate::api::source::JsCode { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsError { +impl flutter_rust_bridge::IntoDart for crate::api::error::JsError { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsError::Promise(field0) => { + crate::api::error::JsError::Promise(field0) => { [0.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Module { + crate::api::error::JsError::Module { module, method, message, @@ -4875,44 +6044,89 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsError { message.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsError::Context(field0) => { + crate::api::error::JsError::Context(field0) => { [2.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Storage(field0) => { + crate::api::error::JsError::Storage(field0) => { [3.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Io { path, message } => [ + crate::api::error::JsError::Io { path, message } => [ 4.into_dart(), path.into_into_dart().into_dart(), message.into_into_dart().into_dart(), ] .into_dart(), - crate::api::js::JsError::Runtime(field0) => { + crate::api::error::JsError::Runtime(field0) => { [5.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Generic(field0) => { + crate::api::error::JsError::Generic(field0) => { [6.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Engine(field0) => { + crate::api::error::JsError::Engine(field0) => { [7.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsError::Bridge(field0) => { + crate::api::error::JsError::Bridge(field0) => { [8.into_dart(), field0.into_into_dart().into_dart()].into_dart() } + crate::api::error::JsError::Conversion { from, to, message } => [ + 9.into_dart(), + from.into_into_dart().into_dart(), + to.into_into_dart().into_dart(), + message.into_into_dart().into_dart(), + ] + .into_dart(), + crate::api::error::JsError::Timeout { + operation, + timeout_ms, + } => [ + 10.into_dart(), + operation.into_into_dart().into_dart(), + timeout_ms.into_into_dart().into_dart(), + ] + .into_dart(), + crate::api::error::JsError::MemoryLimit { current, limit } => [ + 11.into_dart(), + current.into_into_dart().into_dart(), + limit.into_into_dart().into_dart(), + ] + .into_dart(), + crate::api::error::JsError::StackOverflow(field0) => { + [12.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::error::JsError::Syntax { + line, + column, + message, + } => [ + 13.into_dart(), + line.into_into_dart().into_dart(), + column.into_into_dart().into_dart(), + message.into_into_dart().into_dart(), + ] + .into_dart(), + crate::api::error::JsError::Reference(field0) => { + [14.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::error::JsError::Type(field0) => { + [15.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::error::JsError::Cancelled(field0) => { + [16.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } _ => { unimplemented!(""); } } } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsError {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsError { - fn into_into_dart(self) -> crate::api::js::JsError { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::error::JsError {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::error::JsError { + fn into_into_dart(self) -> crate::api::error::JsError { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsEvalOptions { +impl flutter_rust_bridge::IntoDart for crate::api::source::JsEvalOptions { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.global.into_into_dart().into_dart(), @@ -4923,16 +6137,19 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsEvalOptions { .into_dart() } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsEvalOptions {} -impl flutter_rust_bridge::IntoIntoDart - for crate::api::js::JsEvalOptions +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::source::JsEvalOptions +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::source::JsEvalOptions { - fn into_into_dart(self) -> crate::api::js::JsEvalOptions { + fn into_into_dart(self) -> crate::api::source::JsEvalOptions { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsModule { +impl flutter_rust_bridge::IntoDart for crate::api::source::JsModule { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.name.into_into_dart().into_dart(), @@ -4941,20 +6158,22 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsModule { .into_dart() } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsModule {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsModule { - fn into_into_dart(self) -> crate::api::js::JsModule { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::source::JsModule {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::source::JsModule +{ + fn into_into_dart(self) -> crate::api::source::JsModule { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::api::js::JsResult { +impl flutter_rust_bridge::IntoDart for crate::api::error::JsResult { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { - crate::api::js::JsResult::Ok(field0) => { + crate::api::error::JsResult::Ok(field0) => { [0.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::js::JsResult::Err(field0) => { + crate::api::error::JsResult::Err(field0) => { [1.into_dart(), field0.into_into_dart().into_dart()].into_dart() } _ => { @@ -4963,9 +6182,11 @@ impl flutter_rust_bridge::IntoDart for crate::api::js::JsResult { } } } -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::js::JsResult {} -impl flutter_rust_bridge::IntoIntoDart for crate::api::js::JsResult { - fn into_into_dart(self) -> crate::api::js::JsResult { +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::error::JsResult {} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::error::JsResult +{ + fn into_into_dart(self) -> crate::api::error::JsResult { self } } @@ -4989,12 +6210,24 @@ impl flutter_rust_bridge::IntoDart for crate::api::value::JsValue { crate::api::value::JsValue::String(field0) => { [5.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::value::JsValue::Array(field0) => { + crate::api::value::JsValue::Bytes(field0) => { [6.into_dart(), field0.into_into_dart().into_dart()].into_dart() } - crate::api::value::JsValue::Object(field0) => { + crate::api::value::JsValue::Array(field0) => { [7.into_dart(), field0.into_into_dart().into_dart()].into_dart() } + crate::api::value::JsValue::Object(field0) => { + [8.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::value::JsValue::Date(field0) => { + [9.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::value::JsValue::Symbol(field0) => { + [10.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } + crate::api::value::JsValue::Function(field0) => { + [11.into_dart(), field0.into_into_dart().into_dart()].into_dart() + } _ => { unimplemented!(""); } @@ -5178,48 +6411,60 @@ impl SseEncode for isize { } } -impl SseEncode for crate::api::js::JsAction { +impl SseEncode for crate::api::engine::JsAction { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsAction::Eval { + crate::api::engine::JsAction::Eval { id, source, options, } => { ::sse_encode(0, serializer); ::sse_encode(id, serializer); - ::sse_encode(source, serializer); - >::sse_encode(options, serializer); + ::sse_encode(source, serializer); + >::sse_encode(options, serializer); } - crate::api::js::JsAction::DeclareNewModule { id, module } => { + crate::api::engine::JsAction::DeclareNewModule { id, module } => { ::sse_encode(1, serializer); ::sse_encode(id, serializer); - ::sse_encode(module, serializer); + ::sse_encode(module, serializer); } - crate::api::js::JsAction::DeclareNewModules { id, modules } => { + crate::api::engine::JsAction::DeclareNewModules { id, modules } => { ::sse_encode(2, serializer); ::sse_encode(id, serializer); - >::sse_encode(modules, serializer); + >::sse_encode(modules, serializer); } - crate::api::js::JsAction::ClearNewModules { id } => { + crate::api::engine::JsAction::ClearNewModules { id } => { ::sse_encode(3, serializer); ::sse_encode(id, serializer); } - crate::api::js::JsAction::EvaluateModule { id, module } => { + crate::api::engine::JsAction::EvaluateModule { id, module } => { ::sse_encode(4, serializer); ::sse_encode(id, serializer); - ::sse_encode(module, serializer); + ::sse_encode(module, serializer); } - crate::api::js::JsAction::GetDeclaredModules { id } => { + crate::api::engine::JsAction::GetDeclaredModules { id } => { ::sse_encode(5, serializer); ::sse_encode(id, serializer); } - crate::api::js::JsAction::IsModuleDeclared { id, module_name } => { + crate::api::engine::JsAction::IsModuleDeclared { id, module_name } => { ::sse_encode(6, serializer); ::sse_encode(id, serializer); ::sse_encode(module_name, serializer); } + crate::api::engine::JsAction::CallFunction { + id, + module, + method, + params, + } => { + ::sse_encode(7, serializer); + ::sse_encode(id, serializer); + ::sse_encode(module, serializer); + ::sse_encode(method, serializer); + >>::sse_encode(params, serializer); + } _ => { unimplemented!(""); } @@ -5227,15 +6472,15 @@ impl SseEncode for crate::api::js::JsAction { } } -impl SseEncode for crate::api::js::JsActionResult { +impl SseEncode for crate::api::engine::JsActionResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.id, serializer); - ::sse_encode(self.result, serializer); + ::sse_encode(self.result, serializer); } } -impl SseEncode for crate::api::js::JsBuiltinOptions { +impl SseEncode for crate::api::source::JsBuiltinOptions { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { >::sse_encode(self.abort, serializer); @@ -5267,18 +6512,18 @@ impl SseEncode for crate::api::js::JsBuiltinOptions { } } -impl SseEncode for crate::api::js::JsCallback { +impl SseEncode for crate::api::engine::JsCallback { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsCallback::Initialized => { + crate::api::engine::JsCallback::Initialized => { ::sse_encode(0, serializer); } - crate::api::js::JsCallback::Handler(field0) => { + crate::api::engine::JsCallback::Handler(field0) => { ::sse_encode(1, serializer); - ::sse_encode(field0, serializer); + ::sse_encode(field0, serializer); } - crate::api::js::JsCallback::Bridge(field0) => { + crate::api::engine::JsCallback::Bridge(field0) => { ::sse_encode(2, serializer); ::sse_encode(field0, serializer); } @@ -5289,19 +6534,19 @@ impl SseEncode for crate::api::js::JsCallback { } } -impl SseEncode for crate::api::js::JsCallbackResult { +impl SseEncode for crate::api::engine::JsCallbackResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsCallbackResult::Initialized => { + crate::api::engine::JsCallbackResult::Initialized => { ::sse_encode(0, serializer); } - crate::api::js::JsCallbackResult::Handler => { + crate::api::engine::JsCallbackResult::Handler => { ::sse_encode(1, serializer); } - crate::api::js::JsCallbackResult::Bridge(field0) => { + crate::api::engine::JsCallbackResult::Bridge(field0) => { ::sse_encode(2, serializer); - ::sse_encode(field0, serializer); + ::sse_encode(field0, serializer); } _ => { unimplemented!(""); @@ -5310,19 +6555,19 @@ impl SseEncode for crate::api::js::JsCallbackResult { } } -impl SseEncode for crate::api::js::JsCode { +impl SseEncode for crate::api::source::JsCode { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsCode::Code(field0) => { + crate::api::source::JsCode::Code(field0) => { ::sse_encode(0, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsCode::Path(field0) => { + crate::api::source::JsCode::Path(field0) => { ::sse_encode(1, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsCode::Bytes(field0) => { + crate::api::source::JsCode::Bytes(field0) => { ::sse_encode(2, serializer); >::sse_encode(field0, serializer); } @@ -5333,15 +6578,15 @@ impl SseEncode for crate::api::js::JsCode { } } -impl SseEncode for crate::api::js::JsError { +impl SseEncode for crate::api::error::JsError { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsError::Promise(field0) => { + crate::api::error::JsError::Promise(field0) => { ::sse_encode(0, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Module { + crate::api::error::JsError::Module { module, method, message, @@ -5351,35 +6596,80 @@ impl SseEncode for crate::api::js::JsError { >::sse_encode(method, serializer); ::sse_encode(message, serializer); } - crate::api::js::JsError::Context(field0) => { + crate::api::error::JsError::Context(field0) => { ::sse_encode(2, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Storage(field0) => { + crate::api::error::JsError::Storage(field0) => { ::sse_encode(3, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Io { path, message } => { + crate::api::error::JsError::Io { path, message } => { ::sse_encode(4, serializer); >::sse_encode(path, serializer); ::sse_encode(message, serializer); } - crate::api::js::JsError::Runtime(field0) => { + crate::api::error::JsError::Runtime(field0) => { ::sse_encode(5, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Generic(field0) => { + crate::api::error::JsError::Generic(field0) => { ::sse_encode(6, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Engine(field0) => { + crate::api::error::JsError::Engine(field0) => { ::sse_encode(7, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsError::Bridge(field0) => { + crate::api::error::JsError::Bridge(field0) => { ::sse_encode(8, serializer); ::sse_encode(field0, serializer); } + crate::api::error::JsError::Conversion { from, to, message } => { + ::sse_encode(9, serializer); + ::sse_encode(from, serializer); + ::sse_encode(to, serializer); + ::sse_encode(message, serializer); + } + crate::api::error::JsError::Timeout { + operation, + timeout_ms, + } => { + ::sse_encode(10, serializer); + ::sse_encode(operation, serializer); + ::sse_encode(timeout_ms, serializer); + } + crate::api::error::JsError::MemoryLimit { current, limit } => { + ::sse_encode(11, serializer); + ::sse_encode(current, serializer); + ::sse_encode(limit, serializer); + } + crate::api::error::JsError::StackOverflow(field0) => { + ::sse_encode(12, serializer); + ::sse_encode(field0, serializer); + } + crate::api::error::JsError::Syntax { + line, + column, + message, + } => { + ::sse_encode(13, serializer); + >::sse_encode(line, serializer); + >::sse_encode(column, serializer); + ::sse_encode(message, serializer); + } + crate::api::error::JsError::Reference(field0) => { + ::sse_encode(14, serializer); + ::sse_encode(field0, serializer); + } + crate::api::error::JsError::Type(field0) => { + ::sse_encode(15, serializer); + ::sse_encode(field0, serializer); + } + crate::api::error::JsError::Cancelled(field0) => { + ::sse_encode(16, serializer); + ::sse_encode(field0, serializer); + } _ => { unimplemented!(""); } @@ -5387,7 +6677,7 @@ impl SseEncode for crate::api::js::JsError { } } -impl SseEncode for crate::api::js::JsEvalOptions { +impl SseEncode for crate::api::source::JsEvalOptions { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { >::sse_encode(self.global, serializer); @@ -5397,25 +6687,25 @@ impl SseEncode for crate::api::js::JsEvalOptions { } } -impl SseEncode for crate::api::js::JsModule { +impl SseEncode for crate::api::source::JsModule { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.name, serializer); - ::sse_encode(self.source, serializer); + ::sse_encode(self.source, serializer); } } -impl SseEncode for crate::api::js::JsResult { +impl SseEncode for crate::api::error::JsResult { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { match self { - crate::api::js::JsResult::Ok(field0) => { + crate::api::error::JsResult::Ok(field0) => { ::sse_encode(0, serializer); ::sse_encode(field0, serializer); } - crate::api::js::JsResult::Err(field0) => { + crate::api::error::JsResult::Err(field0) => { ::sse_encode(1, serializer); - ::sse_encode(field0, serializer); + ::sse_encode(field0, serializer); } _ => { unimplemented!(""); @@ -5451,16 +6741,32 @@ impl SseEncode for crate::api::value::JsValue { ::sse_encode(5, serializer); ::sse_encode(field0, serializer); } - crate::api::value::JsValue::Array(field0) => { + crate::api::value::JsValue::Bytes(field0) => { ::sse_encode(6, serializer); + >::sse_encode(field0, serializer); + } + crate::api::value::JsValue::Array(field0) => { + ::sse_encode(7, serializer); >::sse_encode(field0, serializer); } crate::api::value::JsValue::Object(field0) => { - ::sse_encode(7, serializer); + ::sse_encode(8, serializer); >::sse_encode( field0, serializer, ); } + crate::api::value::JsValue::Date(field0) => { + ::sse_encode(9, serializer); + ::sse_encode(field0, serializer); + } + crate::api::value::JsValue::Symbol(field0) => { + ::sse_encode(10, serializer); + ::sse_encode(field0, serializer); + } + crate::api::value::JsValue::Function(field0) => { + ::sse_encode(11, serializer); + ::sse_encode(field0, serializer); + } _ => { unimplemented!(""); } @@ -5468,12 +6774,12 @@ impl SseEncode for crate::api::value::JsValue { } } -impl SseEncode for Vec { +impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.len() as _, serializer); for item in self { - ::sse_encode(item, serializer); + ::sse_encode(item, serializer); } } } @@ -5528,32 +6834,42 @@ impl SseEncode for Option { } } -impl SseEncode for Option { +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + +impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.is_some(), serializer); if let Some(value) = self { - ::sse_encode(value, serializer); + ::sse_encode(value, serializer); } } } -impl SseEncode for Option { +impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.is_some(), serializer); if let Some(value) = self { - ::sse_encode(value, serializer); + ::sse_encode(value, serializer); } } } -impl SseEncode for Option> { +impl SseEncode for Option> { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.is_some(), serializer); if let Some(value) = self { - >::sse_encode(value, serializer); + >::sse_encode(value, serializer); } } } @@ -5627,7 +6943,8 @@ mod io { // Section: imports use super::*; - use crate::api::js::*; + use crate::api::engine::*; + use crate::api::runtime::*; use flutter_rust_bridge::for_generated::byteorder::{ NativeEndian, ReadBytesExt, WriteBytesExt, }; @@ -5734,7 +7051,8 @@ mod web { // Section: imports use super::*; - use crate::api::js::*; + use crate::api::engine::*; + use crate::api::runtime::*; use flutter_rust_bridge::for_generated::byteorder::{ NativeEndian, ReadBytesExt, WriteBytesExt, }; diff --git a/pubspec.yaml b/pubspec.yaml index 0d23259..ff42f54 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: fjs description: "A high-performance JavaScript runtime for Flutter applications, built with Rust and powered by QuickJS." -version: 1.3.0 +version: 1.3.1 homepage: https://github.com/fluttercandies/fjs repository: https://github.com/fluttercandies/fjs issue_tracker: https://github.com/fluttercandies/fjs/issues From a9cd6548e8ca4fa8a1f5647a665d8b12b6ab9022 Mon Sep 17 00:00:00 2001 From: iota9star Date: Mon, 1 Dec 2025 13:18:31 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9D=20update:=20modify=20runtime?= =?UTF-8?q?=20API=20and=20integration=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update CHANGELOG.md with latest changes - Modify integration test in example - Update runtime.rs implementation - Sync package dependencies --- CHANGELOG.md | 16 +- example/integration_test/simple_test.dart | 1758 ++++++++++++++++++++- example/pubspec.lock | 2 +- libfjs/src/api/runtime.rs | 46 +- pubspec.yaml | 2 +- 5 files changed, 1811 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0ceaf7..e4d4ce9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,21 @@ # Changelog -## 1.3.1 +## 1.4.0 -* **PERFORMANCE**: Optimized BigInt conversion using native rquickjs API instead of JavaScript evaluation -* **PERFORMANCE**: Improved Symbol description extraction using native rquickjs Symbol API -* **PERFORMANCE**: Simplified file reading with direct `tokio::fs::read()` call +* **BREAKING**: Restructured API modules - removed deprecated `js` module, added `engine`, `error`, `runtime`, and `source` modules for better organization +* **FIX**: Fixed Promise result unwrapping - QuickJS's `JS_EVAL_FLAG_ASYNC` wraps Promise results in `{value: xxx}` format, now properly detected and unwrapped by checking for objects with exactly one `value` property +* **FIX**: Fixed nested Promise handling to correctly await and unwrap chained Promises +* **FIX**: Fixed `undefined` value handling in Promise results - now correctly returns `JsValue.none()` instead of the wrapper object * **FIX**: Fixed `DynamicModuleResolver` to properly check module existence before resolving * **FIX**: Fixed `build_loaders()` to properly include additional modules in resolver and loader chains * **FIX**: Fixed `GlobalAttachment` to correctly initialize each context independently using context-level userdata +* **PERFORMANCE**: Optimized BigInt conversion using native rquickjs API instead of JavaScript evaluation +* **PERFORMANCE**: Improved Symbol description extraction using native rquickjs Symbol API +* **PERFORMANCE**: Simplified file reading with direct `tokio::fs::read()` call +* **IMPROVEMENT**: Added comprehensive integration tests (130+ test cases) covering Promise edge cases, boundary conditions, bridge call scenarios, and memory management +* **IMPROVEMENT**: Updated example app with new API screens for engine, error, runtime, and source modules +* **IMPROVEMENT**: Added widgets directory for reusable UI components in example app +* **INTERNAL**: Improved Promise result detection logic using object key enumeration instead of direct property access * **INTERNAL**: Removed unused variable in bridge call function * **INTERNAL**: Improved code clarity and reduced redundant logic diff --git a/example/integration_test/simple_test.dart b/example/integration_test/simple_test.dart index a8fa54e..0654fd3 100644 --- a/example/integration_test/simple_test.dart +++ b/example/integration_test/simple_test.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:integration_test/integration_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:fjs/fjs.dart'; @@ -5,7 +7,1759 @@ import 'package:fjs/fjs.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async => await LibFjs.init()); - test('Can call rust function', () async { - // expect(greet(name: "Tom"), "Hello, Tom!"); + + group('JsValue Tests', () { + test('JsValue.from - primitive type conversion', () { + // null + expect(JsValue.from(null), const JsValue.none()); + + // bool + expect(JsValue.from(true), const JsValue.boolean(true)); + expect(JsValue.from(false), const JsValue.boolean(false)); + + // int + expect(JsValue.from(42), const JsValue.integer(42)); + expect(JsValue.from(-100), const JsValue.integer(-100)); + expect(JsValue.from(0), const JsValue.integer(0)); + + // double + expect(JsValue.from(3.14), const JsValue.float(3.14)); + expect(JsValue.from(-2.5), const JsValue.float(-2.5)); + + // String + expect(JsValue.from('hello'), const JsValue.string('hello')); + expect(JsValue.from(''), const JsValue.string('')); + + // BigInt + final bigInt = BigInt.parse('9999999999999999999999'); + expect(JsValue.from(bigInt), JsValue.bigint(bigInt.toString())); + + // Uint8List + final bytes = Uint8List.fromList([1, 2, 3, 4, 5]); + expect(JsValue.from(bytes), JsValue.bytes(bytes)); + }); + + test('JsValue.from - collection type conversion', () { + // List + final list = [1, 'hello', true]; + final jsArray = JsValue.from(list); + expect(jsArray.isArray(), true); + expect( + jsArray, + const JsValue.array([ + JsValue.integer(1), + JsValue.string('hello'), + JsValue.boolean(true), + ]), + ); + + // Map + final map = {'name': 'test', 'age': 25}; + final jsObject = JsValue.from(map); + expect(jsObject.isObject(), true); + }); + + test('JsValue type checking methods', () { + expect(const JsValue.none().isNone(), true); + expect(const JsValue.boolean(true).isBoolean(), true); + expect(const JsValue.integer(42).isNumber(), true); + expect(const JsValue.float(3.14).isNumber(), true); + expect(const JsValue.string('test').isString(), true); + expect(JsValue.bytes(Uint8List(0)).isBytes(), true); + expect(const JsValue.array([]).isArray(), true); + expect(const JsValue.object({}).isObject(), true); + + // isPrimitive + expect(const JsValue.boolean(true).isPrimitive(), true); + expect(const JsValue.integer(42).isPrimitive(), true); + expect(const JsValue.string('test').isPrimitive(), true); + expect(const JsValue.array([]).isPrimitive(), false); + expect(const JsValue.object({}).isPrimitive(), false); + }); + + test('JsValue.value getter', () { + expect(const JsValue.none().value, null); + expect(const JsValue.boolean(true).value, true); + expect(const JsValue.integer(42).value, 42); + expect(const JsValue.float(3.14).value, 3.14); + expect(const JsValue.string('hello').value, 'hello'); + + final date = const JsValue.date(1609459200000); + expect(date.value, isA()); + }); + + test('JsValue safe casting getters', () { + expect(const JsValue.boolean(true).asBoolean, true); + expect(const JsValue.integer(42).asInteger, 42); + expect(const JsValue.float(3.14).asFloat, 3.14); + expect(const JsValue.string('test').asString, 'test'); + + // Wrong type returns null + expect(const JsValue.string('test').asBoolean, null); + expect(const JsValue.boolean(true).asInteger, null); + }); + + test('JsValue.typeName', () { + // Note: JsValue.none() corresponds to JavaScript null/undefined, so typeName returns 'null' + expect(const JsValue.none().typeName(), 'null'); + expect(const JsValue.boolean(true).typeName(), 'boolean'); + // In JavaScript, both integer and float are 'number' type + expect(const JsValue.integer(42).typeName(), 'number'); + expect(const JsValue.float(3.14).typeName(), 'number'); + expect(const JsValue.string('test').typeName(), 'string'); + }); + }); + + group('JsCode Tests', () { + test('JsCode variants', () { + const code = JsCode.code('console.log("hello")'); + expect(code.isCode(), true); + expect(code.isPath(), false); + expect(code.isBytes(), false); + + const path = JsCode.path('/path/to/file.js'); + expect(path.isPath(), true); + + final bytes = JsCode.bytes(Uint8List.fromList([65, 66, 67])); + expect(bytes.isBytes(), true); + }); + }); + + group('JsBuiltinOptions Tests', () { + test('Preset options', () { + final all = JsBuiltinOptions.all(); + expect(all, isNotNull); + + final none = JsBuiltinOptions.none(); + expect(none, isNotNull); + + final essential = JsBuiltinOptions.essential(); + expect(essential, isNotNull); + + final web = JsBuiltinOptions.web(); + expect(web, isNotNull); + + final node = JsBuiltinOptions.node(); + expect(node, isNotNull); + }); + + test('Custom options', () { + const options = JsBuiltinOptions( + console: true, + timers: true, + fetch: false, + ); + expect(options.console, true); + expect(options.timers, true); + expect(options.fetch, false); + }); + }); + + group('JsEvalOptions Tests', () { + test('Preset options', () { + final defaults = JsEvalOptions.defaults(); + expect(defaults, isNotNull); + + final module = JsEvalOptions.module(); + expect(module, isNotNull); + + final withPromise = JsEvalOptions.withPromise(); + expect(withPromise, isNotNull); + }); + + test('Custom options', () { + final options = JsEvalOptions( + global: true, + strict: true, + promise: false, + ); + expect(options, isNotNull); + }); + }); + + group('JsModule Tests', () { + test('Create modules', () { + final fromCode = + JsModule.fromCode(module: 'test', code: 'export const x = 1;'); + expect(fromCode.name, 'test'); + + final fromPath = + JsModule.fromPath(module: 'test2', path: '/path/to/module.js'); + expect(fromPath.name, 'test2'); + + final fromBytes = JsModule.fromBytes( + module: 'test3', + bytes: [65, 66, 67], + ); + expect(fromBytes.name, 'test3'); + + final custom = JsModule( + name: 'custom', + source: const JsCode.code('export const y = 2;'), + ); + expect(custom.name, 'custom'); + }); + }); + + group('JsError Tests', () { + test('Error types', () { + const promiseError = JsError.promise('Promise rejected'); + expect(promiseError.code(), isNotEmpty); + expect(promiseError.isRecoverable(), isA()); + + const moduleError = JsError.module( + module: 'testModule', + method: 'testMethod', + message: 'Module not found', + ); + expect(moduleError.code(), isNotEmpty); + + const syntaxError = JsError.syntax( + line: 10, + column: 5, + message: 'Unexpected token', + ); + expect(syntaxError.code(), isNotEmpty); + + const engineError = JsError.engine('Engine not initialized'); + expect(engineError.toString(), contains('Engine not initialized')); + }); + }); + + group('JsResult Tests', () { + test('Ok result', () { + const result = JsResult.ok(JsValue.integer(42)); + expect(result.isOk, true); + expect(result.isErr, false); + expect(result.ok.value, 42); + }); + + test('Err result', () { + const result = JsResult.err(JsError.generic('Something went wrong')); + expect(result.isOk, false); + expect(result.isErr, true); + expect(result.err, isA()); + }); + }); + + group('Sync Runtime and Context Tests', () { + late JsRuntime runtime; + late JsContext context; + + setUp(() async { + runtime = await JsRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + context = JsContext(rt: runtime); + }); + + test('Basic expression evaluation', () { + final result = context.eval(code: '1 + 2 + 3'); + expect(result.isOk, true); + expect(result.ok.value, 6); + }); + + test('String operations', () { + final result = context.eval(code: '"Hello, " + "World!"'); + expect(result.isOk, true); + expect(result.ok.value, 'Hello, World!'); + }); + + test('Array operations', () { + final result = context.eval(code: '[1, 2, 3].map(x => x * 2)'); + expect(result.isOk, true); + expect(result.ok.isArray(), true); + final arr = result.ok.value as List; + expect(arr, [2, 4, 6]); + }); + + test('Object operations', () { + final result = context.eval(code: '({name: "test", value: 42})'); + expect(result.isOk, true); + expect(result.ok.isObject(), true); + final obj = result.ok.value as Map; + expect(obj['name'], 'test'); + expect(obj['value'], 42); + }); + + test('Boolean expressions', () { + expect(context.eval(code: 'true && false').ok.value, false); + expect(context.eval(code: 'true || false').ok.value, true); + expect(context.eval(code: '!true').ok.value, false); + }); + + test('Comparison operators', () { + expect(context.eval(code: '5 > 3').ok.value, true); + expect(context.eval(code: '5 < 3').ok.value, false); + expect(context.eval(code: '5 === 5').ok.value, true); + expect(context.eval(code: '5 !== 3').ok.value, true); + }); + + test('Function definition and call', () { + context.eval(code: 'function add(a, b) { return a + b; }'); + final result = context.eval(code: 'add(10, 20)'); + expect(result.isOk, true); + expect(result.ok.value, 30); + }); + + test('Arrow functions', () { + final result = context.eval(code: '((x, y) => x * y)(4, 5)'); + expect(result.isOk, true); + expect(result.ok.value, 20); + }); + + test('Template strings', () { + final result = + context.eval(code: 'const name = "World"; `Hello, \${name}!`'); + expect(result.isOk, true); + expect(result.ok.value, 'Hello, World!'); + }); + + test('Destructuring assignment', () { + final result = + context.eval(code: 'const [a, b, c] = [1, 2, 3]; a + b + c'); + expect(result.isOk, true); + expect(result.ok.value, 6); + }); + + test('Spread operator', () { + final result = context.eval(code: '[...[1, 2], ...[3, 4]]'); + expect(result.isOk, true); + expect(result.ok.value, [1, 2, 3, 4]); + }); + + test('Math object', () { + expect(context.eval(code: 'Math.abs(-5)').ok.value, 5); + expect(context.eval(code: 'Math.max(1, 5, 3)').ok.value, 5); + expect(context.eval(code: 'Math.min(1, 5, 3)').ok.value, 1); + expect(context.eval(code: 'Math.floor(3.7)').ok.value, 3); + expect(context.eval(code: 'Math.ceil(3.2)').ok.value, 4); + expect(context.eval(code: 'Math.round(3.5)').ok.value, 4); + }); + + test('JSON operations', () { + final parseResult = + context.eval(code: 'JSON.parse(\'{"a": 1, "b": 2}\')'); + expect(parseResult.isOk, true); + expect((parseResult.ok.value as Map)['a'], 1); + + final stringifyResult = + context.eval(code: 'JSON.stringify({x: 10, y: 20})'); + expect(stringifyResult.isOk, true); + expect(stringifyResult.ok.value, '{"x":10,"y":20}'); + }); + + test('Array methods', () { + expect(context.eval(code: '[1, 2, 3].length').ok.value, 3); + expect(context.eval(code: '[1, 2, 3].includes(2)').ok.value, true); + expect(context.eval(code: '[1, 2, 3].indexOf(2)').ok.value, 1); + expect( + context.eval(code: '[1, 2, 3].filter(x => x > 1)').ok.value, [2, 3]); + expect( + context.eval(code: '[1, 2, 3].reduce((a, b) => a + b, 0)').ok.value, + 6); + expect(context.eval(code: '[1, 2, 3].every(x => x > 0)').ok.value, true); + expect(context.eval(code: '[1, 2, 3].some(x => x > 2)').ok.value, true); + }); + + test('String methods', () { + expect(context.eval(code: '"hello".toUpperCase()').ok.value, 'HELLO'); + expect(context.eval(code: '"HELLO".toLowerCase()').ok.value, 'hello'); + expect(context.eval(code: '"hello world".split(" ")').ok.value, + ['hello', 'world']); + expect(context.eval(code: '" hello ".trim()').ok.value, 'hello'); + expect(context.eval(code: '"hello".includes("ell")').ok.value, true); + expect(context.eval(code: '"hello".startsWith("he")').ok.value, true); + expect(context.eval(code: '"hello".endsWith("lo")').ok.value, true); + expect(context.eval(code: '"hello".substring(1, 4)').ok.value, 'ell'); + }); + + test('Object methods', () { + expect( + context.eval(code: 'Object.keys({a: 1, b: 2})').ok.value, ['a', 'b']); + expect( + context.eval(code: 'Object.values({a: 1, b: 2})').ok.value, [1, 2]); + }); + + test('Syntax error handling', () { + final result = context.eval(code: 'function {'); + expect(result.isErr, true); + }); + + test('Runtime error handling', () { + final result = context.eval(code: 'nonExistentVariable'); + expect(result.isErr, true); + }); + + test('Evaluation with options', () { + final result = context.evalWithOptions( + code: '"use strict"; let x = 10; x', + options: JsEvalOptions(strict: true), + ); + expect(result.isOk, true); + expect(result.ok.value, 10); + }); + + test('Memory usage statistics', () { + final usage = runtime.memoryUsage(); + expect(usage.totalMemory, greaterThanOrEqualTo(0)); + expect(usage.summary(), isNotEmpty); + }); + + test('Garbage collection', () { + // Create some objects + context.eval( + code: 'let arr = []; for(let i=0; i<100; i++) arr.push({x: i});'); + runtime.runGc(); + // Verify runtime still works + final result = context.eval(code: '1 + 1'); + expect(result.ok.value, 2); + }); + + test('Set memory limit', () { + runtime.setMemoryLimit(limit: BigInt.from(50 * 1024 * 1024)); // 50MB + final result = context.eval(code: '1 + 1'); + expect(result.isOk, true); + }); + + test('Set stack size limit', () { + runtime.setMaxStackSize(limit: BigInt.from(1024 * 1024)); // 1MB + final result = context.eval(code: '1 + 1'); + expect(result.isOk, true); + }); + + test('Pending jobs check', () { + expect(runtime.isJobPending(), isA()); + }); + }); + + group('Async Runtime and Context Tests', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + context = await JsAsyncContext.from(rt: runtime); + }); + + test('Async basic expression evaluation', () async { + final result = await context.eval(code: '2 * 3 * 4'); + expect(result.isOk, true); + expect(result.ok.value, equals(24)); + }); + + test('Async string operations', () async { + final result = + await context.eval(code: '"async".toUpperCase() + " test"'); + expect(result.isOk, true); + expect(result.ok.value, equals('ASYNC test')); + }); + + test('Async memory usage', () async { + final usage = await runtime.memoryUsage(); + expect(usage.totalMemory, greaterThanOrEqualTo(0)); + }); + + test('Async garbage collection', () async { + await runtime.runGc(); + final result = await context.eval(code: '42'); + expect(result.ok.value, equals(42)); + }); + + test('Async set memory limit', () async { + await runtime.setMemoryLimit(limit: BigInt.from(100 * 1024 * 1024)); + final result = await context.eval(code: '1 + 1'); + expect(result.isOk, true); + }); + + test('Async pending jobs', () async { + final pending = await runtime.isJobPending(); + expect(pending, isA()); + }); + + test('Async evaluation with options', () async { + final result = await context.evalWithOptions( + code: 'const result = 100; result', + options: JsEvalOptions(global: true), + ); + expect(result.isOk, true); + expect(result.ok.value, equals(100)); + }); + + test('Async Promise evaluation via JsAsyncContext', () async { + final result = await context.eval( + code: 'new Promise((resolve) => { resolve(42); })', + ); + print('DEBUG JsAsyncContext Promise: result.isOk = ${result.isOk}'); + print('DEBUG JsAsyncContext Promise: result.ok = ${result.ok}'); + print( + 'DEBUG JsAsyncContext Promise: result.ok.value = ${result.ok.value}'); + expect(result.isOk, true); + expect(result.ok.value, equals(42)); + }); + }); + + group('JsEngine Advanced Tests', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Engine initialization', () async { + expect(engine.initialized, false); + await engine.init(); + expect(engine.initialized, true); + expect(engine.running, true); + }); + + test('Basic evaluation', () async { + await engine.init(); + + final result = await engine.eval(const JsCode.code('100 + 200')); + expect(result.value, equals(300)); + }); + + test('Complex expression evaluation', () async { + await engine.init(); + + final result = await engine.eval( + const JsCode.code(''' + function fibonacci(n) { + if (n <= 1) return n; + return fibonacci(n - 1) + fibonacci(n - 2); + } + fibonacci(10) + '''), + ); + expect(result.value, equals(55)); + }); + + test('Module declaration and usage', () async { + await engine.init(); + + // Declare module + await engine.declareNewModule( + JsModule.fromCode( + module: 'math-utils', + code: ''' + export const add = (a, b) => a + b; + export const multiply = (a, b) => a * b; + export const square = (x) => x * x; + ''', + ), + ); + + // Check if module is declared + final isDeclared = await engine.isModuleDeclared('math-utils'); + expect(isDeclared, true); + + // Get all declared modules + final modules = await engine.getDeclaredModules(); + expect(modules, contains('math-utils')); + }); + + test('Multiple module declaration', () async { + await engine.init(); + + await engine.declareNewModules([ + JsModule.fromCode( + module: 'string-utils', + code: ''' + export const reverse = (s) => s.split("").reverse().join(""); + export const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1); + ''', + ), + JsModule.fromCode( + module: 'array-utils', + code: ''' + export const sum = (arr) => arr.reduce((a, b) => a + b, 0); + export const average = (arr) => sum(arr) / arr.length; + ''', + ), + ]); + + final modules = await engine.getDeclaredModules(); + expect(modules, containsAll(['string-utils', 'array-utils'])); + }); + + test('Clear modules', () async { + await engine.init(); + + await engine.declareNewModule( + JsModule.fromCode(module: 'temp-module', code: 'export const x = 1;'), + ); + + expect(await engine.isModuleDeclared('temp-module'), true); + + await engine.clearNewModules(); + + expect(await engine.isModuleDeclared('temp-module'), false); + }); + + test('Evaluation with options', () async { + await engine.init(); + + final result = await engine.eval( + const JsCode.code('let strictVar = 123; strictVar'), + options: JsEvalOptions(strict: true), + ); + expect(result.value, equals(123)); + }); + + test('Bridge call', () async { + String? receivedValue; + + await engine.init( + bridgeCall: (value) async { + receivedValue = value.asString; + return const JsValue.string('Response from Dart!'); + }, + ); + + final result = await engine.eval( + const JsCode.code('await fjs.bridge_call("Hello from JS")'), + options: JsEvalOptions.withPromise(), + ); + + expect(receivedValue, equals('Hello from JS')); + expect(result.asString, equals('Response from Dart!')); + }); + + test('Bridge call - complex data', () async { + dynamic receivedData; + + await engine.init( + bridgeCall: (value) async { + receivedData = value.value; + return JsValue.from({'received': true, 'data': receivedData}); + }, + ); + + final result = await engine.eval( + const JsCode.code( + 'await fjs.bridge_call({name: "test", values: [1, 2, 3]})'), + options: JsEvalOptions.withPromise(), + ); + + print('DEBUG: receivedData = $receivedData'); + print('DEBUG: result = $result'); + print('DEBUG: result.runtimeType = ${result.runtimeType}'); + expect(receivedData, isA()); + expect((receivedData as Map)['name'], equals('test')); + // The bridge_call returns the value passed back from Dart + expect(result.value, isA()); + }); + + test('Error handling - syntax error', () async { + await engine.init(); + + expect( + () => engine.eval(const JsCode.code('function {')), + throwsA(isA()), + ); + }); + + test('Error handling - runtime error', () async { + await engine.init(); + + expect( + () => engine.eval(const JsCode.code('undefinedVariable.property')), + throwsA(isA()), + ); + }); + + test('Engine disposal', () async { + await engine.init(); + expect(engine.disposed, false); + + await engine.dispose(); + expect(engine.disposed, true); + }); + + test('Duplicate initialization should throw', () async { + await engine.init(); + + expect( + () => engine.init(), + throwsA(isA()), + ); + }); + + test('Use after disposal should throw', () async { + await engine.init(); + await engine.dispose(); + + expect( + () => engine.eval(const JsCode.code('1 + 1')), + throwsA(isA()), + ); + }); + + test('Use without initialization should throw', () async { + expect( + () => engine.eval(const JsCode.code('1 + 1')), + throwsA(isA()), + ); + }); + + test('Timeout handling', () async { + await engine.init(); + + // Execute a fast operation with short timeout + final result = await engine.eval( + const JsCode.code('1 + 1'), + timeout: const Duration(seconds: 5), + ); + expect(result.value, equals(2)); + }); + }); + + group('ES6+ Features Tests', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + await engine.init(); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Class definition', () async { + final result = await engine.eval( + const JsCode.code(''' + class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + greet() { + return "Hello, I'm " + this.name; + } + } + const p = new Person("Alice", 30); + p.greet() + '''), + ); + expect(result.value, equals("Hello, I'm Alice")); + }); + + test('Class inheritance', () async { + final result = await engine.eval( + const JsCode.code(''' + class Animal { + constructor(name) { this.name = name; } + speak() { return this.name + " makes a sound"; } + } + class Dog extends Animal { + speak() { return this.name + " barks"; } + } + const d = new Dog("Rex"); + d.speak() + '''), + ); + expect(result.value, equals('Rex barks')); + }); + + test('Promise', () async { + final result = await engine.eval( + const JsCode.code(''' + new Promise((resolve) => { + resolve(42); + }) + '''), + options: JsEvalOptions.withPromise(), + ); + print('DEBUG Promise: result = $result'); + print('DEBUG Promise: result.runtimeType = ${result.runtimeType}'); + expect(result.value, equals(42)); + }); + + test('async/await', () async { + final result = await engine.eval( + const JsCode.code(''' + (async () => { + const delay = (ms) => new Promise(r => setTimeout(r, ms)); + await delay(10); + return "done"; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals('done')); + }); + + test('Map and Set', () async { + final mapResult = await engine.eval( + const JsCode.code(''' + const m = new Map(); + m.set("key", "value"); + m.get("key") + '''), + ); + expect(mapResult.value, equals('value')); + + final setResult = await engine.eval( + const JsCode.code(''' + const s = new Set([1, 2, 3, 2, 1]); + s.size + '''), + ); + expect(setResult.value, equals(3)); + }); + + test('Symbol', () async { + final result = await engine.eval( + const JsCode.code(''' + const sym = Symbol("mySymbol"); + typeof sym + '''), + ); + expect(result.value, equals('symbol')); + }); + + test('Proxy', () async { + final result = await engine.eval( + const JsCode.code(''' + const target = { message: "hello" }; + const handler = { + get: (obj, prop) => prop === "message" ? obj[prop].toUpperCase() : obj[prop] + }; + const proxy = new Proxy(target, handler); + proxy.message + '''), + ); + expect(result.value, equals('HELLO')); + }); + + test('Generator', () async { + final result = await engine.eval( + const JsCode.code(''' + function* gen() { + yield 1; + yield 2; + yield 3; + } + [...gen()] + '''), + ); + expect(result.value, equals([1, 2, 3])); + }); + + test('Default parameters', () async { + final result = await engine.eval( + const JsCode.code(''' + function greet(name = "World") { + return "Hello, " + name; + } + greet() + '''), + ); + expect(result.value, equals('Hello, World')); + }); + + test('Rest parameters', () async { + final result = await engine.eval( + const JsCode.code(''' + function sum(...numbers) { + return numbers.reduce((a, b) => a + b, 0); + } + sum(1, 2, 3, 4, 5) + '''), + ); + expect(result.value, equals(15)); + }); + + test('Optional chaining operator', () async { + final result = await engine.eval( + const JsCode.code(''' + const objChain = { a: { b: { c: 42 } } }; + objChain?.a?.b?.c + '''), + ); + expect(result.value, equals(42)); + + final nullResult = await engine.eval( + const JsCode.code(''' + const objNull = { a: null }; + objNull?.a?.b?.c ?? "default" + '''), + ); + expect(nullResult.value, equals('default')); + }); + + test('Nullish coalescing operator', () async { + final result = await engine.eval( + const JsCode.code(''' + const value = null ?? "default"; + value + '''), + ); + expect(result.value, equals('default')); + }); + + test('BigInt', () async { + final result = await engine.eval( + const JsCode.code(''' + const big = 9007199254740991n + 1n; + big.toString() + '''), + ); + expect(result.value, equals('9007199254740992')); + }); + }); + + group('Builtin Modules Tests', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + await engine.init(); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('console module', () async { + // console.log returns nothing, but should not throw + final result = await engine.eval( + const JsCode.code('console.log("test"); "logged"'), + ); + expect(result.value, equals('logged')); + }); + + test('URL parsing', () async { + final result = await engine.eval( + const JsCode.code(''' + const url = new URL("https://example.com:8080/path?query=value#hash"); + ({ + protocol: url.protocol, + hostname: url.hostname, + port: url.port, + pathname: url.pathname, + search: url.search, + hash: url.hash + }) + '''), + ); + print('DEBUG URL: result = $result'); + print('DEBUG URL: result.value = ${result.value}'); + expect(result.isObject(), true); + final obj = result.value as Map; + expect(obj['protocol'], equals('https:')); + expect(obj['hostname'], equals('example.com')); + expect(obj['port'], equals('8080')); + expect(obj['pathname'], equals('/path')); + expect(obj['search'], equals('?query=value')); + expect(obj['hash'], equals('#hash')); + }); + + test('URLSearchParams', () async { + final result = await engine.eval( + const JsCode.code(''' + const params = new URLSearchParams("a=1&b=2&c=3"); + params.get("b") + '''), + ); + expect(result.value, equals('2')); + }); + + test('TextEncoder/TextDecoder', () async { + final result = await engine.eval( + const JsCode.code(''' + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const encoded = encoder.encode("Hello"); + decoder.decode(encoded) + '''), + ); + expect(result.value, equals('Hello')); + }); + + test('atob/btoa', () async { + final encodeResult = await engine.eval( + const JsCode.code('btoa("Hello, World!")'), + ); + expect(encodeResult.value, equals('SGVsbG8sIFdvcmxkIQ==')); + + final decodeResult = await engine.eval( + const JsCode.code('atob("SGVsbG8sIFdvcmxkIQ==")'), + ); + expect(decodeResult.value, equals('Hello, World!')); + }); + }); + + group('Performance and Stability Tests', () { + test('Heavy computation', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + final engine = JsEngine(context); + await engine.init(); + + final result = await engine.eval( + const JsCode.code(''' + let sum = 0; + for (let i = 0; i < 10000; i++) { + sum += i; + } + sum + '''), + ); + expect(result.value, equals(49995000)); + + await engine.dispose(); + }); + + test('Large array processing', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + final engine = JsEngine(context); + await engine.init(); + + final result = await engine.eval( + const JsCode.code(''' + const arr = Array.from({length: 1000}, (_, i) => i); + arr.reduce((a, b) => a + b, 0) + '''), + ); + expect(result.value, equals(499500)); + + await engine.dispose(); + }); + + test('Multiple evaluations', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + final engine = JsEngine(context); + await engine.init(); + + for (int i = 0; i < 100; i++) { + final result = await engine.eval(JsCode.code('$i * 2')); + expect(result.value, equals(i * 2)); + } + + await engine.dispose(); + }); + + test('Multiple engine instances', () async { + final engines = []; + + for (int i = 0; i < 5; i++) { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + final engine = JsEngine(context); + await engine.init(); + engines.add(engine); + } + + // Parallel evaluation + final results = await Future.wait( + engines.asMap().entries.map((e) async { + return await e.value.eval(JsCode.code('${e.key} + 100')); + }), + ); + + for (int i = 0; i < 5; i++) { + expect(results[i].value, equals(i + 100)); + } + + // Cleanup + for (final engine in engines) { + await engine.dispose(); + } + }); + }); + + group('Promise and Async Edge Cases', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + await engine.init(); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Nested Promise', () async { + final result = await engine.eval( + const JsCode.code(''' + new Promise((resolve) => { + resolve(new Promise((resolve2) => { + resolve2(42); + })); + }) + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals(42)); + }); + + test('Triple nested Promise', () async { + final result = await engine.eval( + const JsCode.code(''' + new Promise((resolve) => { + resolve(new Promise((resolve2) => { + resolve2(new Promise((resolve3) => { + resolve3("deep"); + })); + })); + }) + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals("deep")); + }); + + test('Promise.resolve', () async { + final result = await engine.eval( + const JsCode.code('Promise.resolve(123)'), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals(123)); + }); + + test('Promise.resolve with object', () async { + final result = await engine.eval( + const JsCode.code('Promise.resolve({a: 1, b: 2})'), + options: JsEvalOptions.withPromise(), + ); + // Result may be wrapped or direct object + final value = result.value; + expect(value, isA()); + final obj = value as Map; + expect(obj['a'], equals(1)); + expect(obj['b'], equals(2)); + }); + + test('Async function returning object', () async { + final result = await engine.eval( + const JsCode.code(''' + (async () => { + return {x: 10, y: 20}; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + final value = result.value; + expect(value, isA()); + final obj = value as Map; + expect(obj['x'], equals(10)); + expect(obj['y'], equals(20)); + }); + + test('Async function with await chain', () async { + final result = await engine.eval( + const JsCode.code(''' + (async () => { + const a = await Promise.resolve(1); + const b = await Promise.resolve(2); + const c = await Promise.resolve(3); + return a + b + c; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals(6)); + }); + + test('Promise with setTimeout', () async { + final result = await engine.eval( + const JsCode.code(''' + new Promise((resolve) => { + setTimeout(() => resolve("delayed"), 10); + }) + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals("delayed")); + }); + + test('Promise.all', () async { + final result = await engine.eval( + const JsCode.code(''' + Promise.all([ + Promise.resolve(1), + Promise.resolve(2), + Promise.resolve(3) + ]) + '''), + options: JsEvalOptions.withPromise(), + ); + final arr = result.value; + expect(arr, isA()); + expect(arr, equals([1, 2, 3])); + }); + + test('Promise.race', () async { + final result = await engine.eval( + const JsCode.code(''' + Promise.race([ + Promise.resolve("first"), + new Promise(r => setTimeout(() => r("second"), 100)) + ]) + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals("first")); + }); + + test('Async generator simulation', () async { + final result = await engine.eval( + const JsCode.code(''' + (async () => { + const results = []; + for (let i = 0; i < 3; i++) { + results.push(await Promise.resolve(i * 10)); + } + return results; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + final arr = result.value; + expect(arr, isA()); + expect(arr, equals([0, 10, 20])); + }); + }); + + group('Edge Cases and Boundary Tests', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + await engine.init(); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Empty string', () async { + final result = await engine.eval(const JsCode.code('""')); + expect(result.value, equals('')); + }); + + test('Unicode string', () async { + final result = await engine.eval( + const JsCode.code('"Hello 世界 🌍 مرحبا"'), + ); + expect(result.value, equals('Hello 世界 🌍 مرحبا')); + }); + + test('Very long string', () async { + final result = await engine.eval( + const JsCode.code('"a".repeat(10000).length'), + ); + expect(result.value, equals(10000)); + }); + + test('Zero and negative zero', () async { + final zero = await engine.eval(const JsCode.code('0')); + expect(zero.value, equals(0)); + + final negZero = await engine.eval(const JsCode.code('-0')); + expect(negZero.value, equals(0)); + }); + + test('Infinity values', () async { + final inf = await engine.eval(const JsCode.code('Infinity')); + expect(inf.value, equals(double.infinity)); + + final negInf = await engine.eval(const JsCode.code('-Infinity')); + expect(negInf.value, equals(double.negativeInfinity)); + }); + + test('NaN handling', () async { + final result = await engine.eval(const JsCode.code('NaN')); + expect((result.value as double).isNaN, true); + }); + + test('Large integer', () async { + final result = await engine.eval( + const JsCode.code('9007199254740991'), // Number.MAX_SAFE_INTEGER + ); + expect(result.value, equals(9007199254740991)); + }); + + test('Small integer', () async { + final result = await engine.eval( + const JsCode.code('-9007199254740991'), // Number.MIN_SAFE_INTEGER + ); + expect(result.value, equals(-9007199254740991)); + }); + + test('Empty array', () async { + final result = await engine.eval(const JsCode.code('[]')); + expect(result.isArray(), true); + expect(result.value, equals([])); + }); + + test('Empty object', () async { + final result = await engine.eval(const JsCode.code('({})')); + expect(result.isObject(), true); + expect(result.value, equals({})); + }); + + test('Null value', () async { + final result = await engine.eval(const JsCode.code('null')); + expect(result.isNone(), true); + expect(result.value, isNull); + }); + + test('Undefined value', () async { + final result = await engine.eval(const JsCode.code('undefined')); + expect(result.isNone(), true); + }); + + test('Boolean false', () async { + final result = await engine.eval(const JsCode.code('false')); + expect(result.isBoolean(), true); + expect(result.value, false); + }); + + test('Deeply nested object', () async { + final result = await engine.eval( + const JsCode.code('({a: {b: {c: {d: {e: "deep"}}}}})'), + ); + expect(result.isObject(), true); + final obj = result.value as Map; + expect((((obj['a'] as Map)['b'] as Map)['c'] as Map)['d']['e'], + equals("deep")); + }); + + test('Array with mixed types', () async { + final result = await engine.eval( + const JsCode.code('[1, "two", true, null, {a: 1}, [1, 2]]'), + ); + expect(result.isArray(), true); + final arr = result.value as List; + expect(arr[0], equals(1)); + expect(arr[1], equals("two")); + expect(arr[2], equals(true)); + expect(arr[3], isNull); + expect((arr[4] as Map)['a'], equals(1)); + expect(arr[5], equals([1, 2])); + }); + + test('Object with special keys', () async { + final result = await engine.eval( + const JsCode.code('({"key with spaces": 1, "123": 2, "": 3})'), + ); + expect(result.isObject(), true); + final obj = result.value as Map; + expect(obj['key with spaces'], equals(1)); + expect(obj['123'], equals(2)); + expect(obj[''], equals(3)); + }); + + test('Circular reference handling', () async { + // This should not cause infinite loop + final result = await engine.eval( + const JsCode.code(''' + const obj = {a: 1}; + obj.self = obj; + obj.a + '''), + ); + expect(result.value, equals(1)); + }); + + test('Date object', () async { + final result = await engine.eval( + const JsCode.code('new Date(1609459200000).getTime()'), + ); + expect(result.value, equals(1609459200000)); + }); + + test('RegExp test', () async { + final result = await engine.eval( + const JsCode.code('/hello/.test("hello world")'), + ); + expect(result.value, equals(true)); + }); + + test('typeof operator', () async { + final results = await Future.wait([ + engine.eval(const JsCode.code('typeof 42')), + engine.eval(const JsCode.code('typeof "hello"')), + engine.eval(const JsCode.code('typeof true')), + engine.eval(const JsCode.code('typeof undefined')), + engine.eval(const JsCode.code('typeof null')), + engine.eval(const JsCode.code('typeof {}')), + engine.eval(const JsCode.code('typeof []')), + engine.eval(const JsCode.code('typeof (() => {})')), + ]); + + expect(results[0].value, equals('number')); + expect(results[1].value, equals('string')); + expect(results[2].value, equals('boolean')); + expect(results[3].value, equals('undefined')); + expect(results[4].value, equals('object')); + expect(results[5].value, equals('object')); + expect(results[6].value, equals('object')); + expect(results[7].value, equals('function')); + }); + }); + + group('Error Handling Edge Cases', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + await engine.init(); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Try-catch in JS', () async { + final result = await engine.eval( + const JsCode.code(''' + try { + throw new Error("test error"); + } catch (e) { + "caught: " + e.message + } + '''), + ); + expect(result.value, equals("caught: test error")); + }); + + test('Promise rejection handling in JS', () async { + final result = await engine.eval( + const JsCode.code(''' + (async () => { + try { + await Promise.reject("rejected"); + } catch (e) { + return "handled: " + e; + } + })() + '''), + options: JsEvalOptions.withPromise(), + ); + expect(result.value, equals("handled: rejected")); + }); + + test('TypeError in JS', () async { + expect( + () => engine.eval(const JsCode.code('null.property')), + throwsA(isA()), + ); + }); + + test('ReferenceError in JS', () async { + expect( + () => engine.eval(const JsCode.code('nonExistentVariable')), + throwsA(isA()), + ); + }); + + test('SyntaxError in JS', () async { + expect( + () => engine.eval(const JsCode.code('function {')), + throwsA(isA()), + ); + }); + + test('RangeError in JS', () async { + expect( + () => engine.eval(const JsCode.code('new Array(-1)')), + throwsA(isA()), + ); + }); + }); + + group('Bridge Call Edge Cases', () { + late JsAsyncRuntime runtime; + late JsAsyncContext context; + late JsEngine engine; + + setUp(() async { + runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.all(), + ); + context = await JsAsyncContext.from(rt: runtime); + engine = JsEngine(context); + }); + + tearDown(() async { + if (!engine.disposed) { + await engine.dispose(); + } + }); + + test('Bridge call with null', () async { + dynamic received; + await engine.init( + bridgeCall: (value) async { + received = value.value; + return const JsValue.string('ok'); + }, + ); + + await engine.eval( + const JsCode.code('await fjs.bridge_call(null)'), + options: JsEvalOptions.withPromise(), + ); + expect(received, isNull); + }); + + test('Bridge call with undefined', () async { + dynamic received; + await engine.init( + bridgeCall: (value) async { + received = value; + return const JsValue.string('ok'); + }, + ); + + await engine.eval( + const JsCode.code('await fjs.bridge_call(undefined)'), + options: JsEvalOptions.withPromise(), + ); + expect(received.isNone(), true); + }); + + test('Bridge call with large object', () async { + dynamic received; + await engine.init( + bridgeCall: (value) async { + received = value.value; + return const JsValue.boolean(true); + }, + ); + + await engine.eval( + const JsCode.code(''' + const obj = {}; + for (let i = 0; i < 100; i++) { + obj["key" + i] = i; + } + await fjs.bridge_call(obj) + '''), + options: JsEvalOptions.withPromise(), + ); + expect(received, isA()); + expect((received as Map).length, equals(100)); + }); + + test('Bridge call with array', () async { + dynamic received; + await engine.init( + bridgeCall: (value) async { + received = value.value; + return const JsValue.boolean(true); + }, + ); + + await engine.eval( + const JsCode.code('await fjs.bridge_call([1, 2, 3, 4, 5])'), + options: JsEvalOptions.withPromise(), + ); + expect(received, equals([1, 2, 3, 4, 5])); + }); + + test('Multiple bridge calls', () async { + int callCount = 0; + await engine.init( + bridgeCall: (value) async { + callCount++; + return JsValue.integer(callCount); + }, + ); + + final result = await engine.eval( + const JsCode.code(''' + (async () => { + const a = await fjs.bridge_call(1); + const b = await fjs.bridge_call(2); + const c = await fjs.bridge_call(3); + return a + b + c; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + expect(callCount, equals(3)); + expect(result.value, equals(6)); // 1 + 2 + 3 + }); + + test('Bridge call returning different types', () async { + int callIndex = 0; + final returns = [ + const JsValue.integer(42), + const JsValue.string("hello"), + const JsValue.boolean(true), + const JsValue.array([JsValue.integer(1), JsValue.integer(2)]), + ]; + + await engine.init( + bridgeCall: (value) async { + return returns[callIndex++]; + }, + ); + + final results = await engine.eval( + const JsCode.code(''' + (async () => { + const a = await fjs.bridge_call(0); + const b = await fjs.bridge_call(1); + const c = await fjs.bridge_call(2); + const d = await fjs.bridge_call(3); + return [a, b, c, d]; + })() + '''), + options: JsEvalOptions.withPromise(), + ); + expect(results.isArray(), true); + final arr = results.value as List; + expect(arr[0], equals(42)); + expect(arr[1], equals("hello")); + expect(arr[2], equals(true)); + expect(arr[3], equals([1, 2])); + }); + }); + + group('Memory and Resource Tests', () { + test('Memory limit enforcement', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + + // Set a small memory limit + await runtime.setMemoryLimit(limit: BigInt.from(1024 * 1024)); // 1MB + + final engine = JsEngine(context); + await engine.init(); + + // This should work with small data + final smallResult = await engine.eval( + const JsCode.code('const arr = [1, 2, 3]; arr.length'), + ); + expect(smallResult.value, equals(3)); + + await engine.dispose(); + }); + + test('Garbage collection', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + final context = await JsAsyncContext.from(rt: runtime); + final engine = JsEngine(context); + await engine.init(); + + // Create and discard objects + for (int i = 0; i < 100; i++) { + await engine.eval( + JsCode.code('const obj$i = { data: new Array(100).fill($i) };'), + ); + } + + // Force GC + await runtime.runGc(); + + // Engine should still work + final result = await engine.eval(const JsCode.code('1 + 1')); + expect(result.value, equals(2)); + + await engine.dispose(); + }); + + test('Context isolation', () async { + final runtime = await JsAsyncRuntime.withOptions( + builtin: JsBuiltinOptions.essential(), + ); + + final context1 = await JsAsyncContext.from(rt: runtime); + final context2 = await JsAsyncContext.from(rt: runtime); + + final engine1 = JsEngine(context1); + final engine2 = JsEngine(context2); + + await engine1.init(); + await engine2.init(); + + // Set variable in engine1 + await engine1.eval(const JsCode.code('globalThis.testVar = "engine1"')); + + // Should not be visible in engine2 + final result = await engine2.eval( + const JsCode.code('typeof globalThis.testVar'), + ); + expect(result.value, equals('undefined')); + + await engine1.dispose(); + await engine2.dispose(); + }); }); } diff --git a/example/pubspec.lock b/example/pubspec.lock index 677e0fd..644e420 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -143,7 +143,7 @@ packages: path: ".." relative: true source: path - version: "1.3.0" + version: "1.4.0" flutter: dependency: "direct main" description: flutter diff --git a/libfjs/src/api/runtime.rs b/libfjs/src/api/runtime.rs index 8da9041..1c4240c 100644 --- a/libfjs/src/api/runtime.rs +++ b/libfjs/src/api/runtime.rs @@ -601,13 +601,49 @@ pub(crate) async fn result_from_promise<'js>( res: rquickjs::Result>, ) -> JsResult { match res.catch(ctx) { - Ok(promise) => match promise.into_future::().await.catch(ctx) { - Ok(v) => match JsValue::from_js(ctx, v).catch(ctx) { + Ok(promise) => { + let mut value = match promise.into_future::().await.catch(ctx) { + Ok(v) => v, + Err(e) => return JsResult::Err(JsError::runtime(e.to_string())), + }; + + // JS_EVAL_FLAG_ASYNC wraps result in {value: xxx} + // Detect wrapper: object with exactly one property named "value" + if let Some(obj) = value.as_object() { + if let Ok(keys) = obj.keys::().collect::, _>>() { + if keys.len() == 1 && keys[0] == "value" { + // This is the QuickJS wrapper, extract the inner value + if let Ok(inner) = obj.get::<_, rquickjs::Value>("value") { + value = inner; + } + } + } + } + + // Handle nested promises + while value.is_promise() { + value = match value.as_promise().unwrap().clone().into_future::().await.catch(ctx) { + Ok(v) => v, + Err(e) => return JsResult::Err(JsError::runtime(e.to_string())), + }; + // Unwrap wrapper again if needed + if let Some(obj) = value.as_object() { + if let Ok(keys) = obj.keys::().collect::, _>>() { + if keys.len() == 1 && keys[0] == "value" { + if let Ok(inner) = obj.get::<_, rquickjs::Value>("value") { + value = inner; + } + } + } + } + } + + match JsValue::from_js(ctx, value).catch(ctx) { Ok(v) => JsResult::Ok(v), Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - }, - Err(e) => JsResult::Err(JsError::runtime(e.to_string())), - }, + } + } Err(e) => JsResult::Err(JsError::runtime(e.to_string())), } } + diff --git a/pubspec.yaml b/pubspec.yaml index ff42f54..ce6eb3c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: fjs description: "A high-performance JavaScript runtime for Flutter applications, built with Rust and powered by QuickJS." -version: 1.3.1 +version: 1.4.0 homepage: https://github.com/fluttercandies/fjs repository: https://github.com/fluttercandies/fjs issue_tracker: https://github.com/fluttercandies/fjs/issues