@umituz/react-native-ai-gemini-provider 1.14.27 → 1.14.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/domain/README.md +232 -0
  3. package/src/domain/constants/README.md +191 -0
  4. package/src/domain/entities/README.md +238 -0
  5. package/src/infrastructure/README.md +252 -0
  6. package/src/infrastructure/cache/CACHE_SYSTEM.md +213 -0
  7. package/src/infrastructure/cache/README.md +213 -0
  8. package/src/infrastructure/content/CONTENT_BUILDER.md +175 -0
  9. package/src/infrastructure/content/README.md +175 -0
  10. package/src/infrastructure/interceptors/README.md +226 -0
  11. package/src/infrastructure/interceptors/REQUEST_INTERCEPTORS.md +171 -0
  12. package/src/infrastructure/job/JOB_MANAGER.md +174 -0
  13. package/src/infrastructure/job/README.md +194 -0
  14. package/src/infrastructure/response/README.md +187 -0
  15. package/src/infrastructure/response/RESPONSE_FORMATTER.md +185 -0
  16. package/src/infrastructure/services/CORE_CLIENT_SERVICE.md +202 -0
  17. package/src/infrastructure/services/FEATURE_MODEL_SELECTOR_SERVICE.md +206 -0
  18. package/src/infrastructure/services/GENERATION_EXECUTOR_SERVICE.md +176 -0
  19. package/src/infrastructure/services/IMAGE_EDIT_SERVICE.md +169 -0
  20. package/src/infrastructure/services/IMAGE_GENERATION_SERVICE.md +166 -0
  21. package/src/infrastructure/services/JOB_PROCESSOR_SERVICE.md +174 -0
  22. package/src/infrastructure/services/PROVIDER_INITIALIZER_SERVICE.md +176 -0
  23. package/src/infrastructure/services/README.md +233 -0
  24. package/src/infrastructure/services/RETRY_SERVICE.md +178 -0
  25. package/src/infrastructure/services/STREAMING_SERVICE.md +166 -0
  26. package/src/infrastructure/services/STRUCTURED_TEXT_SERVICE.md +175 -0
  27. package/src/infrastructure/services/TEXT_GENERATION_SERVICE.md +160 -0
  28. package/src/infrastructure/services/VEO_HTTP_CLIENT_SERVICE.md +179 -0
  29. package/src/infrastructure/services/VEO_POLLING_SERVICE.md +173 -0
  30. package/src/infrastructure/services/VIDEO_DOWNLOADER_SERVICE.md +166 -0
  31. package/src/infrastructure/services/VIDEO_ERROR_HANDLER_SERVICE.md +185 -0
  32. package/src/infrastructure/services/VIDEO_GENERATION_SERVICE.md +176 -0
  33. package/src/infrastructure/services/VIDEO_URL_EXTRACTOR_SERVICE.md +186 -0
  34. package/src/infrastructure/telemetry/README.md +203 -0
  35. package/src/infrastructure/telemetry/TELEMETRY_SYSTEM.md +200 -0
  36. package/src/infrastructure/utils/DATA_TRANSFORMER_UTILS.md +175 -0
  37. package/src/infrastructure/utils/ERROR_MAPPER.md +170 -0
  38. package/src/infrastructure/utils/ERROR_UTILITIES.md +208 -0
  39. package/src/infrastructure/utils/IMAGE_PREPARER_UTILS.md +185 -0
  40. package/src/infrastructure/utils/INPUT_BUILDERS.md +214 -0
  41. package/src/infrastructure/utils/MODEL_VALIDATION_UTILS.md +189 -0
  42. package/src/infrastructure/utils/PERFORMANCE_UTILITIES.md +477 -0
  43. package/src/infrastructure/utils/PERFORMANCE_UTILS.md +219 -0
  44. package/src/infrastructure/utils/README.md +289 -0
  45. package/src/presentation/README.md +187 -0
  46. package/src/presentation/hooks/README.md +188 -0
  47. package/src/presentation/hooks/USE_GEMINI_HOOK.md +226 -0
  48. package/src/providers/README.md +247 -0
