mirror of
https://github.com/foss42/apidash.git
synced 2025-07-03 14:36:22 +08:00
Merge branch 'main' into add-feature-scripts
This commit is contained in:
@ -105,7 +105,7 @@ API Dash can be downloaded from the links below:
|
||||
| Insomnia | ✅ |
|
||||
| OpenAPI | https://github.com/foss42/apidash/issues/121 |
|
||||
| hurl | https://github.com/foss42/apidash/issues/123 |
|
||||
| HAR | https://github.com/foss42/apidash/issues/122 |
|
||||
| HAR | ✅ |
|
||||
|
||||
|
||||
**↗️ Create & Customize API Requests**
|
||||
|
@ -144,7 +144,8 @@ enum CodegenLanguage {
|
||||
enum ImportFormat {
|
||||
curl("cURL"),
|
||||
postman("Postman Collection v2.1"),
|
||||
insomnia("Insomnia v4");
|
||||
insomnia("Insomnia v4"),
|
||||
har("Har v1.2");
|
||||
|
||||
const ImportFormat(this.label);
|
||||
final String label;
|
||||
|
2
lib/dashbot/consts.dart
Normal file
2
lib/dashbot/consts.dart
Normal file
@ -0,0 +1,2 @@
|
||||
const kModel = 'llama3.2:3b';
|
||||
const kOllamaEndpoint = 'http://127.0.0.1:11434/api';
|
@ -1,6 +1,6 @@
|
||||
import 'dart:convert';
|
||||
import '../services/dashbot_service.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class DebugFeature {
|
||||
final DashBotService _service;
|
||||
|
66
lib/dashbot/features/documentation.dart
Normal file
66
lib/dashbot/features/documentation.dart
Normal file
@ -0,0 +1,66 @@
|
||||
import 'dart:convert';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class DocumentationFeature {
|
||||
final DashBotService _service;
|
||||
|
||||
DocumentationFeature(this._service);
|
||||
|
||||
Future<String> generateApiDocumentation({
|
||||
required RequestModel? requestModel,
|
||||
required dynamic responseModel,
|
||||
}) async {
|
||||
if (requestModel == null || responseModel == null) {
|
||||
return "No recent API requests found.";
|
||||
}
|
||||
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final headers = requestModel.httpRequestModel?.enabledHeadersMap ?? {};
|
||||
final parameters = requestModel.httpRequestModel?.enabledParamsMap ?? {};
|
||||
final body = requestModel.httpRequestModel?.body;
|
||||
final rawResponse = responseModel.body;
|
||||
final responseBody =
|
||||
rawResponse is String ? rawResponse : jsonEncode(rawResponse);
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
final prompt = """
|
||||
API DOCUMENTATION GENERATION
|
||||
|
||||
**API Details:**
|
||||
- Endpoint: $endpoint
|
||||
- Method: $method
|
||||
- Status Code: $statusCode
|
||||
|
||||
**Request Components:**
|
||||
- Headers: ${headers.isNotEmpty ? jsonEncode(headers) : "None"}
|
||||
- Query Parameters: ${parameters.isNotEmpty ? jsonEncode(parameters) : "None"}
|
||||
- Request Body: ${body != null && body.isNotEmpty ? body : "None"}
|
||||
|
||||
**Response Example:**
|
||||
```
|
||||
$responseBody
|
||||
```
|
||||
|
||||
**Documentation Instructions:**
|
||||
Create comprehensive API documentation that includes:
|
||||
|
||||
1. **Overview**: A clear, concise description of what this API endpoint does
|
||||
2. **Authentication**: Required authentication method based on headers
|
||||
3. **Request Details**: All required and optional parameters with descriptions
|
||||
4. **Response Structure**: Breakdown of response fields and their meanings
|
||||
5. **Error Handling**: Possible error codes and troubleshooting
|
||||
6. **Example Usage**: A complete code example showing how to call this API
|
||||
|
||||
Format in clean markdown with proper sections and code blocks where appropriate.
|
||||
""";
|
||||
|
||||
return _service.generateResponse(prompt);
|
||||
}
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
import '../services/dashbot_service.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class ExplainFeature {
|
||||
final DashBotService _service;
|
||||
|
5
lib/dashbot/features/features.dart
Normal file
5
lib/dashbot/features/features.dart
Normal file
@ -0,0 +1,5 @@
|
||||
export 'debug.dart';
|
||||
export 'documentation.dart';
|
||||
export 'explain.dart';
|
||||
export 'general_query.dart';
|
||||
export 'test_generator.dart';
|
54
lib/dashbot/features/general_query.dart
Normal file
54
lib/dashbot/features/general_query.dart
Normal file
@ -0,0 +1,54 @@
|
||||
import 'package:ollama_dart/ollama_dart.dart';
|
||||
import '../../models/models.dart';
|
||||
import '../consts.dart';
|
||||
|
||||
class GeneralQueryFeature {
|
||||
final OllamaClient _client;
|
||||
|
||||
GeneralQueryFeature(this._client);
|
||||
|
||||
Future<String> generateResponse(String prompt,
|
||||
{RequestModel? requestModel, dynamic responseModel}) async {
|
||||
String enhancedPrompt = prompt;
|
||||
|
||||
if (requestModel != null && responseModel != null) {
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
enhancedPrompt = '''
|
||||
CONTEXT-AWARE RESPONSE
|
||||
|
||||
**User Question:**
|
||||
$prompt
|
||||
|
||||
**Related API Context:**
|
||||
- Endpoint: $endpoint
|
||||
- Method: $method
|
||||
- Status Code: $statusCode
|
||||
|
||||
**Instructions:**
|
||||
1. Directly address the user's specific question
|
||||
2. Provide relevant, concise information
|
||||
3. Reference the API context when helpful
|
||||
4. Focus on practical, actionable insights
|
||||
5. Avoid generic explanations or documentation
|
||||
|
||||
Respond in a helpful, direct manner that specifically answers what was asked.
|
||||
''';
|
||||
}
|
||||
|
||||
final response = await _client.generateCompletion(
|
||||
request: GenerateCompletionRequest(
|
||||
model: kModel,
|
||||
prompt: enhancedPrompt,
|
||||
),
|
||||
);
|
||||
return response.response.toString();
|
||||
}
|
||||
}
|
94
lib/dashbot/features/test_generator.dart
Normal file
94
lib/dashbot/features/test_generator.dart
Normal file
@ -0,0 +1,94 @@
|
||||
import 'dart:convert';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class TestGeneratorFeature {
|
||||
final DashBotService _service;
|
||||
|
||||
TestGeneratorFeature(this._service);
|
||||
|
||||
Future<String> generateApiTests({
|
||||
required RequestModel? requestModel,
|
||||
required dynamic responseModel,
|
||||
}) async {
|
||||
if (requestModel == null || responseModel == null) {
|
||||
return "No recent API requests found.";
|
||||
}
|
||||
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final rawResponse = responseModel.body;
|
||||
final responseBody =
|
||||
rawResponse is String ? rawResponse : jsonEncode(rawResponse);
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
Uri uri = Uri.parse(endpoint);
|
||||
final baseUrl = "${uri.scheme}://${uri.host}";
|
||||
final path = uri.path;
|
||||
|
||||
final parameterAnalysis = _analyzeParameters(uri.queryParameters);
|
||||
|
||||
final prompt = """
|
||||
EXECUTABLE API TEST CASES GENERATOR
|
||||
|
||||
**API Analysis:**
|
||||
- Base URL: $baseUrl
|
||||
- Endpoint: $path
|
||||
- Method: $method
|
||||
- Current Parameters: ${uri.queryParameters}
|
||||
- Current Response: $responseBody (Status: $statusCode)
|
||||
- Parameter Types: $parameterAnalysis
|
||||
|
||||
**Test Generation Task:**
|
||||
Generate practical, ready-to-use test cases for this API in cURL format. Each test should be executable immediately.
|
||||
|
||||
Include these test categories:
|
||||
1. **Valid Cases**: Different valid parameter values (use real-world examples like other country codes if this is a country API)
|
||||
2. **Invalid Parameter Tests**: Missing parameters, empty values, incorrect formats
|
||||
3. **Edge Cases**: Special characters, long values, unexpected inputs
|
||||
4. **Validation Tests**: Test input validation and error handling
|
||||
|
||||
For each test case:
|
||||
1. Provide a brief description of what the test verifies
|
||||
2. Include a complete, executable cURL command
|
||||
3. Show the expected outcome (status code and sample response)
|
||||
4. Organize tests in a way that's easy to copy and run
|
||||
|
||||
Focus on creating realistic test values based on the API context (e.g., for a country flag API, use real country codes, invalid codes, etc.)
|
||||
""";
|
||||
|
||||
final testCases = await _service.generateResponse(prompt);
|
||||
return "TEST_CASES_HIDDEN\n$testCases";
|
||||
}
|
||||
|
||||
String _analyzeParameters(Map<String, String> parameters) {
|
||||
if (parameters.isEmpty) {
|
||||
return "No parameters detected";
|
||||
}
|
||||
|
||||
Map<String, String> analysis = {};
|
||||
|
||||
parameters.forEach((key, value) {
|
||||
if (RegExp(r'^[A-Z]{3}$').hasMatch(value)) {
|
||||
analysis[key] =
|
||||
"Appears to be a 3-letter country code (ISO 3166-1 alpha-3)";
|
||||
} else if (RegExp(r'^[A-Z]{2}$').hasMatch(value)) {
|
||||
analysis[key] =
|
||||
"Appears to be a 2-letter country code (ISO 3166-1 alpha-2)";
|
||||
} else if (RegExp(r'^\d+$').hasMatch(value)) {
|
||||
analysis[key] = "Numeric value";
|
||||
} else if (RegExp(r'^[a-zA-Z]+$').hasMatch(value)) {
|
||||
analysis[key] = "Alphabetic string";
|
||||
} else {
|
||||
analysis[key] = "Unknown format: $value";
|
||||
}
|
||||
});
|
||||
|
||||
return jsonEncode(analysis);
|
||||
}
|
||||
}
|
@ -1,7 +1,11 @@
|
||||
import 'dart:convert';
|
||||
import 'package:apidash/services/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../services/dashbot_service.dart';
|
||||
import '../services/services.dart';
|
||||
|
||||
final dashBotMinimizedProvider = StateProvider<bool>((ref) {
|
||||
return true;
|
||||
});
|
||||
|
||||
final chatMessagesProvider =
|
||||
StateNotifierProvider<ChatMessagesNotifier, List<Map<String, dynamic>>>(
|
||||
@ -17,19 +21,16 @@ class ChatMessagesNotifier extends StateNotifier<List<Map<String, dynamic>>> {
|
||||
_loadMessages();
|
||||
}
|
||||
|
||||
static const _storageKey = 'chatMessages';
|
||||
|
||||
Future<void> _loadMessages() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final messages = prefs.getString(_storageKey);
|
||||
final messages = await hiveHandler.getDashbotMessages();
|
||||
if (messages != null) {
|
||||
state = List<Map<String, dynamic>>.from(json.decode(messages));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _saveMessages() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_storageKey, json.encode(state));
|
||||
final messages = json.encode(state);
|
||||
await hiveHandler.saveDashbotMessages(messages);
|
||||
}
|
||||
|
||||
void addMessage(Map<String, dynamic> message) {
|
||||
|
@ -1,36 +1,61 @@
|
||||
import 'package:apidash/dashbot/features/debug.dart';
|
||||
import 'package:ollama_dart/ollama_dart.dart';
|
||||
import '../features/explain.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../consts.dart';
|
||||
import '../features/features.dart';
|
||||
|
||||
class DashBotService {
|
||||
final OllamaClient _client;
|
||||
late final ExplainFeature _explainFeature;
|
||||
late final DebugFeature _debugFeature;
|
||||
late final DocumentationFeature _documentationFeature;
|
||||
late final TestGeneratorFeature _testGeneratorFeature;
|
||||
final GeneralQueryFeature _generalQueryFeature;
|
||||
|
||||
DashBotService()
|
||||
: _client = OllamaClient(baseUrl: 'http://127.0.0.1:11434/api') {
|
||||
: _client = OllamaClient(baseUrl: kOllamaEndpoint),
|
||||
_generalQueryFeature =
|
||||
GeneralQueryFeature(OllamaClient(baseUrl: kOllamaEndpoint)) {
|
||||
_explainFeature = ExplainFeature(this);
|
||||
_debugFeature = DebugFeature(this);
|
||||
_documentationFeature = DocumentationFeature(this);
|
||||
_testGeneratorFeature = TestGeneratorFeature(this);
|
||||
}
|
||||
|
||||
Future<String> generateResponse(String prompt) async {
|
||||
final response = await _client.generateCompletion(
|
||||
request: GenerateCompletionRequest(model: 'llama3.2:3b', prompt: prompt),
|
||||
);
|
||||
return response.response.toString();
|
||||
return _generalQueryFeature.generateResponse(prompt);
|
||||
}
|
||||
|
||||
Future<String> handleRequest(
|
||||
String input, RequestModel? requestModel, dynamic responseModel) async {
|
||||
String input,
|
||||
RequestModel? requestModel,
|
||||
dynamic responseModel,
|
||||
) async {
|
||||
if (input == "Explain API") {
|
||||
return _explainFeature.explainLatestApi(
|
||||
requestModel: requestModel, responseModel: responseModel);
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Debug API") {
|
||||
return _debugFeature.debugApi(
|
||||
requestModel: requestModel, responseModel: responseModel);
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Document API") {
|
||||
return _documentationFeature.generateApiDocumentation(
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Test API") {
|
||||
return _testGeneratorFeature.generateApiTests(
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
}
|
||||
|
||||
return generateResponse(input);
|
||||
return _generalQueryFeature.generateResponse(
|
||||
input,
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
1
lib/dashbot/services/services.dart
Normal file
1
lib/dashbot/services/services.dart
Normal file
@ -0,0 +1 @@
|
||||
export 'dashbot_service.dart';
|
@ -7,7 +7,11 @@ class ChatBubble extends StatelessWidget {
|
||||
final String message;
|
||||
final bool isUser;
|
||||
|
||||
const ChatBubble({super.key, required this.message, this.isUser = false});
|
||||
const ChatBubble({
|
||||
super.key,
|
||||
required this.message,
|
||||
this.isUser = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
|
@ -5,12 +5,18 @@ import 'package:flutter_highlight/flutter_highlight.dart';
|
||||
import 'package:flutter_highlight/themes/monokai-sublime.dart';
|
||||
import 'package:flutter_markdown/flutter_markdown.dart';
|
||||
|
||||
Widget renderContent(BuildContext context, String text) {
|
||||
Widget renderContent(
|
||||
BuildContext context,
|
||||
String text,
|
||||
) {
|
||||
if (text.isEmpty) {
|
||||
return const Text("No content to display.");
|
||||
}
|
||||
|
||||
final codeBlockPattern = RegExp(r'```(\w+)?\n([\s\S]*?)```', multiLine: true);
|
||||
final codeBlockPattern = RegExp(
|
||||
r'```(\w+)?\n([\s\S]*?)```',
|
||||
multiLine: true,
|
||||
);
|
||||
final matches = codeBlockPattern.allMatches(text);
|
||||
|
||||
if (matches.isEmpty) {
|
||||
@ -22,8 +28,10 @@ Widget renderContent(BuildContext context, String text) {
|
||||
|
||||
for (var match in matches) {
|
||||
if (match.start > lastEnd) {
|
||||
children
|
||||
.add(_renderMarkdown(context, text.substring(lastEnd, match.start)));
|
||||
children.add(_renderMarkdown(
|
||||
context,
|
||||
text.substring(lastEnd, match.start),
|
||||
));
|
||||
}
|
||||
|
||||
final language = match.group(1) ?? 'text';
|
||||
@ -43,7 +51,10 @@ Widget renderContent(BuildContext context, String text) {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderMarkdown(BuildContext context, String markdown) {
|
||||
Widget _renderMarkdown(
|
||||
BuildContext context,
|
||||
String markdown,
|
||||
) {
|
||||
return MarkdownBody(
|
||||
data: markdown,
|
||||
selectable: true,
|
||||
@ -53,7 +64,11 @@ Widget _renderMarkdown(BuildContext context, String markdown) {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
Widget _renderCodeBlock(
|
||||
BuildContext context,
|
||||
String language,
|
||||
String code,
|
||||
) {
|
||||
if (language == 'json') {
|
||||
try {
|
||||
final prettyJson =
|
||||
@ -63,7 +78,10 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
color: Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
child: SelectableText(
|
||||
prettyJson,
|
||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||||
style: const TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
@ -78,7 +96,10 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
code,
|
||||
language: language,
|
||||
theme: monokaiSublimeTheme,
|
||||
textStyle: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||||
textStyle: const TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
@ -87,14 +108,20 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
}
|
||||
}
|
||||
|
||||
Widget _renderFallbackCode(BuildContext context, String code) {
|
||||
Widget _renderFallbackCode(
|
||||
BuildContext context,
|
||||
String code,
|
||||
) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
color: Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
child: SelectableText(
|
||||
code,
|
||||
style: const TextStyle(
|
||||
fontFamily: 'monospace', fontSize: 12, color: Colors.red),
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
// lib/dashbot/widgets/dashbot_widget.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:apidash/dashbot/providers/dashbot_providers.dart';
|
||||
import 'package:apidash/providers/providers.dart';
|
||||
import 'test_runner_widget.dart';
|
||||
import 'chat_bubble.dart';
|
||||
|
||||
class DashBotWidget extends ConsumerStatefulWidget {
|
||||
@ -48,10 +48,21 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
try {
|
||||
final response = await dashBotService.handleRequest(
|
||||
message, requestModel, responseModel);
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message': response,
|
||||
});
|
||||
if (response.startsWith("TEST_CASES_HIDDEN\n")) {
|
||||
final testCases = response.replaceFirst("TEST_CASES_HIDDEN\n", "");
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message':
|
||||
"Test cases generated successfully. Click the button below to run them.",
|
||||
'testCases': testCases,
|
||||
'showTestButton': true,
|
||||
});
|
||||
} else {
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message': response,
|
||||
});
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
debugPrint('Error in _sendMessage: $error');
|
||||
debugPrint('StackTrace: $stackTrace');
|
||||
@ -63,7 +74,7 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
setState(() => _isLoading = false);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_scrollController.animateTo(
|
||||
0,
|
||||
_scrollController.position.minScrollExtent,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
@ -71,111 +82,225 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
void _showTestRunner(String testCases) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => Dialog(
|
||||
child: SizedBox(
|
||||
width: MediaQuery.of(context).size.width * 0.8,
|
||||
height: 500,
|
||||
child: TestRunnerWidget(testCases: testCases),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final messages = ref.watch(chatMessagesProvider);
|
||||
final requestModel = ref.read(selectedRequestModelProvider);
|
||||
final statusCode = requestModel?.httpResponseModel?.statusCode;
|
||||
final showDebugButton = statusCode != null && statusCode >= 400;
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
|
||||
return Container(
|
||||
height: 450,
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: const [
|
||||
BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, 4))
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
child: isMinimized
|
||||
? _buildMinimizedView(context)
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 12),
|
||||
_buildQuickActions(showDebugButton),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(child: _buildChatArea(messages)),
|
||||
if (_isLoading) _buildLoadingIndicator(),
|
||||
const SizedBox(height: 10),
|
||||
_buildInputArea(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 12),
|
||||
_buildQuickActions(showDebugButton),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(child: _buildChatArea(messages)),
|
||||
if (_isLoading) _buildLoadingIndicator(),
|
||||
const SizedBox(height: 10),
|
||||
_buildInputArea(context),
|
||||
const Text(
|
||||
'DashBot',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: Icon(
|
||||
isMinimized ? Icons.fullscreen : Icons.remove,
|
||||
size: 20,
|
||||
),
|
||||
tooltip: isMinimized ? 'Maximize' : 'Minimize',
|
||||
onPressed: () {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state =
|
||||
!isMinimized;
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.close, size: 20),
|
||||
tooltip: 'Close',
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.delete_sweep, size: 20),
|
||||
tooltip: 'Clear Chat',
|
||||
onPressed: () {
|
||||
ref.read(chatMessagesProvider.notifier).clearMessages();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
Widget _buildMinimizedView(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('DashBot',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_sweep),
|
||||
tooltip: 'Clear Chat',
|
||||
onPressed: () =>
|
||||
ref.read(chatMessagesProvider.notifier).clearMessages(),
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: _buildInputArea(context),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQuickActions(bool showDebugButton) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Explain API"),
|
||||
icon: const Icon(Icons.info_outline),
|
||||
label: const Text("Explain"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
),
|
||||
),
|
||||
if (showDebugButton)
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Debug API"),
|
||||
icon: const Icon(Icons.bug_report_outlined),
|
||||
label: const Text("Debug"),
|
||||
onPressed: () => _sendMessage("Explain API"),
|
||||
icon: const Icon(Icons.info_outline, size: 16),
|
||||
label: const Text("Explain"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (showDebugButton)
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Debug API"),
|
||||
icon: const Icon(Icons.bug_report_outlined, size: 16),
|
||||
label: const Text("Debug"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Document API"),
|
||||
icon: const Icon(Icons.description_outlined, size: 16),
|
||||
label: const Text("Document"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Test API"),
|
||||
icon: const Icon(Icons.science_outlined, size: 16),
|
||||
label: const Text("Test"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChatArea(List<Map<String, dynamic>> messages) {
|
||||
return ListView.builder(
|
||||
controller: _scrollController,
|
||||
reverse: true,
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages.reversed.toList()[index];
|
||||
return ChatBubble(
|
||||
message: message['message'],
|
||||
isUser: message['role'] == 'user',
|
||||
);
|
||||
},
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
reverse: true,
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages.reversed.toList()[index];
|
||||
final isBot = message['role'] == 'bot';
|
||||
final text = message['message'] as String;
|
||||
final showTestButton = message['showTestButton'] == true;
|
||||
final testCases = message['testCases'] as String?;
|
||||
|
||||
if (isBot && showTestButton && testCases != null) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ChatBubble(message: text, isUser: false),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 12, top: 4, bottom: 4),
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () => _showTestRunner(testCases),
|
||||
icon: const Icon(Icons.play_arrow, size: 16),
|
||||
label: const Text("Run Test Cases"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ChatBubble(
|
||||
message: text,
|
||||
isUser: message['role'] == 'user',
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoadingIndicator() {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: LinearProgressIndicator(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInputArea(BuildContext context) {
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: Theme.of(context).colorScheme.surfaceContainer,
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
@ -184,14 +309,29 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Ask DashBot...',
|
||||
border: InputBorder.none,
|
||||
contentPadding: EdgeInsets.symmetric(vertical: 8),
|
||||
),
|
||||
onSubmitted: _sendMessage,
|
||||
onSubmitted: (value) {
|
||||
_sendMessage(value);
|
||||
_controller.clear();
|
||||
if (isMinimized) {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state = false;
|
||||
}
|
||||
},
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send),
|
||||
onPressed: () => _sendMessage(_controller.text),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
icon: const Icon(Icons.send, size: 20),
|
||||
onPressed: () {
|
||||
_sendMessage(_controller.text);
|
||||
_controller.clear();
|
||||
if (isMinimized) {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state = false;
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
|
327
lib/dashbot/widgets/test_runner_widget.dart
Normal file
327
lib/dashbot/widgets/test_runner_widget.dart
Normal file
@ -0,0 +1,327 @@
|
||||
import 'dart:convert';
|
||||
import 'package:apidash_core/apidash_core.dart' as http;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'content_renderer.dart';
|
||||
|
||||
class TestRunnerWidget extends ConsumerStatefulWidget {
|
||||
final String testCases;
|
||||
|
||||
const TestRunnerWidget({
|
||||
super.key,
|
||||
required this.testCases,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<TestRunnerWidget> createState() => _TestRunnerWidgetState();
|
||||
}
|
||||
|
||||
class _TestRunnerWidgetState extends ConsumerState<TestRunnerWidget> {
|
||||
List<Map<String, dynamic>> _parsedTests = [];
|
||||
Map<int, Map<String, dynamic>> _results = {};
|
||||
bool _isRunning = false;
|
||||
int _currentTestIndex = -1;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_parseTestCases();
|
||||
}
|
||||
|
||||
void _parseTestCases() {
|
||||
final curlRegex = RegExp(r'```bash\ncurl\s+(.*?)\n```', dotAll: true);
|
||||
final descriptionRegex = RegExp(r'###\s*(.*?)\n', dotAll: true);
|
||||
|
||||
final curlMatches = curlRegex.allMatches(widget.testCases);
|
||||
final descMatches = descriptionRegex.allMatches(widget.testCases);
|
||||
|
||||
List<Map<String, dynamic>> tests = [];
|
||||
int index = 0;
|
||||
|
||||
for (var match in curlMatches) {
|
||||
String? description = "Test case ${index + 1}";
|
||||
if (index < descMatches.length) {
|
||||
description = descMatches.elementAt(index).group(1)?.trim();
|
||||
}
|
||||
|
||||
final curlCommand = match.group(1)?.trim() ?? "";
|
||||
|
||||
tests.add({
|
||||
'description': description,
|
||||
'command': curlCommand,
|
||||
'index': index,
|
||||
});
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_parsedTests = tests;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _runTest(int index) async {
|
||||
if (_isRunning) return;
|
||||
|
||||
setState(() {
|
||||
_isRunning = true;
|
||||
_currentTestIndex = index;
|
||||
});
|
||||
|
||||
final test = _parsedTests[index];
|
||||
final command = test['command'];
|
||||
|
||||
try {
|
||||
final urlMatch = RegExp(r'"([^"]*)"').firstMatch(command) ??
|
||||
RegExp(r"'([^']*)'").firstMatch(command);
|
||||
final url = urlMatch?.group(1) ?? "";
|
||||
if (url.isEmpty) throw Exception("Could not parse URL from curl command");
|
||||
|
||||
String method = "GET";
|
||||
if (command.contains("-X POST") || command.contains("--request POST")) {
|
||||
method = "POST";
|
||||
} else if (command.contains("-X PUT") ||
|
||||
command.contains("--request PUT")) {
|
||||
method = "PUT";
|
||||
}
|
||||
|
||||
http.Response response;
|
||||
if (method == "GET") {
|
||||
response = await http.get(Uri.parse(url));
|
||||
} else if (method == "POST") {
|
||||
final bodyMatch = RegExp(r'-d\s+"([^"]*)"').firstMatch(command);
|
||||
final body = bodyMatch?.group(1) ?? "";
|
||||
response = await http.post(Uri.parse(url), body: body);
|
||||
} else {
|
||||
throw Exception("Unsupported HTTP method: $method");
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_results[index] = {
|
||||
'status': response.statusCode,
|
||||
'body': response.body,
|
||||
'headers': response.headers,
|
||||
'isSuccess': response.statusCode >= 200 && response.statusCode < 300,
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_results[index] = {
|
||||
'error': e.toString(),
|
||||
'isSuccess': false,
|
||||
};
|
||||
});
|
||||
} finally {
|
||||
setState(() {
|
||||
_isRunning = false;
|
||||
_currentTestIndex = -1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runAllTests() async {
|
||||
for (int i = 0; i < _parsedTests.length; i++) {
|
||||
if (!mounted) return;
|
||||
await _runTest(i);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('API Test Runner'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.help_outline),
|
||||
tooltip: 'How to use',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('API Test Runner'),
|
||||
content: const Text(
|
||||
'Run generated API tests:\n\n'
|
||||
'• "Run All" executes all tests\n'
|
||||
'• "Run" executes a single test\n'
|
||||
'• "Copy" copies the curl command',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: _parsedTests.isEmpty
|
||||
? const Center(child: Text("No test cases found"))
|
||||
: _buildTestList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_buildActionButtons(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTestList() {
|
||||
return ListView.builder(
|
||||
itemCount: _parsedTests.length,
|
||||
itemBuilder: (context, index) {
|
||||
final test = _parsedTests[index];
|
||||
final result = _results[index];
|
||||
final bool hasResult = result != null;
|
||||
final bool isSuccess = hasResult && (result['isSuccess'] ?? false);
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
test['description'] ?? "Test case ${index + 1}",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color:
|
||||
hasResult ? (isSuccess ? Colors.green : Colors.red) : null,
|
||||
),
|
||||
),
|
||||
subtitle: Text('Test ${index + 1} of ${_parsedTests.length}'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy),
|
||||
tooltip: 'Copy command',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: test['command']));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Command copied')),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (_currentTestIndex == index && _isRunning)
|
||||
const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
icon: Icon(hasResult
|
||||
? (isSuccess ? Icons.check_circle : Icons.error)
|
||||
: Icons.play_arrow),
|
||||
color: hasResult
|
||||
? (isSuccess ? Colors.green : Colors.red)
|
||||
: null,
|
||||
tooltip: hasResult ? 'Run again' : 'Run test',
|
||||
onPressed: () => _runTest(index),
|
||||
),
|
||||
],
|
||||
),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Command:',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(top: 4, bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
width: double.infinity,
|
||||
child: SelectableText(
|
||||
test['command'],
|
||||
style: const TextStyle(fontFamily: 'monospace'),
|
||||
),
|
||||
),
|
||||
if (hasResult) ...[
|
||||
const Divider(),
|
||||
Text(
|
||||
'Result:',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isSuccess ? Colors.green : Colors.red,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (result.containsKey('error'))
|
||||
Text(
|
||||
'Error: ${result['error']}',
|
||||
style: const TextStyle(color: Colors.red),
|
||||
)
|
||||
else ...[
|
||||
Text('Status: ${result['status']}'),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Response:',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(top: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
width: double.infinity,
|
||||
child: renderContent(
|
||||
context, _tryFormatJson(result['body'])),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActionButtons() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: _isRunning ? null : _runAllTests,
|
||||
icon: const Icon(Icons.play_circle_outline),
|
||||
label: const Text("Run All Tests"),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _tryFormatJson(dynamic input) {
|
||||
if (input == null) return "null";
|
||||
if (input is! String) return input.toString();
|
||||
try {
|
||||
final decoded = json.decode(input);
|
||||
return JsonEncoder.withIndent(' ').convert(decoded);
|
||||
} catch (_) {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
}
|
@ -13,6 +13,7 @@ class Importer {
|
||||
.toList(),
|
||||
ImportFormat.postman => PostmanIO().getHttpRequestModelList(content),
|
||||
ImportFormat.insomnia => InsomniaIO().getHttpRequestModelList(content),
|
||||
ImportFormat.har => HarParserIO().getHttpRequestModelList(content),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,8 @@ class Dashboard extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final railIdx = ref.watch(navRailIndexStateProvider);
|
||||
final settings = ref.watch(settingsProvider);
|
||||
final isDashBotEnabled =
|
||||
ref.watch(settingsProvider.select((value) => value.isDashBotEnabled));
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Row(
|
||||
@ -126,7 +127,7 @@ class Dashboard extends ConsumerWidget {
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: settings.isDashBotEnabled
|
||||
floatingActionButton: isDashBotEnabled
|
||||
? FloatingActionButton(
|
||||
onPressed: () => showModalBottomSheet(
|
||||
context: context,
|
||||
|
@ -1,6 +1,8 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
|
||||
enum HiveBoxType { normal, lazy }
|
||||
|
||||
const String kDataBox = "apidash-data";
|
||||
const String kKeyDataBoxIds = "ids";
|
||||
|
||||
@ -11,6 +13,17 @@ const String kHistoryMetaBox = "apidash-history-meta";
|
||||
const String kHistoryBoxIds = "historyIds";
|
||||
const String kHistoryLazyBox = "apidash-history-lazy";
|
||||
|
||||
const String kDashBotBox = "apidash-dashbot-data";
|
||||
const String kKeyDashBotBoxIds = 'messages';
|
||||
|
||||
const kHiveBoxes = [
|
||||
(kDataBox, HiveBoxType.normal),
|
||||
(kEnvironmentBox, HiveBoxType.normal),
|
||||
(kHistoryMetaBox, HiveBoxType.normal),
|
||||
(kHistoryLazyBox, HiveBoxType.lazy),
|
||||
(kDashBotBox, HiveBoxType.lazy),
|
||||
];
|
||||
|
||||
Future<bool> initHiveBoxes(
|
||||
bool initializeUsingPath,
|
||||
String? workspaceFolderPath,
|
||||
@ -34,10 +47,13 @@ Future<bool> initHiveBoxes(
|
||||
|
||||
Future<bool> openHiveBoxes() async {
|
||||
try {
|
||||
await Hive.openBox(kDataBox);
|
||||
await Hive.openBox(kEnvironmentBox);
|
||||
await Hive.openBox(kHistoryMetaBox);
|
||||
await Hive.openLazyBox(kHistoryLazyBox);
|
||||
for (var box in kHiveBoxes) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.openBox(box.$1);
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.openLazyBox(box.$1);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR OPEN HIVE BOXES: $e");
|
||||
@ -47,17 +63,14 @@ Future<bool> openHiveBoxes() async {
|
||||
|
||||
Future<void> clearHiveBoxes() async {
|
||||
try {
|
||||
if (Hive.isBoxOpen(kDataBox)) {
|
||||
await Hive.box(kDataBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kEnvironmentBox)) {
|
||||
await Hive.box(kEnvironmentBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryMetaBox)) {
|
||||
await Hive.box(kHistoryMetaBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryLazyBox)) {
|
||||
await Hive.lazyBox(kHistoryLazyBox).clear();
|
||||
for (var box in kHiveBoxes) {
|
||||
if (Hive.isBoxOpen(box.$1)) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.box(box.$1).clear();
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.lazyBox(box.$1).clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("ERROR CLEAR HIVE BOXES: $e");
|
||||
@ -66,17 +79,14 @@ Future<void> clearHiveBoxes() async {
|
||||
|
||||
Future<void> deleteHiveBoxes() async {
|
||||
try {
|
||||
if (Hive.isBoxOpen(kDataBox)) {
|
||||
await Hive.box(kDataBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kEnvironmentBox)) {
|
||||
await Hive.box(kEnvironmentBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryMetaBox)) {
|
||||
await Hive.box(kHistoryMetaBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryLazyBox)) {
|
||||
await Hive.lazyBox(kHistoryLazyBox).deleteFromDisk();
|
||||
for (var box in kHiveBoxes) {
|
||||
if (Hive.isBoxOpen(box.$1)) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.box(box.$1).deleteFromDisk();
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.lazyBox(box.$1).deleteFromDisk();
|
||||
}
|
||||
}
|
||||
}
|
||||
await Hive.close();
|
||||
} catch (e) {
|
||||
@ -91,6 +101,7 @@ class HiveHandler {
|
||||
late final Box environmentBox;
|
||||
late final Box historyMetaBox;
|
||||
late final LazyBox historyLazyBox;
|
||||
late final LazyBox dashBotBox;
|
||||
|
||||
HiveHandler() {
|
||||
debugPrint("Trying to open Hive boxes");
|
||||
@ -98,6 +109,7 @@ class HiveHandler {
|
||||
environmentBox = Hive.box(kEnvironmentBox);
|
||||
historyMetaBox = Hive.box(kHistoryMetaBox);
|
||||
historyLazyBox = Hive.lazyBox(kHistoryLazyBox);
|
||||
dashBotBox = Hive.lazyBox(kDashBotBox);
|
||||
}
|
||||
|
||||
dynamic getIds() => dataBox.get(kKeyDataBoxIds);
|
||||
@ -135,11 +147,16 @@ class HiveHandler {
|
||||
Future<dynamic> getHistoryRequest(String id) async =>
|
||||
await historyLazyBox.get(id);
|
||||
Future<void> setHistoryRequest(
|
||||
String id, Map<String, dynamic>? historyRequestJsoon) =>
|
||||
historyLazyBox.put(id, historyRequestJsoon);
|
||||
String id, Map<String, dynamic>? historyRequestJson) =>
|
||||
historyLazyBox.put(id, historyRequestJson);
|
||||
|
||||
Future<void> deleteHistoryRequest(String id) => historyLazyBox.delete(id);
|
||||
|
||||
Future<dynamic> getDashbotMessages() async =>
|
||||
await dashBotBox.get(kKeyDashBotBoxIds);
|
||||
Future<void> saveDashbotMessages(String messages) =>
|
||||
dashBotBox.put(kKeyDashBotBoxIds, messages);
|
||||
|
||||
Future clearAllHistory() async {
|
||||
await historyMetaBox.clear();
|
||||
await historyLazyBox.clear();
|
||||
@ -150,6 +167,7 @@ class HiveHandler {
|
||||
await environmentBox.clear();
|
||||
await historyMetaBox.clear();
|
||||
await historyLazyBox.clear();
|
||||
await dashBotBox.clear();
|
||||
}
|
||||
|
||||
Future<void> removeUnused() async {
|
||||
|
135
packages/apidash_core/lib/import_export/har_io.dart
Normal file
135
packages/apidash_core/lib/import_export/har_io.dart
Normal file
@ -0,0 +1,135 @@
|
||||
import 'package:har/har.dart' as har;
|
||||
import 'package:seed/seed.dart';
|
||||
import '../consts.dart';
|
||||
import '../models/models.dart';
|
||||
import '../utils/utils.dart';
|
||||
|
||||
class HarParserIO {
|
||||
List<(String?, HttpRequestModel)>? getHttpRequestModelList(String content) {
|
||||
content = content.trim();
|
||||
try {
|
||||
final hl = har.harLogFromJsonStr(content);
|
||||
final requests = har.getRequestsFromHarLog(hl);
|
||||
return requests
|
||||
.map((req) => (req.$2.url, harRequestToHttpRequestModel(req.$2)))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
HttpRequestModel harRequestToHttpRequestModel(har.Request request) {
|
||||
HTTPVerb method;
|
||||
|
||||
try {
|
||||
method = HTTPVerb.values.byName((request.method ?? "").toLowerCase());
|
||||
} catch (e) {
|
||||
method = kDefaultHttpMethod;
|
||||
}
|
||||
String url = stripUrlParams(request.url ?? "");
|
||||
List<NameValueModel> headers = [];
|
||||
List<bool> isHeaderEnabledList = [];
|
||||
|
||||
List<NameValueModel> params = [];
|
||||
List<bool> isParamEnabledList = [];
|
||||
|
||||
for (var header in request.headers ?? <har.Header>[]) {
|
||||
var name = header.name ?? "";
|
||||
var value = header.value;
|
||||
var activeHeader = header.disabled ?? false;
|
||||
headers.add(NameValueModel(name: name, value: value));
|
||||
isHeaderEnabledList.add(!activeHeader);
|
||||
}
|
||||
|
||||
for (var query in request.queryString ?? <har.Query>[]) {
|
||||
var name = query.name ?? "";
|
||||
var value = query.value;
|
||||
var activeQuery = query.disabled ?? false;
|
||||
params.add(NameValueModel(name: name, value: value));
|
||||
isParamEnabledList.add(!activeQuery);
|
||||
}
|
||||
|
||||
ContentType bodyContentType = kDefaultContentType;
|
||||
String? body;
|
||||
List<FormDataModel>? formData = [];
|
||||
|
||||
if (request.postData?.mimeType == "application/json") {
|
||||
bodyContentType = ContentType.json;
|
||||
body = request.postData?.text;
|
||||
}
|
||||
FormDataType formDataType = FormDataType.text;
|
||||
if (request.postData?.mimeType == "application/x-www-form-urlencoded") {
|
||||
bodyContentType = ContentType.formdata;
|
||||
var formDataStr = request.postData?.text;
|
||||
Map<String, String> parsedData = parseFormData(formDataStr);
|
||||
parsedData.forEach((key, value) {
|
||||
formDataType = FormDataType.text;
|
||||
var name = key;
|
||||
var val = value;
|
||||
formData.add(FormDataModel(
|
||||
name: name,
|
||||
value: val,
|
||||
type: formDataType,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
if (request.postData?.mimeType == "multipart/form-data") {
|
||||
bodyContentType = ContentType.formdata;
|
||||
String? name, val;
|
||||
for (var fd in request.postData?.params ?? <har.Param>[]) {
|
||||
name = fd.name;
|
||||
if (fd.contentType == "text/plain") {
|
||||
formDataType = FormDataType.text;
|
||||
val = fd.value;
|
||||
} else {
|
||||
formDataType = FormDataType.file;
|
||||
val = fd.fileName;
|
||||
}
|
||||
formData.add(FormDataModel(
|
||||
name: name ?? "",
|
||||
value: val ?? "",
|
||||
type: formDataType,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return HttpRequestModel(
|
||||
method: method,
|
||||
url: url,
|
||||
headers: headers,
|
||||
params: params,
|
||||
isHeaderEnabledList: isHeaderEnabledList,
|
||||
isParamEnabledList: isParamEnabledList,
|
||||
body: body,
|
||||
bodyContentType: bodyContentType,
|
||||
formData: formData);
|
||||
}
|
||||
|
||||
Map<String, String> parseFormData(String? data) {
|
||||
// Return an empty map if the input is null or empty
|
||||
if (data == null || data.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
// Split the input string into individual key-value pairs
|
||||
var pairs = data.split('&');
|
||||
|
||||
// Create a Map to store key-value pairs
|
||||
Map<String, String> result = {};
|
||||
|
||||
// Loop through the pairs and split them into keys and values
|
||||
for (var pair in pairs) {
|
||||
var keyValue = pair.split('=');
|
||||
|
||||
// Ensure the pair contains both key and value
|
||||
if (keyValue.length == 2) {
|
||||
var key = Uri.decodeComponent(keyValue[0]);
|
||||
var value = Uri.decodeComponent(keyValue[1]);
|
||||
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
export 'curl_io.dart';
|
||||
export 'postman_io.dart';
|
||||
export 'insomnia_io.dart';
|
||||
export 'har_io.dart';
|
||||
|
@ -22,6 +22,8 @@ dependencies:
|
||||
json5: ^0.8.2
|
||||
postman:
|
||||
path: ../postman
|
||||
har:
|
||||
path: ../har
|
||||
seed: ^0.0.3
|
||||
xml: ^6.3.0
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
# melos_managed_dependency_overrides: curl_parser,insomnia_collection,postman,seed
|
||||
# melos_managed_dependency_overrides: curl_parser,insomnia_collection,postman,seed,har
|
||||
dependency_overrides:
|
||||
curl_parser:
|
||||
path: ../curl_parser
|
||||
har:
|
||||
path: ../har
|
||||
insomnia_collection:
|
||||
path: ../insomnia_collection
|
||||
postman:
|
||||
|
32
packages/har/.gitignore
vendored
Normal file
32
packages/har/.gitignore
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
build/
|
||||
coverage/
|
3
packages/har/CHANGELOG.md
Normal file
3
packages/har/CHANGELOG.md
Normal file
@ -0,0 +1,3 @@
|
||||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
201
packages/har/LICENSE
Normal file
201
packages/har/LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Ashita Prasad, Ankit Mahato
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
340
packages/har/README.md
Normal file
340
packages/har/README.md
Normal file
@ -0,0 +1,340 @@
|
||||
# har
|
||||
|
||||
Seamlessly convert Har Collection Format v1.2 to Dart.
|
||||
|
||||
Helps you bring your APIs stored in Har to Dart and work with them.
|
||||
|
||||
Currently, this package is being used by [API Dash](https://github.com/foss42/apidash), a beautiful open-source cross-platform (macOS, Windows, Linux, Android & iOS) API Client built using Flutter which can help you easily create & customize your API requests, visually inspect responses and generate API integration code. A lightweight alternative to postman.
|
||||
|
||||
## Usage
|
||||
|
||||
### Example 1: Har collection JSON string to Har model
|
||||
|
||||
```dart
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
// Example 1: Har collection JSON string to Har model
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
var collection = harLogFromJsonStr(collectionJsonStr);
|
||||
|
||||
print(collection.log?.creator);
|
||||
print(collection.log?.entries?[0].startedDateTime);
|
||||
print(collection.log?.entries?[0].request?.url);
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: Har collection from JSON
|
||||
|
||||
```dart
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
// Example 2: Har collection from JSON
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
var collection1 = HarLog.fromJson(collectionJson);
|
||||
print(collection1.log?.creator?.name);
|
||||
print(collection1.log?.entries?[0].startedDateTime);
|
||||
print(collection1.log?.entries?[0].request?.url);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## Maintainer
|
||||
|
||||
- Ashita Prasad ([GitHub](https://github.com/ashitaprasad), [LinkedIn](https://www.linkedin.com/in/ashitaprasad/), [X](https://x.com/ashitaprasad))
|
||||
- Mohammed Ayaan (contributor) ([GitHub](https://github.com/ayaan-md-blr))
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [Apache License 2.0](https://github.com/foss42/apidash/blob/main/packages/har/LICENSE).
|
6
packages/har/analysis_options.yaml
Normal file
6
packages/har/analysis_options.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
analyzer:
|
||||
exclude:
|
||||
- "**/*.g.dart"
|
||||
- "**/*.freezed.dart"
|
||||
errors:
|
||||
invalid_annotation_target: ignore
|
312
packages/har/example/har_example.dart
Normal file
312
packages/har/example/har_example.dart
Normal file
@ -0,0 +1,312 @@
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
//Example 1
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {
|
||||
"name": "Client Name",
|
||||
"version": "v8.x.x"
|
||||
},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "code",
|
||||
"value": "US"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{ "name": "num", "value": "8700000" },
|
||||
{ "name": "digits", "value": "3" },
|
||||
{ "name": "system", "value": "SS" },
|
||||
{ "name": "add_space", "value": "true" },
|
||||
{ "name": "trailing_zeros", "value": "true" }
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{
|
||||
"name": "User-Agent",
|
||||
"value": "Test Agent"
|
||||
}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{ "name": "text", "value": "API", "contentType":"text/plain" },
|
||||
{ "name": "sep", "value": "|", "contentType":"text/plain" },
|
||||
{ "name": "times", "value": "3", "contentType":"text/plain" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
,
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{ "name": "token", "value": "xyz", "contentType":"text/plain" },
|
||||
{ "name": "imfile", "fileName": "hire AI.jpeg", "contentType":"image/jpeg" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
var collection = harLogFromJsonStr(collectionJsonStr);
|
||||
|
||||
print(collection.log?.creator);
|
||||
print(collection.log?.entries?[0].startedDateTime);
|
||||
print(collection.log?.entries?[0].request?.url);
|
||||
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
var collection1 = HarLog.fromJson(collectionJson);
|
||||
print(collection1.log?.creator?.name);
|
||||
print(collection1.log?.entries?[0].startedDateTime);
|
||||
print(collection1.log?.entries?[0].request?.url);
|
||||
}
|
4
packages/har/lib/har.dart
Normal file
4
packages/har/lib/har.dart
Normal file
@ -0,0 +1,4 @@
|
||||
library har;
|
||||
|
||||
export 'models/models.dart';
|
||||
export 'utils/har_utils.dart';
|
174
packages/har/lib/models/har_log.dart
Normal file
174
packages/har/lib/models/har_log.dart
Normal file
@ -0,0 +1,174 @@
|
||||
import 'dart:convert';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'har_log.freezed.dart';
|
||||
part 'har_log.g.dart';
|
||||
|
||||
HarLog harLogFromJsonStr(String str) => HarLog.fromJson(json.decode(str));
|
||||
|
||||
String harLogToJsonStr(HarLog data) =>
|
||||
JsonEncoder.withIndent(' ').convert(data);
|
||||
|
||||
@freezed
|
||||
class HarLog with _$HarLog {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory HarLog({
|
||||
Log? log,
|
||||
}) = _HarLog;
|
||||
|
||||
factory HarLog.fromJson(Map<String, dynamic> json) => _$HarLogFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Log with _$Log {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Log({
|
||||
String? version,
|
||||
Creator? creator,
|
||||
List<Entry>? entries,
|
||||
}) = _Log;
|
||||
|
||||
factory Log.fromJson(Map<String, dynamic> json) => _$LogFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Creator with _$Creator {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Creator({
|
||||
String? name,
|
||||
String? version,
|
||||
}) = _Creator;
|
||||
|
||||
factory Creator.fromJson(Map<String, dynamic> json) =>
|
||||
_$CreatorFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Entry with _$Entry {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Entry({
|
||||
String? startedDateTime,
|
||||
int? time,
|
||||
Request? request,
|
||||
Response? response,
|
||||
}) = _Entry;
|
||||
|
||||
factory Entry.fromJson(Map<String, dynamic> json) => _$EntryFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Request with _$Request {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Request({
|
||||
String? method,
|
||||
String? url,
|
||||
String? httpVersion,
|
||||
List<dynamic>? cookies,
|
||||
List<Header>? headers,
|
||||
List<Query>? queryString,
|
||||
PostData? postData,
|
||||
int? headersSize,
|
||||
int? bodySize,
|
||||
}) = _Request;
|
||||
|
||||
factory Request.fromJson(Map<String, dynamic> json) =>
|
||||
_$RequestFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class PostData with _$PostData {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory PostData({
|
||||
String? mimeType,
|
||||
String? text,
|
||||
List<Param>? params, // for multipart/form-data params
|
||||
}) = _PostData;
|
||||
|
||||
factory PostData.fromJson(Map<String, dynamic> json) =>
|
||||
_$PostDataFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Param with _$Param {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Param({
|
||||
String? name,
|
||||
String? value,
|
||||
String? fileName,
|
||||
String? contentType,
|
||||
bool? disabled,
|
||||
}) = _Param;
|
||||
|
||||
factory Param.fromJson(Map<String, dynamic> json) => _$ParamFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Query with _$Query {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Query({
|
||||
String? name,
|
||||
String? value,
|
||||
bool? disabled,
|
||||
}) = _Query;
|
||||
|
||||
factory Query.fromJson(Map<String, dynamic> json) => _$QueryFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Header with _$Header {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Header({
|
||||
String? name,
|
||||
String? value,
|
||||
bool? disabled,
|
||||
}) = _Header;
|
||||
|
||||
factory Header.fromJson(Map<String, dynamic> json) => _$HeaderFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Response with _$Response {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Response({
|
||||
int? status,
|
||||
String? statusText,
|
||||
String? httpVersion,
|
||||
List<dynamic>? cookies,
|
||||
List<dynamic>? headers,
|
||||
Content? content,
|
||||
String? redirectURL,
|
||||
int? headersSize,
|
||||
int? bodySize,
|
||||
}) = _Response;
|
||||
|
||||
factory Response.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResponseFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Content with _$Content {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Content({
|
||||
int? size,
|
||||
String? mimeType,
|
||||
}) = _Content;
|
||||
|
||||
factory Content.fromJson(Map<String, dynamic> json) =>
|
||||
_$ContentFromJson(json);
|
||||
}
|
2482
packages/har/lib/models/har_log.freezed.dart
Normal file
2482
packages/har/lib/models/har_log.freezed.dart
Normal file
File diff suppressed because it is too large
Load Diff
198
packages/har/lib/models/har_log.g.dart
Normal file
198
packages/har/lib/models/har_log.g.dart
Normal file
@ -0,0 +1,198 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'har_log.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_$HarLogImpl _$$HarLogImplFromJson(Map json) => _$HarLogImpl(
|
||||
log: json['log'] == null
|
||||
? null
|
||||
: Log.fromJson(Map<String, dynamic>.from(json['log'] as Map)),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$HarLogImplToJson(_$HarLogImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.log?.toJson() case final value?) 'log': value,
|
||||
};
|
||||
|
||||
_$LogImpl _$$LogImplFromJson(Map json) => _$LogImpl(
|
||||
version: json['version'] as String?,
|
||||
creator: json['creator'] == null
|
||||
? null
|
||||
: Creator.fromJson(Map<String, dynamic>.from(json['creator'] as Map)),
|
||||
entries: (json['entries'] as List<dynamic>?)
|
||||
?.map((e) => Entry.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$LogImplToJson(_$LogImpl instance) => <String, dynamic>{
|
||||
if (instance.version case final value?) 'version': value,
|
||||
if (instance.creator?.toJson() case final value?) 'creator': value,
|
||||
if (instance.entries?.map((e) => e.toJson()).toList() case final value?)
|
||||
'entries': value,
|
||||
};
|
||||
|
||||
_$CreatorImpl _$$CreatorImplFromJson(Map json) => _$CreatorImpl(
|
||||
name: json['name'] as String?,
|
||||
version: json['version'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$CreatorImplToJson(_$CreatorImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.version case final value?) 'version': value,
|
||||
};
|
||||
|
||||
_$EntryImpl _$$EntryImplFromJson(Map json) => _$EntryImpl(
|
||||
startedDateTime: json['startedDateTime'] as String?,
|
||||
time: (json['time'] as num?)?.toInt(),
|
||||
request: json['request'] == null
|
||||
? null
|
||||
: Request.fromJson(Map<String, dynamic>.from(json['request'] as Map)),
|
||||
response: json['response'] == null
|
||||
? null
|
||||
: Response.fromJson(
|
||||
Map<String, dynamic>.from(json['response'] as Map)),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$EntryImplToJson(_$EntryImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.startedDateTime case final value?) 'startedDateTime': value,
|
||||
if (instance.time case final value?) 'time': value,
|
||||
if (instance.request?.toJson() case final value?) 'request': value,
|
||||
if (instance.response?.toJson() case final value?) 'response': value,
|
||||
};
|
||||
|
||||
_$RequestImpl _$$RequestImplFromJson(Map json) => _$RequestImpl(
|
||||
method: json['method'] as String?,
|
||||
url: json['url'] as String?,
|
||||
httpVersion: json['httpVersion'] as String?,
|
||||
cookies: json['cookies'] as List<dynamic>?,
|
||||
headers: (json['headers'] as List<dynamic>?)
|
||||
?.map((e) => Header.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
queryString: (json['queryString'] as List<dynamic>?)
|
||||
?.map((e) => Query.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
postData: json['postData'] == null
|
||||
? null
|
||||
: PostData.fromJson(
|
||||
Map<String, dynamic>.from(json['postData'] as Map)),
|
||||
headersSize: (json['headersSize'] as num?)?.toInt(),
|
||||
bodySize: (json['bodySize'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$RequestImplToJson(_$RequestImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.method case final value?) 'method': value,
|
||||
if (instance.url case final value?) 'url': value,
|
||||
if (instance.httpVersion case final value?) 'httpVersion': value,
|
||||
if (instance.cookies case final value?) 'cookies': value,
|
||||
if (instance.headers?.map((e) => e.toJson()).toList() case final value?)
|
||||
'headers': value,
|
||||
if (instance.queryString?.map((e) => e.toJson()).toList()
|
||||
case final value?)
|
||||
'queryString': value,
|
||||
if (instance.postData?.toJson() case final value?) 'postData': value,
|
||||
if (instance.headersSize case final value?) 'headersSize': value,
|
||||
if (instance.bodySize case final value?) 'bodySize': value,
|
||||
};
|
||||
|
||||
_$PostDataImpl _$$PostDataImplFromJson(Map json) => _$PostDataImpl(
|
||||
mimeType: json['mimeType'] as String?,
|
||||
text: json['text'] as String?,
|
||||
params: (json['params'] as List<dynamic>?)
|
||||
?.map((e) => Param.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$PostDataImplToJson(_$PostDataImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.mimeType case final value?) 'mimeType': value,
|
||||
if (instance.text case final value?) 'text': value,
|
||||
if (instance.params?.map((e) => e.toJson()).toList() case final value?)
|
||||
'params': value,
|
||||
};
|
||||
|
||||
_$ParamImpl _$$ParamImplFromJson(Map json) => _$ParamImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
fileName: json['fileName'] as String?,
|
||||
contentType: json['contentType'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ParamImplToJson(_$ParamImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.fileName case final value?) 'fileName': value,
|
||||
if (instance.contentType case final value?) 'contentType': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$QueryImpl _$$QueryImplFromJson(Map json) => _$QueryImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$QueryImplToJson(_$QueryImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$HeaderImpl _$$HeaderImplFromJson(Map json) => _$HeaderImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$HeaderImplToJson(_$HeaderImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$ResponseImpl _$$ResponseImplFromJson(Map json) => _$ResponseImpl(
|
||||
status: (json['status'] as num?)?.toInt(),
|
||||
statusText: json['statusText'] as String?,
|
||||
httpVersion: json['httpVersion'] as String?,
|
||||
cookies: json['cookies'] as List<dynamic>?,
|
||||
headers: json['headers'] as List<dynamic>?,
|
||||
content: json['content'] == null
|
||||
? null
|
||||
: Content.fromJson(Map<String, dynamic>.from(json['content'] as Map)),
|
||||
redirectURL: json['redirectURL'] as String?,
|
||||
headersSize: (json['headersSize'] as num?)?.toInt(),
|
||||
bodySize: (json['bodySize'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ResponseImplToJson(_$ResponseImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.status case final value?) 'status': value,
|
||||
if (instance.statusText case final value?) 'statusText': value,
|
||||
if (instance.httpVersion case final value?) 'httpVersion': value,
|
||||
if (instance.cookies case final value?) 'cookies': value,
|
||||
if (instance.headers case final value?) 'headers': value,
|
||||
if (instance.content?.toJson() case final value?) 'content': value,
|
||||
if (instance.redirectURL case final value?) 'redirectURL': value,
|
||||
if (instance.headersSize case final value?) 'headersSize': value,
|
||||
if (instance.bodySize case final value?) 'bodySize': value,
|
||||
};
|
||||
|
||||
_$ContentImpl _$$ContentImplFromJson(Map json) => _$ContentImpl(
|
||||
size: (json['size'] as num?)?.toInt(),
|
||||
mimeType: json['mimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ContentImplToJson(_$ContentImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.size case final value?) 'size': value,
|
||||
if (instance.mimeType case final value?) 'mimeType': value,
|
||||
};
|
1
packages/har/lib/models/models.dart
Normal file
1
packages/har/lib/models/models.dart
Normal file
@ -0,0 +1 @@
|
||||
export 'har_log.dart';
|
24
packages/har/lib/utils/har_utils.dart
Normal file
24
packages/har/lib/utils/har_utils.dart
Normal file
@ -0,0 +1,24 @@
|
||||
import '../models/har_log.dart';
|
||||
|
||||
List<(String?, Request)> getRequestsFromHarLog(HarLog? hl) {
|
||||
if (hl == null || hl.log == null || hl.log?.entries == null) {
|
||||
return [];
|
||||
}
|
||||
List<(String?, Request)> requests = [];
|
||||
if (hl.log?.entries?.isNotEmpty ?? false)
|
||||
for (var entry in hl.log!.entries!) {
|
||||
requests.addAll(getRequestsFromHarLogEntry(entry));
|
||||
}
|
||||
return requests;
|
||||
}
|
||||
|
||||
List<(String?, Request)> getRequestsFromHarLogEntry(Entry? entry) {
|
||||
if (entry == null) {
|
||||
return [];
|
||||
}
|
||||
List<(String?, Request)> requests = [];
|
||||
if (entry.request != null) {
|
||||
requests.add((entry.startedDateTime, entry.request!));
|
||||
}
|
||||
return requests;
|
||||
}
|
25
packages/har/pubspec.yaml
Normal file
25
packages/har/pubspec.yaml
Normal file
@ -0,0 +1,25 @@
|
||||
name: har
|
||||
description: "Seamlessly convert har Format to Dart and vice versa."
|
||||
version: 0.0.1
|
||||
homepage: https://github.com/foss42/apidash
|
||||
|
||||
topics:
|
||||
- har
|
||||
- api
|
||||
- rest
|
||||
- http
|
||||
- network
|
||||
|
||||
environment:
|
||||
sdk: ">=3.0.0 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
freezed_annotation: ^2.4.4
|
||||
json_annotation: ^4.9.0
|
||||
|
||||
dev_dependencies:
|
||||
build_runner: ^2.4.12
|
||||
freezed: ^2.5.7
|
||||
json_serializable: ^6.7.1
|
||||
lints: ^4.0.0
|
||||
test: ^1.24.0
|
329
packages/har/test/collection_examples/collection_apidash.dart
Normal file
329
packages/har/test/collection_examples/collection_apidash.dart
Normal file
@ -0,0 +1,329 @@
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {
|
||||
"name": "Client Name",
|
||||
"version": "v8.x.x"
|
||||
},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "code",
|
||||
"value": "US"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "num",
|
||||
"value": "8700000"
|
||||
},
|
||||
{
|
||||
"name": "digits",
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"value": "SS"
|
||||
},
|
||||
{
|
||||
"name": "add_space",
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"name": "trailing_zeros",
|
||||
"value": "true"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
},
|
||||
"bodySize": 50
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{
|
||||
"name": "User-Agent",
|
||||
"value": "Test Agent"
|
||||
}
|
||||
],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{
|
||||
"name": "text",
|
||||
"value": "API",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "sep",
|
||||
"value": "|",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "times",
|
||||
"value": "3",
|
||||
"contentType": "text/plain"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bodySize": 100
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{
|
||||
"name": "token",
|
||||
"value": "xyz",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bodySize": 150
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}''';
|
||||
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
25
packages/har/test/har_test.dart
Normal file
25
packages/har/test/har_test.dart
Normal file
@ -0,0 +1,25 @@
|
||||
import 'package:har/har.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'collection_examples/collection_apidash.dart';
|
||||
import 'models/collection_apidash_model.dart';
|
||||
|
||||
void main() {
|
||||
group('Har tests', () {
|
||||
test('API Dash Har Requests from Json String', () {
|
||||
expect(harLogFromJsonStr(collectionJsonStr), collectionApiDashModel);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests from Json', () {
|
||||
expect(HarLog.fromJson(collectionJson), collectionApiDashModel);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests to Json String', () {
|
||||
expect(harLogToJsonStr(collectionApiDashModel), collectionJsonStr);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests to Json', () {
|
||||
expect(collectionApiDashModel.toJson(), collectionJson);
|
||||
});
|
||||
});
|
||||
}
|
212
packages/har/test/models/collection_apidash_model.dart
Normal file
212
packages/har/test/models/collection_apidash_model.dart
Normal file
@ -0,0 +1,212 @@
|
||||
import 'package:har/models/models.dart';
|
||||
|
||||
var collectionApiDashModel = HarLog(
|
||||
log: Log(
|
||||
version: "1.2",
|
||||
creator: Creator(name: "Client Name", version: "v8.x.x"),
|
||||
entries: [
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:00:00.000Z",
|
||||
time: 100,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url: "https://api.apidash.dev",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:01:00.000Z",
|
||||
time: 150,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url: "https://api.apidash.dev/country/data?code=US",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [Query(name: "code", value: "US", disabled: null)],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:02:00.000Z",
|
||||
time: 200,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url:
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [
|
||||
Query(name: "num", value: "8700000", disabled: null),
|
||||
Query(name: "digits", value: "3", disabled: null),
|
||||
Query(name: "system", value: "SS", disabled: null),
|
||||
Query(name: "add_space", value: "true", disabled: null),
|
||||
Query(name: "trailing_zeros", value: "true", disabled: null)
|
||||
],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:03:00.000Z",
|
||||
time: 300,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/case/lower",
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: PostData(
|
||||
mimeType: "application/json",
|
||||
text: '{ "text": "I LOVE Flutter" }',
|
||||
params: null,
|
||||
),
|
||||
bodySize: 50,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:04:00.000Z",
|
||||
time: 350,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/io/form",
|
||||
headers: [
|
||||
Header(name: "User-Agent", value: "Test Agent", disabled: null)
|
||||
],
|
||||
queryString: [],
|
||||
bodySize: 100,
|
||||
postData: PostData(
|
||||
mimeType: "multipart/form-data",
|
||||
params: [
|
||||
Param(
|
||||
name: "text",
|
||||
value: "API",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "sep",
|
||||
value: "|",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "times",
|
||||
value: "3",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null)
|
||||
],
|
||||
),
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:05:00.000Z",
|
||||
time: 400,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/io/img",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: PostData(
|
||||
mimeType: "multipart/form-data",
|
||||
text: null,
|
||||
params: [
|
||||
Param(
|
||||
name: "token",
|
||||
value: "xyz",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "imfile",
|
||||
value: null,
|
||||
fileName: "hire AI.jpeg",
|
||||
contentType: "image/jpeg",
|
||||
disabled: null)
|
||||
],
|
||||
),
|
||||
headersSize: null,
|
||||
bodySize: 150,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
@ -703,6 +703,13 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
har:
|
||||
dependency: transitive
|
||||
description:
|
||||
path: "packages/har"
|
||||
relative: true
|
||||
source: path
|
||||
version: "0.0.1"
|
||||
highlight:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
Reference in New Issue
Block a user