@@ -0,0 +1,189 @@
1
+ # Model Validation Utilities
2
+
3
+ Helper functions for validating model IDs and determining model categories. Ensures only valid models are used in requests.
4
+
5
+ ## 📍 Import Path
6
+
7
+ ```
8
+ import {
9
+ isValidModel,
10
+ validateModel,
11
+ getSafeModel,
12
+ getModelCategory,
13
+ getAllValidModels,
14
+ isTextModel,
15
+ isImageModel,
16
+ isImageEditModel,
17
+ isVideoGenerationModel
18
+ } from '@umituz/react-native-ai-gemini-provider';
19
+ ```
20
+
21
+ ## 🎯 Purpose
22
+
23
+ Use validation utilities to verify model IDs before making API requests. Prevents errors from invalid model usage.
24
+
25
+ **When to use:**
26
+ - Validate model IDs before use
27
+ - Check model capabilities
28
+ - Get safe fallback models
29
+ - Determine model category
30
+ - List available models
31
+
32
+ ## 📌 Strategy
33
+
34
+ Validation prevents API errors. This system:
35
+ - Validates models against whitelist
36
+ - Provides safe fallbacks
37
+ - Categorizes models by capability
38
+ - Lists all valid models
39
+ - Ensures model compatibility
40
+
41
+ **Key Decision**: Always validate user-provided model IDs. Use `getSafeModel()` for fallback handling.
42
+
43
+ ## ⚠️ Rules
44
+
45
+ ### Validation Rules
46
+ - **MUST** validate models before API calls
47
+ - **SHOULD** use `getSafeModel()` for user input
48
+ - **MUST** handle invalid models
49
+ - **SHOULD** validate early in request flow
50
+ - **MUST NOT** skip validation
51
+
52
+ ### Fallback Rules
53
+ - **SHOULD** provide safe defaults
54
+ - **MUST** handle undefined models
55
+ - **SHOULD** use appropriate default types
56
+ - **MUST** document fallback behavior
57
+ - **SHOULD NOT** silently use wrong model
58
+
59
+ ### Category Rules
60
+ - **MUST** check category before using model
61
+ - **SHOULD** verify model capabilities
62
+ - **MUST** handle unknown models
63
+ - **SHOULD** use category checks
64
+ - **MUST NOT** assume model type
65
+
66
+ ### Usage Rules
67
+ - **SHOULD** validate in UI layer
68
+ - **MUST** throw on invalid models (validateModel)
69
+ - **SHOULD** return safe default (getSafeModel)
70
+ - **MUST** document validation behavior
71
+ - **SHOULD NOT** allow invalid models
72
+
73
+ ## 🤖 AI Agent Guidelines
74
+
75
+ ### When Validating Models
76
+ 1. **CALL** validation function
77
+ 2. **CHECK** return value
78
+ 3. **HANDLE** invalid model case
79
+ 4. **USE** fallback or throw
80
+ 5. **LOG** validation failures
81
+
82
+ ### When Getting Safe Models
83
+ 1. **USE** getSafeModel() for user input
84
+ 2. **PROVIDE** appropriate default type
85
+ 3. **HANDLE** undefined input
86
+ 4. **RETURN** valid model ID
87
+ 5. **DOCUMENT** fallback behavior
88
+
89
+ ### When Checking Categories
90
+ 1. **CALL** category check function
91
+ 2. **VERIFY** model supports feature
92
+ 3. **USE** appropriate service
93
+ 4. **HANDLE** category mismatch
94
+ 5. **PROVIDE** clear error messages
95
+
96
+ ### Code Style Rules
97
+ - **VALIDATE** early in request flow
98
+ - **USE** type-safe functions
99
+ - **HANDLE** all validation cases
100
+ - **PROVIDE** helpful error messages
101
+ - **DOCUMENT** validation behavior
102
+
103
+ ## 📦 Available Functions
104
+
105
+ **Refer to**: [`model-validation.util.ts`](./model-validation.util.ts)
106
+
107
+ ### Validation Functions
108
+ - `isValidModel(model)` - Check if model ID is valid
109
+ - `validateModel(model)` - Validate or throw error
110
+ - `getSafeModel(model, defaultType)` - Get safe model with fallback
111
+ - `getAllValidModels()` - Get all valid model IDs
112
+
113
+ ### Category Checks
114
+ - `isTextModel(model)` - Check if text model
115
+ - `isImageModel(model)` - Check if image model
116
+ - `isImageEditModel(model)` - Check if image edit model
117
+ - `isVideoGenerationModel(model)` - Check if video model
118
+ - `getModelCategory(model)` - Get model category
119
+
120
+ ## 🔗 Related Modules
121
+
122
+ - **Domain Entities**: [`../../domain/entities/README.md`](../../domain/entities/README.md)
123
+ - **Error Utilities**: [`./ERROR_UTILITIES.md`](./ERROR_UTILITIES.md)
124
+ - **Services README**: [`../services/README.md`](../services/README.md)
125
+
126
+ ## 📋 Model Categories
127
+
128
+ ### Text Models
129
+ Text generation models: `gemini-2.5-flash-lite`, `gemini-2.5-flash`, `gemini-2.5-pro`, `gemini-2.0-flash-exp`, `gemini-1.5-pro`, `gemini-1.5-flash`
130
+
131
+ ### Text-to-Image Models
132
+ Image generation models: `imagen-4.0-generate-001`, `imagen-3.0-generate-001`
133
+
134
+ ### Image Edit Models
135
+ Image editing models: `gemini-2.5-flash-image`, `gemini-3-pro-image-preview`
136
+
137
+ ### Video Generation Models
138
+ Video generation models: `veo-3.1-fast-generate-preview`, `veo-3.0-generate-001`
139
+
140
+ ## 🎓 Usage Patterns
141
+
142
+ ### Model Validation
143
+ 1. Call `isValidModel()` or `validateModel()`
144
+ 2. Check return value
145
+ 3. Handle invalid model case
146
+ 4. Use validated model in request
147
+ 5. Provide fallback if needed
148
+
149
+ ### Safe Model Selection
150
+ 1. Get user input for model
151
+ 2. Call `getSafeModel()` with default
152
+ 3. Use returned model ID
153
+ 4. Handle validation errors
154
+ 5. Use appropriate service
155
+
156
+ ### Category-Based Routing
157
+ 1. Get model category
158
+ 2. Route to appropriate service
159
+ 3. Use category-specific features
160
+ 4. Handle unknown categories
161
+ 5. Provide clear error messages
162
+
163
+ ### Model Listing
164
+ 1. Call `getAllValidModels()`
165
+ 2. Filter by category if needed
166
+ 3. Display to user
167
+ 4. Handle model selection
168
+ 5. Validate selection
169
+
170
+ ## 🚨 Common Pitfalls
171
+
172
+ ### Don't
173
+ - Skip model validation
174
+ - Use user input without validation
175
+ - Assume model type from name
176
+ - Allow invalid models to API
177
+ - Ignore category checks
178
+
179
+ ### Do
180
+ - Always validate model IDs
181
+ - Use safe fallbacks
182
+ - Check model categories
183
+ - Validate early in flow
184
+ - Handle all validation cases
185
+
186
+ ---
187
+
188
+ **Last Updated**: 2025-01-08
189
+ **See Also**: [AI_GUIDELINES.md](../../../../AI_GUIDELINES.md)
@@ -0,0 +1,477 @@
1
+ # Performance Utilities
2
+
3
+ Performans izleme ve optimizasyon araçları. Operasyon sürelerini ölçmek, debouncing ve throttling yapmak için kullanılır.
4
+
5
+ ## Dosya
6
+
7
+ [`performance.util.ts`](./performance.util.ts)
8
+
9
+ ## Fonksiyonlar
10
+
11
+ ### `measureAsync(operation, metadata?)`
12
+
13
+ Asenkron operasyonun süresini ölçer.
14
+
15
+ **Parametreler:**
16
+ - `operation`: `() => Promise<T>` - Ölçülecek operasyon
17
+ - `metadata?`: `Record<string, unknown>` - Ek metadata (opsiyonel)
18
+
19
+ **Dönen değer:** `Promise<{ result: T; duration: number }>`
20
+
21
+ **Örnek:**
22
+
23
+ ```typescript
24
+ import { measureAsync } from '@umituz/react-native-ai-gemini-provider';
25
+
26
+ const { result, duration } = await measureAsync(
27
+ async () => {
28
+ return await fetch('https://api.example.com/data');
29
+ },
30
+ { operation: 'fetch-data' }
31
+ );
32
+
33
+ console.log(`Sonuç:`, result);
34
+ console.log(`Süre: ${duration}ms`);
35
+ ```
36
+
37
+ ### `measureSync(operation, metadata?)`
38
+
39
+ Senkron operasyonun süresini ölçer.
40
+
41
+ **Parametreler:**
42
+ - `operation`: `() => T` - Ölçülecek operasyon
43
+ - `metadata?`: `Record<string, unknown>` - Ek metadata (opsiyonel)
44
+
45
+ **Dönen değer:** `{ result: T; duration: number }`
46
+
47
+ **Örnek:**
48
+
49
+ ```typescript
50
+ import { measureSync } from '@umituz/react-native-ai-gemini-provider';
51
+
52
+ const { result, duration } = measureSync(
53
+ () => {
54
+ return expensiveCalculation();
55
+ },
56
+ { operation: 'calculation' }
57
+ );
58
+
59
+ console.log(`Sonuç: ${result}, Süre: ${duration}ms`);
60
+ ```
61
+
62
+ ### `debounce(func, wait)`
63
+
64
+ Debounce fonksiyonu oluşturur. Fonksiyon çağrıları arasındaki bekleme süresini kontrol eder.
65
+
66
+ **Parametreler:**
67
+ - `func`: `T` - Debounce edilecek fonksiyon
68
+ - `wait`: `number` - Bekleme süresi (ms)
69
+
70
+ **Dönen değer:** Debounce edilmiş fonksiyon
71
+
72
+ **Örnek:**
73
+
74
+ ```typescript
75
+ import { debounce } from '@umituz/react-native-ai-gemini-provider';
76
+
77
+ const debouncedSearch = debounce((query: string) => {
78
+ console.log('Aranıyor:', query);
79
+ }, 300);
80
+
81
+ debouncedSearch('test'); // 300ms bekler
82
+ debouncedSearch('test2'); // Önceki iptal olur, 300ms bekler
83
+ // 300ms sonra: 'Aranıyor: test2'
84
+ ```
85
+
86
+ ### `throttle(func, limit)`
87
+
88
+ Throttle fonksiyonu oluşturur. Fonksiyonun maksimum çağrılma sıklığını sınırlar.
89
+
90
+ **Parametreler:**
91
+ - `func`: `T` - Throttle edilecek fonksiyon
92
+ - `limit`: `number` - Minimum çağrılma aralığı (ms)
93
+
94
+ **Dönen değer:** Throttle edilmiş fonksiyon
95
+
96
+ **Örnek:**
97
+
98
+ ```typescript
99
+ import { throttle } from '@umituz/react-native-ai-gemini-provider';
100
+
101
+ const throttledScroll = throttle(() => {
102
+ console.log('Scroll olayı');
103
+ }, 100);
104
+
105
+ // Her 100ms'de en fazla bir kez çalışır
106
+ window.addEventListener('scroll', throttledScroll);
107
+ ```
108
+
109
+ ## Sınıflar
110
+
111
+ ### PerformanceTimer
112
+
113
+ Performans zamanlayıcısı.
114
+
115
+ ```typescript
116
+ class PerformanceTimer {
117
+ constructor(metadata?: Record<string, unknown>)
118
+
119
+ stop(): number
120
+ get duration: number
121
+ getMetrics(): PerformanceMetrics
122
+ get isRunning(): boolean
123
+ }
124
+ ```
125
+
126
+ #### Kullanım
127
+
128
+ ```typescript
129
+ import { PerformanceTimer } from '@umituz/react-native-ai-gemini-provider';
130
+
131
+ const timer = new PerformanceTimer({ operation: 'data-processing' });
132
+
133
+ // İşlem yap
134
+ processData();
135
+
136
+ const duration = timer.stop();
137
+ console.log(`Süre: ${duration}ms`);
138
+ console.log(`Çalışıyor mu? ${timer.isRunning}`); // false
139
+ ```
140
+
141
+ ### PerformanceTracker
142
+
143
+ Performans takipçisi. Birden fazla operasyonun istatistiklerini tutar.
144
+
145
+ ```typescript
146
+ class PerformanceTracker {
147
+ record(operation: string, duration: number): void
148
+ getStats(operation: string): Stats | null
149
+ getAllStats(): Record<string, Stats>
150
+ clear(): void
151
+ }
152
+
153
+ interface Stats {
154
+ count: number;
155
+ avg: number;
156
+ min: number;
157
+ max: number;
158
+ }
159
+ ```
160
+
161
+ #### Kullanım
162
+
163
+ ```typescript
164
+ import { performanceTracker } from '@umituz/react-native-ai-gemini-provider';
165
+
166
+ // Operasyon sürelerini kaydet
167
+ performanceTracker.record('api-call', 150);
168
+ performanceTracker.record('api-call', 200);
169
+ performanceTracker.record('api-call', 175);
170
+
171
+ // İstatistikleri al
172
+ const stats = performanceTracker.getStats('api-call');
173
+ console.log(stats);
174
+ // { count: 3, avg: 175, min: 150, max: 200 }
175
+
176
+ // Tüm istatistikleri al
177
+ const allStats = performanceTracker.getAllStats();
178
+ console.log(allStats);
179
+ // { 'api-call': { count: 3, avg: 175, min: 150, max: 200 } }
180
+
181
+ // Temizle
182
+ performanceTracker.clear();
183
+ ```
184
+
185
+ ## Global Instance
186
+
187
+ ```typescript
188
+ export const performanceTracker = new PerformanceTracker();
189
+ ```
190
+
191
+ ## Kullanım Örnekleri
192
+
193
+ ### API Çağrısı Ölçümü
194
+
195
+ ```typescript
196
+ import { measureAsync, performanceTracker } from '@umituz/react-native-ai-gemini-provider';
197
+
198
+ async function fetchUserData(userId: string) {
199
+ const { result, duration } = await measureAsync(
200
+ () => fetch(`/api/users/${userId}`).then(r => r.json()),
201
+ { operation: 'fetch-user', userId }
202
+ );
203
+
204
+ // Performans tracker'a kaydet
205
+ performanceTracker.record('fetch-user', duration);
206
+
207
+ return result;
208
+ }
209
+ ```
210
+
211
+ ### Batch İşlem Performansı
212
+
213
+ ```typescript
214
+ import { measureSync } from '@umituz/react-native-ai-gemini-provider';
215
+
216
+ function processBatch(items: any[]) {
217
+ const { result, duration } = measureSync(
218
+ () => items.map(item => processItem(item)),
219
+ { operation: 'batch-process', itemCount: items.length }
220
+ );
221
+
222
+ console.log(`${items.length} öğe ${duration}ms'de işlendi`);
223
+ console.log(`Ortalama: ${(duration / items.length).toFixed(2)}ms per item`);
224
+
225
+ return result;
226
+ }
227
+ ```
228
+
229
+ ### Arama Input'u Debounce
230
+
231
+ ```typescript
232
+ import { debounce } from '@umituz/react-native-ai-gemini-provider';
233
+
234
+ function SearchInput() {
235
+ const [query, setQuery] = useState('');
236
+
237
+ // Debounce ile arama
238
+ const debouncedSearch = debounce(async (searchQuery: string) => {
239
+ const results = await searchAPI(searchQuery);
240
+ setResults(results);
241
+ }, 500);
242
+
243
+ const handleChange = (text: string) => {
244
+ setQuery(text);
245
+ debouncedSearch(text);
246
+ };
247
+
248
+ return (
249
+ <TextInput
250
+ value={query}
251
+ onChangeText={handleChange}
252
+ placeholder="Ara..."
253
+ />
254
+ );
255
+ }
256
+ ```
257
+
258
+ ### Scroll Olayı Throttle
259
+
260
+ ```typescript
261
+ import { throttle } from '@umituz/react-native-ai-gemini-provider';
262
+
263
+ function InfiniteScrollList() {
264
+ const handleScroll = throttle(() => {
265
+ // Scroll sonuna yaklaştıkça daha fazla veri yükle
266
+ loadMoreData();
267
+ }, 500);
268
+
269
+ return (
270
+ <ScrollView onScroll={handleScroll}>
271
+ {/* İçerik */}
272
+ </ScrollView>
273
+ );
274
+ }
275
+ ```
276
+
277
+ ### Kompleks Operasyon Takibi
278
+
279
+ ```typescript
280
+ import { PerformanceTimer } from '@umituz/react-native-ai-gemini-provider';
281
+
282
+ async function complexOperation() {
283
+ const timers = {
284
+ step1: new PerformanceTimer({ step: 'step1' }),
285
+ step2: new PerformanceTimer({ step: 'step2' }),
286
+ step3: new PerformanceTimer({ step: 'step3' }),
287
+ };
288
+
289
+ // Adım 1
290
+ const result1 = await step1();
291
+ timers.step1.stop();
292
+ console.log(`Adım 1: ${timers.step1.duration}ms`);
293
+
294
+ // Adım 2
295
+ const result2 = await step2();
296
+ timers.step2.stop();
297
+ console.log(`Adım 2: ${timers.step2.duration}ms`);
298
+
299
+ // Adım 3
300
+ const result3 = await step3();
301
+ timers.step3.stop();
302
+ console.log(`Adım 3: ${timers.step3.duration}ms`);
303
+
304
+ const totalDuration = timers.step1.duration + timers.step2.duration + timers.step3.duration;
305
+ console.log(`Toplam: ${totalDuration}ms`);
306
+ }
307
+ ```
308
+
309
+ ### Performance Dashboard
310
+
311
+ ```typescript
312
+ import { performanceTracker } from '@umituz/react-native-ai-gemini-provider';
313
+
314
+ function PerformanceDashboard() {
315
+ const stats = performanceTracker.getAllStats();
316
+
317
+ return (
318
+ <View>
319
+ <Text>Performans İstatistikleri</Text>
320
+ {Object.entries(stats).map(([operation, stat]) => (
321
+ <View key={operation}>
322
+ <Text>{operation}</Text>
323
+ <Text>Count: {stat.count}</Text>
324
+ <Text>Average: {stat.avg.toFixed(0)}ms</Text>
325
+ <Text>Min: {stat.min}ms</Text>
326
+ <Text>Max: {stat.max}ms</Text>
327
+ </View>
328
+ ))}
329
+ </View>
330
+ );
331
+ }
332
+ ```
333
+
334
+ ### Conditional Measurement
335
+
336
+ ```typescript
337
+ import { measureAsync } from '@umituz/react-native-ai-gemini-provider';
338
+
339
+ async function conditionalFetch(shouldMeasure: boolean) {
340
+ if (shouldMeasure) {
341
+ // Development modunda ölç
342
+ const { result, duration } = await measureAsync(
343
+ () => fetch('https://api.example.com/data'),
344
+ { operation: 'fetch-data' }
345
+ );
346
+
347
+ if (__DEV__) {
348
+ console.log(`API call took ${duration}ms`);
349
+ }
350
+
351
+ return result;
352
+ } else {
353
+ // Production'da direkt çağır
354
+ return await fetch('https://api.example.com/data');
355
+ }
356
+ }
357
+ ```
358
+
359
+ ### Memory Monitoring
360
+
361
+ ```typescript
362
+ import { measureAsync } from '@umituz/react-native-ai-gemini-provider';
363
+
364
+ async function monitoredOperation() {
365
+ const startMemory = performance.memory?.usedJSHeapSize;
366
+
367
+ const { result, duration } = await measureAsync(async () => {
368
+ return await heavyOperation();
369
+ });
370
+
371
+ const endMemory = performance.memory?.usedJSHeapSize;
372
+ const memoryUsed = endMemory && startMemory
373
+ ? endMemory - startMemory
374
+ : 0;
375
+
376
+ console.log(`Süre: ${duration}ms`);
377
+ console.log(`Memory: ${(memoryUsed / 1024 / 1024).toFixed(2)}MB`);
378
+
379
+ return result;
380
+ }
381
+ ```
382
+
383
+ ### Performance Alerts
384
+
385
+ ```typescript
386
+ import { performanceTracker } from '@umituz/react-native-ai-gemini-provider';
387
+
388
+ // Performance monitoring
389
+ setInterval(() => {
390
+ const stats = performanceTracker.getAllStats();
391
+
392
+ Object.entries(stats).forEach(([operation, stat]) => {
393
+ // Yavaş operasyon kontrolü
394
+ if (stat.avg > 5000) {
395
+ console.warn(`⚠️ Yavaş operasyon: ${operation} (avg: ${stat.avg.toFixed(0)}ms)`);
396
+ // Alert gönder
397
+ sendAlert({
398
+ type: 'slow-operation',
399
+ operation,
400
+ avgTime: stat.avg,
401
+ });
402
+ }
403
+
404
+ // Çok değişken (min-max farkı büyük)
405
+ const variance = stat.max - stat.min;
406
+ if (variance > 3000) {
407
+ console.warn(`⚠️ Dengesiz operasyon: ${operation} (min: ${stat.min}ms, max: ${stat.max}ms)`);
408
+ }
409
+ });
410
+ }, 60000); // Her dakika
411
+ ```
412
+
413
+ ## PerformanceMetrics
414
+
415
+ ```typescript
416
+ interface PerformanceMetrics {
417
+ duration: number;
418
+ timestamp: number;
419
+ metadata?: Record<string, unknown>;
420
+ }
421
+ ```
422
+
423
+ ## Best Practices
424
+
425
+ ### 1. Measure kullanın
426
+
427
+ ```typescript
428
+ // ✅ İyi - measureAsync kullan
429
+ const { result, duration } = await measureAsync(() => apiCall());
430
+
431
+ // ❌ Kötü - Manuel ölçüm
432
+ const start = Date.now();
433
+ const result = await apiCall();
434
+ const duration = Date.now() - start;
435
+ ```
436
+
437
+ ### 2. Metadata ekleyin
438
+
439
+ ```typescript
440
+ // ✅ İyi - Metadata ile
441
+ measureAsync(() => apiCall(), {
442
+ operation: 'fetch-user',
443
+ userId: '123',
444
+ endpoint: '/api/users/123'
445
+ });
446
+
447
+ // ❌ Kötü - Metadata olmadan
448
+ measureAsync(() => apiCall());
449
+ ```
450
+
451
+ ### 3. Debounce/throttle kullanın
452
+
453
+ ```typescript
454
+ // ✅ İyi - Debounce ile
455
+ const debouncedSearch = debounce(search, 300);
456
+
457
+ // ❌ Kötü - Her tuşta arama
458
+ onChange={(e) => search(e.target.value)}
459
+ ```
460
+
461
+ ### 4. Development'da ölçün
462
+
463
+ ```typescript
464
+ // ✅ İyi - Sadece development'ta
465
+ if (__DEV__) {
466
+ const { duration } = await measureAsync(() => apiCall());
467
+ console.log(`API call: ${duration}ms`);
468
+ }
469
+
470
+ // ❌ Kötü - Her zaman ölçüm
471
+ const { duration } = await measureAsync(() => apiCall());
472
+ ```
473
+
474
+ ## İlgili Dosyalar
475
+
476
+ - [`performance.util.ts`](./performance.util.ts) - Implementasyon
477
+ - [`../telemetry/README.md`](../telemetry/README.md) - Telemetry modülü