@testerpaykit/sdk 0.0.0-stage → 1.1.0

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.
@@ -0,0 +1,908 @@
1
+ import { ISessionManager, IStorage, IApiClient, DeviceMetadata, AppMetadata, BugReportInput, VoiceBugExtractResponse, QuickActionKind, MyBugReportsResponse, NotificationsResult, OutboxItemStatus, WeeklySummary, TaskListFilter, TaskListResponse, RetestItem, RetestStepVerdicts, TesterProfile, TesterPoints, IEventTracker } from '@testerpaykit/core';
2
+ export { AppMetadata, BUG_REPORT_CATEGORIES, BUG_REPORT_SEVERITIES, BUG_REPORT_TYPES, BugReportCategory, BugReportInput, BugReportSeverity, BugReportType, DeviceMetadata, IApiClient, IEventTracker, ISessionManager, IStorage, OutboxItemStatus, QualityFlags, SessionMetrics, WeeklySummary } from '@testerpaykit/core';
3
+
4
+ type SessionEndReason = 'completed' | 'lifecycle_flush' | 'timeout' | 'abandoned';
5
+ /**
6
+ * Session manager implementation for tracking user testing sessions.
7
+ *
8
+ * Implements ISessionManager interface and manages the lifecycle of testing sessions,
9
+ * including session creation, duration tracking, foreground/paid-time clock,
10
+ * and database persistence.
11
+ */
12
+ declare class SessionManager implements ISessionManager {
13
+ private currentSessionId;
14
+ private sessionStartTime;
15
+ private storage;
16
+ private foregroundAccumulatedMs;
17
+ private foregroundClockStartMs;
18
+ constructor(storage: IStorage);
19
+ /**
20
+ * Start a new testing session.
21
+ *
22
+ * Creates a new session with a unique ID and stores it in the database.
23
+ * If there's an active session, it will be ended before starting the new one.
24
+ *
25
+ * @returns Promise resolving to the new session ID
26
+ */
27
+ startSession(): Promise<string>;
28
+ /**
29
+ * End the current testing session.
30
+ *
31
+ * Calculates session duration and updates the database.
32
+ * After ending, no session will be active.
33
+ *
34
+ * @param endReason - Reason for ending the session (default: 'completed')
35
+ */
36
+ endSession(endReason?: SessionEndReason): Promise<void>;
37
+ /**
38
+ * Pause the foreground (paid-time) clock.
39
+ * Call when the app moves to background. Has no effect if already paused.
40
+ */
41
+ pauseForegroundClock(): void;
42
+ /**
43
+ * Resume the foreground (paid-time) clock.
44
+ * Call when the app returns to foreground. Has no effect if already running.
45
+ */
46
+ resumeForegroundClock(): void;
47
+ /**
48
+ * Get the accumulated foreground seconds for the current session.
49
+ *
50
+ * @returns Foreground time in whole seconds
51
+ */
52
+ getForegroundSeconds(): number;
53
+ /**
54
+ * Get the current session ID.
55
+ *
56
+ * @returns Current session ID or null if no session is active
57
+ */
58
+ getCurrentSessionId(): string | null;
59
+ /**
60
+ * Check if there's an active session.
61
+ *
62
+ * @returns true if a session is currently active
63
+ */
64
+ hasActiveSession(): boolean;
65
+ /**
66
+ * Get the current session duration in seconds.
67
+ *
68
+ * @returns Duration in seconds, or 0 if no session is active
69
+ */
70
+ getSessionDuration(): number;
71
+ /**
72
+ * Get the epoch-ms timestamp when the current session started.
73
+ *
74
+ * @returns Epoch ms, or null when no session is active
75
+ */
76
+ getCurrentSessionStartedAt(): number | null;
77
+ /**
78
+ * Increment the screen view count for the current session.
79
+ * Internal method used by EventTracker.
80
+ */
81
+ incrementScreenViews(): Promise<void>;
82
+ /**
83
+ * Increment the tap count for the current session.
84
+ * Internal method used by EventTracker.
85
+ */
86
+ incrementTaps(): Promise<void>;
87
+ }
88
+
89
+ /**
90
+ * Configuration for TesterPayKit SDK.
91
+ */
92
+ interface TesterPayKitConfig {
93
+ /**
94
+ * API key for authentication
95
+ */
96
+ apiKey: string;
97
+ /**
98
+ * API base URL (required). Used to derive `environment`.
99
+ * e.g. "https://api.testerpaykit.com" or "http://localhost:18080"
100
+ */
101
+ apiBaseUrl?: string;
102
+ /**
103
+ * Project identifier
104
+ */
105
+ projectId: string;
106
+ /**
107
+ * Tester pseudonymous identifier
108
+ */
109
+ testerId: string;
110
+ /**
111
+ * Device pseudonymous identifier override.
112
+ * When omitted, a UUIDv4 is generated and persisted by DeviceIdManager
113
+ * with a 30-day rotation policy (contract: invariants.device_id).
114
+ */
115
+ deviceId?: string;
116
+ /**
117
+ * Storage adapter instance
118
+ */
119
+ storage: IStorage;
120
+ /**
121
+ * API client instance (optional, for Agent 4 integration)
122
+ */
123
+ apiClient?: IApiClient;
124
+ /**
125
+ * Device metadata
126
+ */
127
+ deviceMetadata: DeviceMetadata;
128
+ /**
129
+ * App metadata
130
+ */
131
+ appMetadata: AppMetadata;
132
+ /**
133
+ * Automatically start a session on init (default: true)
134
+ */
135
+ autoStartSession?: boolean;
136
+ /**
137
+ * Enable debug logging (default: false)
138
+ */
139
+ debugMode?: boolean;
140
+ /**
141
+ * Base payout amount awarded at session start (default: 1.0).
142
+ */
143
+ earningsBaseAmount?: number;
144
+ /**
145
+ * Additional payout per engaged minute (default: 0.10).
146
+ */
147
+ earningsPerMinuteRate?: number;
148
+ /**
149
+ * Currency for earnings display (default: 'EUR').
150
+ */
151
+ earningsCurrency?: string;
152
+ /**
153
+ * Capture screen view events (default: true)
154
+ */
155
+ captureScreenViews?: boolean;
156
+ /**
157
+ * Capture tap/click events (default: true)
158
+ */
159
+ captureTapEvents?: boolean;
160
+ /**
161
+ * Capture error events (default: true)
162
+ */
163
+ captureErrors?: boolean;
164
+ /**
165
+ * Capture crash events (default: true)
166
+ */
167
+ captureCrashes?: boolean;
168
+ /**
169
+ * Day of week for the weekly period submission (1=Mon … 7=Sun, default: 7).
170
+ * Contract: configuration.weeklySubmissionDay
171
+ */
172
+ weeklySubmissionDay?: number;
173
+ }
174
+ /**
175
+ * Main TesterPayKit SDK class.
176
+ *
177
+ * Orchestrates session management, event tracking, and metrics aggregation
178
+ * for the TesterPayKit testing platform.
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * import { TesterPayKit } from '@testerpaykit/sdk';
183
+ * import { IndexedDBAdapter } from '@testerpaykit/storage-browser';
184
+ *
185
+ * const storage = new IndexedDBAdapter();
186
+ * const sdk = new TesterPayKit({
187
+ * apiKey: 'your-api-key',
188
+ * apiBaseUrl: 'https://api.testerpaykit.com',
189
+ * projectId: 'project-123',
190
+ * testerId: 'tester-456',
191
+ * storage,
192
+ * deviceMetadata: { os: 'Web', osVersion: '1.0', ... },
193
+ * appMetadata: { bundleId: 'com.example.app', version: '1.0.0', ... },
194
+ * });
195
+ *
196
+ * await sdk.init();
197
+ * await sdk.anonymousAuthReady; // wait for auth before first authed call
198
+ * await sdk.trackScreenView('HomeScreen');
199
+ * ```
200
+ */
201
+ declare class TesterPayKit {
202
+ private config;
203
+ private sessionManager;
204
+ private eventTracker;
205
+ private metricsAggregator;
206
+ private outbox;
207
+ private deviceIdManager;
208
+ private initialized;
209
+ private _resolvedDeviceId;
210
+ private _resolvedTesterId;
211
+ private _authToken;
212
+ private _serverSessionId;
213
+ private _pendingSessionEvents;
214
+ readonly anonymousAuthReady: Promise<void>;
215
+ private _resolveAnonymousAuth;
216
+ readonly environment: 'local' | 'prod';
217
+ private static readonly LOG_BUFFER_MAX;
218
+ private _logBuffer;
219
+ constructor(config: TesterPayKitConfig);
220
+ get onTokenReady(): Promise<void>;
221
+ get isAuthenticated(): boolean;
222
+ /**
223
+ * Initialize the SDK.
224
+ *
225
+ * Must be called before using any other SDK methods.
226
+ * Initializes storage and optionally starts a session.
227
+ */
228
+ init(): Promise<void>;
229
+ /**
230
+ * Provide an auth token to the SDK (e.g. after anonymous login).
231
+ * Makes isAuthenticated return true and enables runDurabilitySweep.
232
+ */
233
+ setAuthToken(token: string): void;
234
+ /**
235
+ * Request a passwordless magic-link sign-in for a registered tester.
236
+ * TesterPayKit tester auth is magic-link (no passwords): the server emails a
237
+ * single-use link that returns to `returnUrl` (a first-party *.moinsen.dev
238
+ * page) carrying a token, which the host consumes via consumeTesterMagicLink.
239
+ * `country` (DE/AT/CH) lets an unknown email self-signup. Returns true if the
240
+ * request was accepted. Never throws.
241
+ */
242
+ requestTesterMagicLink(email: string, returnUrl: string, country?: string): Promise<boolean>;
243
+ /**
244
+ * Consume a magic-link token (from the returnUrl the tester landed on). On
245
+ * success the real tester token supersedes the anonymous one, the tester is
246
+ * enrolled in this project, and {accessToken, refreshToken} is returned so
247
+ * the host can persist the session. Returns null on failure. Never throws.
248
+ */
249
+ consumeTesterMagicLink(token: string): Promise<{
250
+ accessToken: string;
251
+ refreshToken?: string;
252
+ } | null>;
253
+ /**
254
+ * Enroll the current tester into THIS project (idempotent, best-effort).
255
+ * Used right after loginTester so the tester is a project participant.
256
+ * Returns true if enrolled (or already enrolled), false on hard failure.
257
+ */
258
+ enrollSelf(): Promise<boolean>;
259
+ /** device_info payload for the server session, from configured metadata. */
260
+ private _sessionDeviceInfo;
261
+ /**
262
+ * Lazily create the SERVER tester session once an anonymous token is in
263
+ * hand, then flush any buffered events. This is what makes the session
264
+ * show up in the coordinator dashboard. Best-effort: never throws.
265
+ */
266
+ private _ensureServerSession;
267
+ private _serverSessionInFlight;
268
+ private _createServerSession;
269
+ /** Flush buffered session events to the server (best-effort, re-queues on fail). */
270
+ private _flushServerSessionEvents;
271
+ /** End the server session (best-effort). Clears the id so it won't re-end. */
272
+ private _endServerSession;
273
+ /**
274
+ * Run a durability sweep to ensure testing work is persisted and uploaded.
275
+ *
276
+ * No-op when no auth token is held. Otherwise, best-effort (each step is
277
+ * individually wrapped so one failure does not abort the rest):
278
+ *
279
+ * 1. Reconcile open sessions: find sessions in storage without an end_time
280
+ * and close them with endReason='abandoned' so their duration counts.
281
+ * 2. Auto-create a period submission when overdue: tracks the last submission
282
+ * timestamp in sdk_meta. "Due" = more than 7 days since last enqueue.
283
+ * (Heuristic — uses wall-clock elapsed time, not calendar periods.)
284
+ * 3. Drain the outbox. The Outbox drain already skips server-known submission
285
+ * ids (fetchServerSubmissionIds guard) so no double-pay occurs.
286
+ *
287
+ * Contract: api.submissions.runDurabilitySweep
288
+ */
289
+ runDurabilitySweep(): Promise<void>;
290
+ private _reconcileOpenSessions;
291
+ private _autoCreateSubmissionIfDue;
292
+ /**
293
+ * Start a new testing session.
294
+ *
295
+ * @returns Promise resolving to the new session ID
296
+ */
297
+ startSession(): Promise<string>;
298
+ /**
299
+ * End the current testing session.
300
+ *
301
+ * @param endReason - Reason for ending (default: 'completed')
302
+ */
303
+ endSession(endReason?: SessionEndReason): Promise<void>;
304
+ /**
305
+ * Call when the app moves to the foreground / resumes.
306
+ *
307
+ * Contract behaviour:
308
+ * - If NO active session exists → start a new one.
309
+ * - If a session IS active → resume the foreground clock only.
310
+ * MUST NOT end and restart the active session.
311
+ */
312
+ onAppResumed(): Promise<void>;
313
+ /**
314
+ * Call when the app moves to the background / is paused.
315
+ *
316
+ * Contract behaviour: freezes the foreground clock.
317
+ * MUST NOT end the session.
318
+ */
319
+ onAppPaused(): void;
320
+ /**
321
+ * Call when the app becomes inactive (e.g. phone call overlay, app-switcher).
322
+ *
323
+ * Contract behaviour: no-op for the session (may log only).
324
+ */
325
+ onAppInactive(): void;
326
+ /**
327
+ * Call when the app process is about to be detached / destroyed.
328
+ *
329
+ * Contract behaviour: ends the active session with end_reason='lifecycle_flush'.
330
+ */
331
+ onAppDetached(): Promise<void>;
332
+ /**
333
+ * Track a screen view event.
334
+ *
335
+ * @param screenName - Name or route of the screen
336
+ * @param metadata - Optional additional metadata
337
+ */
338
+ trackScreenView(screenName: string, metadata?: Record<string, any>): Promise<void>;
339
+ /**
340
+ * Track a tap/click event.
341
+ *
342
+ * @param screenName - Name of the screen where the tap occurred
343
+ * @param elementId - Optional ID of the tapped element
344
+ */
345
+ trackTap(screenName: string, elementId?: string): Promise<void>;
346
+ /**
347
+ * Track a custom event.
348
+ *
349
+ * @param eventType - Type of the event
350
+ * @param metadata - Optional event metadata
351
+ */
352
+ trackEvent(eventType: string, metadata?: Record<string, any>): Promise<void>;
353
+ /**
354
+ * Track an error.
355
+ *
356
+ * @param message - Error message
357
+ * @param stack - Optional stack trace
358
+ */
359
+ trackError(message: string, stack?: string): Promise<void>;
360
+ /**
361
+ * Track a crash.
362
+ *
363
+ * @param message - Crash message
364
+ * @param stack - Stack trace
365
+ */
366
+ trackCrash(message: string, stack: string): Promise<void>;
367
+ /**
368
+ * Track feedback submission.
369
+ *
370
+ * @param content - Feedback content
371
+ * @param rating - Optional numeric rating
372
+ */
373
+ trackFeedback(content: string, rating?: number): Promise<void>;
374
+ /**
375
+ * Track task start.
376
+ *
377
+ * @param taskId - Unique task identifier
378
+ * @param title - Task title
379
+ */
380
+ trackTaskStart(taskId: string, title: string): Promise<void>;
381
+ /**
382
+ * Track task completion.
383
+ *
384
+ * @param taskId - Unique task identifier
385
+ */
386
+ trackTaskComplete(taskId: string): Promise<void>;
387
+ /**
388
+ * Enqueue a bug report to the local outbox and return a local UUID
389
+ * immediately. The upload happens in the background — this method
390
+ * never awaits the network.
391
+ *
392
+ * Builds the full payload required by POST /v1/testers/me/bug-reports:
393
+ * sessionId, type, severity, category, title, description,
394
+ * currentScreen, deviceSnapshot, appSnapshot, projectId.
395
+ * testerId is intentionally omitted — the endpoint is tester-namespaced
396
+ * and derives the tester from the JWT.
397
+ *
398
+ * Contract: api.submissions.submitBugReport / invariants.local_first_outbox
399
+ *
400
+ * @param input - Structured bug report input
401
+ * @returns A local UUID that can be passed to getSubmissionStatus()
402
+ */
403
+ submitBugReport(input: BugReportInput): string;
404
+ /**
405
+ * Extract structured bug-report fields from a base64-encoded audio recording.
406
+ *
407
+ * Delegates to apiClient.voiceExtractBugFields. When `sourceLanguage` is
408
+ * explicitly provided (ISO-639-1, e.g. 'de'), it is forwarded as-is.
409
+ * When omitted, the language hint falls back to navigator.language
410
+ * (best-effort, browser-only). Soft-fails to null when the apiClient does
411
+ * not implement voiceExtractBugFields or the call throws.
412
+ *
413
+ * Contract: wire.bug_reports.voiceExtractBugFields
414
+ *
415
+ * @param audioBase64 - Raw base64 audio (no data: prefix)
416
+ * @param mimeType - MIME type of the audio (e.g. 'audio/webm')
417
+ * @param sourceLanguage - Optional explicit ISO-639-1 language code; when
418
+ * omitted the SDK derives it from navigator.language
419
+ * @returns Extracted fields, or null on any failure
420
+ */
421
+ extractBugFromVoice(audioBase64: string, mimeType: string, sourceLanguage?: string): Promise<VoiceBugExtractResponse | null>;
422
+ /**
423
+ * One-tap report draft from a screenshot of the current screen — the
424
+ * quick-action path next to voice. Returns null when the client does
425
+ * not support it; throws on a server error so the UI can show it.
426
+ *
427
+ * Contract: wire.bug_reports.quickDraftBug
428
+ *
429
+ * @param screenshotDataUrl - `data:image/...;base64,...` of the screen
430
+ */
431
+ quickDraftBug(action: QuickActionKind, screenshotDataUrl: string, options?: {
432
+ screenName?: string;
433
+ language?: string;
434
+ }): Promise<VoiceBugExtractResponse | null>;
435
+ /**
436
+ * Upload an arbitrary attachment (screenshot, screen recording, voice note, etc.)
437
+ * to the standalone attachments endpoint (POST /v1/attachments).
438
+ *
439
+ * Returns the stored URL/path on success, null on any failure (best-effort,
440
+ * never throws).
441
+ *
442
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
443
+ *
444
+ * @param input - Attachment data with base64 content, MIME type, file type, and optional file name
445
+ * @returns The attachment url/path string, or null if upload failed or client unavailable
446
+ */
447
+ uploadAttachment(input: {
448
+ base64: string;
449
+ mimeType: string;
450
+ fileType: 'screen_recording' | 'voice_note' | 'image' | 'screenshot' | 'video' | 'audio' | 'log' | 'document' | 'other';
451
+ fileName?: string;
452
+ }): Promise<string | null>;
453
+ /**
454
+ * Upload a screenshot dataURL to the standalone attachments endpoint.
455
+ *
456
+ * Converts the dataURL to a base64 payload and calls
457
+ * POST /v1/attachments via the api-client. Returns the attachment
458
+ * url/path on success, null on any failure (best-effort, never throws).
459
+ *
460
+ * Contract: wire.bug_reports.uploadAttachment (standalone path)
461
+ *
462
+ * @param dataUrl - A JPEG/PNG dataURL (e.g. from html2canvas or captureScreenshot)
463
+ * @returns The attachment url string, or null if upload failed or client unavailable
464
+ */
465
+ uploadScreenshot(dataUrl: string): Promise<string | null>;
466
+ /**
467
+ * Fetch the bug reports this tester has submitted (newest first).
468
+ * Delegates to apiClient.listMyBugReports. Soft-fails to an empty list
469
+ * when the client lacks the method or the call throws.
470
+ *
471
+ * Requires a tester auth token — if unauthenticated the server 401s and
472
+ * this returns the empty-list soft-fail result.
473
+ */
474
+ getMyBugReports(params?: {
475
+ status?: string;
476
+ limit?: number;
477
+ page?: number;
478
+ }): Promise<MyBugReportsResponse>;
479
+ /**
480
+ * Fetch tester notifications + unread count.
481
+ * Delegates to apiClient.getMyNotifications. Soft-fails to
482
+ * { notifications: [], unreadCount: 0 } on any error or missing method.
483
+ *
484
+ * Requires a tester auth token.
485
+ */
486
+ getNotifications(params?: {
487
+ limit?: number;
488
+ unreadOnly?: boolean;
489
+ }): Promise<NotificationsResult>;
490
+ /**
491
+ * Mark notifications read. Pass an id to mark one; omit to mark all.
492
+ * Delegates to apiClient.markNotificationsRead. Soft-fails to null on
493
+ * any error or missing method (caller should treat null as "no change").
494
+ *
495
+ * Requires a tester auth token.
496
+ *
497
+ * @returns New unread count, or null on soft-fail.
498
+ */
499
+ markNotificationsRead(id?: string): Promise<number | null>;
500
+ /**
501
+ * Aggregate local metrics and enqueue a submission to the outbox.
502
+ * Returns a local UUID immediately — the upload happens in the background.
503
+ *
504
+ * Contract: api.submissions.createSubmissionAsync / invariants.local_first_outbox
505
+ *
506
+ * @returns A local UUID that can be passed to getSubmissionStatus()
507
+ */
508
+ createSubmission(): Promise<string>;
509
+ /**
510
+ * Query the outbox state for a previously-enqueued item.
511
+ *
512
+ * Returns:
513
+ * 'pending' — enqueued, not yet uploaded
514
+ * 'uploading' — upload in progress
515
+ * 'failed' — permanently rejected (4xx); will not be retried
516
+ * null — item not found; treat as successfully sent (deleted on success)
517
+ *
518
+ * Contract: api.submissions.getSubmissionStatus / enums.OutboxItemStatus
519
+ *
520
+ * @param localId - The id returned by submitBugReport() or createSubmission()
521
+ */
522
+ getSubmissionStatus(localId: string): Promise<OutboxItemStatus | null>;
523
+ /**
524
+ * Generate and store a weekly summary.
525
+ *
526
+ * Aggregates all metrics from the past 7 days and stores the summary
527
+ * in the local database for later submission.
528
+ *
529
+ * @returns Promise resolving to the generated summary
530
+ */
531
+ generateWeeklySummary(): Promise<WeeklySummary>;
532
+ /**
533
+ * Get all pending summaries.
534
+ *
535
+ * @returns Array of pending WeeklySummary objects
536
+ */
537
+ getPendingSummaries(): Promise<WeeklySummary[]>;
538
+ /**
539
+ * Submit pending summaries to the server.
540
+ * Requires apiClient to be configured.
541
+ *
542
+ * @returns Number of summaries successfully submitted
543
+ */
544
+ submitPendingSummaries(): Promise<number>;
545
+ /**
546
+ * Get the current session ID.
547
+ *
548
+ * @returns Current session ID or null if no session is active
549
+ */
550
+ getCurrentSessionId(): string | null;
551
+ /**
552
+ * Check if there's an active session.
553
+ *
554
+ * @returns true if a session is currently active
555
+ */
556
+ hasActiveSession(): boolean;
557
+ /**
558
+ * Get the current session duration in seconds.
559
+ *
560
+ * @returns Duration in seconds, or 0 if no session is active
561
+ */
562
+ getSessionDuration(): number;
563
+ /**
564
+ * Close the SDK and clean up resources.
565
+ */
566
+ close(): Promise<void>;
567
+ /**
568
+ * Ensure the SDK is initialized before use.
569
+ * @throws Error if SDK is not initialized
570
+ */
571
+ private ensureInitialized;
572
+ /**
573
+ * Log debug messages. Always pushes to the ring buffer (regardless of
574
+ * debugMode) so TpkDebugLogsScreen has content. Console output stays
575
+ * gated by debugMode.
576
+ */
577
+ private log;
578
+ /**
579
+ * Get a copy of the debug log buffer, newest entry first.
580
+ * The buffer accumulates up to 200 entries regardless of debugMode.
581
+ */
582
+ getDebugLogs(): Array<{
583
+ ts: number;
584
+ message: string;
585
+ }>;
586
+ /**
587
+ * Clear the debug log buffer.
588
+ */
589
+ clearDebugLogs(): void;
590
+ /**
591
+ * Get the epoch-ms timestamp when the current session started.
592
+ * Delegates to SessionManager.
593
+ *
594
+ * @returns Epoch ms, or null when no session is active
595
+ */
596
+ getCurrentSessionStartedAt(): number | null;
597
+ /**
598
+ * Compute estimated session earnings.
599
+ *
600
+ * engagedMinutes = floor(elapsed since session start in minutes).
601
+ * amount = earningsBaseAmount + engagedMinutes * earningsPerMinuteRate.
602
+ * currency = earningsCurrency from config.
603
+ *
604
+ * Soft-safe: never throws; returns base/0/currency when no session.
605
+ * Max cap: 480 minutes (8 hours) to keep amounts sane.
606
+ */
607
+ getSessionEarnings(): {
608
+ engagedMinutes: number;
609
+ amount: number;
610
+ currency: string;
611
+ };
612
+ /**
613
+ * Return the configured app metadata (bundleId, version, buildNumber, etc.).
614
+ * Used by TpkWorkboardScreen to show the current build info block.
615
+ */
616
+ getAppInfo(): AppMetadata;
617
+ /**
618
+ * Fetch the tester's assigned tasks.
619
+ * Delegates to apiClient.getMyTasks. Soft-fails to an empty TaskListResponse
620
+ * when the client lacks the method or the call throws.
621
+ */
622
+ getMyTasks(params?: TaskListFilter): Promise<TaskListResponse>;
623
+ /**
624
+ * Mark a task assignment in-progress.
625
+ * Delegates to apiClient.startTaskAssignment. Soft-fails silently on error.
626
+ */
627
+ startTask(assignmentId: string): Promise<void>;
628
+ /**
629
+ * Complete a task assignment.
630
+ * Delegates to apiClient.completeTaskAssignment. Soft-fails silently on error.
631
+ */
632
+ completeTask(assignmentId: string): Promise<void>;
633
+ /**
634
+ * Fetch the tester's retest queue.
635
+ * Delegates to apiClient.getMyRetests. Soft-fails to an empty array.
636
+ */
637
+ getMyRetests(params?: {
638
+ status?: string;
639
+ }): Promise<RetestItem[]>;
640
+ /**
641
+ * Mark a retest as verified (bug is fixed).
642
+ * Delegates to apiClient.verifyRetest. Soft-fails silently on error.
643
+ */
644
+ verifyRetest(bugId: string, stepVerdicts?: RetestStepVerdicts): Promise<void>;
645
+ /**
646
+ * Reopen a retest (bug still present), optionally with a reason.
647
+ * Delegates to apiClient.reopenRetest. Soft-fails silently on error.
648
+ */
649
+ reopenRetest(bugId: string, reason?: string, stepVerdicts?: RetestStepVerdicts): Promise<void>;
650
+ /**
651
+ * Fetch the tester's profile.
652
+ * Delegates to apiClient.getMyProfile. Soft-fails to null on error.
653
+ */
654
+ getMyProfile(): Promise<TesterProfile | null>;
655
+ /**
656
+ * Fetch the tester's points balance.
657
+ * Delegates to apiClient.getMyPoints. Soft-fails to null on error.
658
+ */
659
+ getMyPoints(): Promise<TesterPoints | null>;
660
+ }
661
+
662
+ interface CaptureFlags {
663
+ captureScreenViews: boolean;
664
+ captureTapEvents: boolean;
665
+ captureErrors: boolean;
666
+ captureCrashes: boolean;
667
+ }
668
+ /**
669
+ * Event tracker implementation for capturing user interactions and app events.
670
+ *
671
+ * Implements IEventTracker interface and tracks various event types including
672
+ * screen views, taps, errors, crashes, feedback, and task progress.
673
+ */
674
+ declare class EventTracker implements IEventTracker {
675
+ private storage;
676
+ private sessionId;
677
+ private captureFlags;
678
+ constructor(storage: IStorage, captureFlags?: Partial<CaptureFlags>);
679
+ /**
680
+ * Set the current session ID.
681
+ * Must be called before tracking events.
682
+ *
683
+ * @param sessionId - The active session ID
684
+ */
685
+ setSessionId(sessionId: string): void;
686
+ /**
687
+ * Track a screen view event.
688
+ * Gated by captureScreenViews flag.
689
+ *
690
+ * @param screenName - Name or route of the screen being viewed
691
+ * @param metadata - Optional additional metadata
692
+ */
693
+ trackScreenView(screenName: string, metadata?: Record<string, any>): Promise<void>;
694
+ /**
695
+ * Track a tap/click event.
696
+ * Gated by captureTapEvents flag.
697
+ *
698
+ * @param screenName - Name of the screen where the tap occurred
699
+ * @param elementId - Optional ID of the tapped element
700
+ */
701
+ trackTap(screenName: string, elementId?: string): Promise<void>;
702
+ /**
703
+ * Track a custom event.
704
+ *
705
+ * @param eventType - Type of the event
706
+ * @param metadata - Optional event metadata
707
+ */
708
+ trackEvent(eventType: string, metadata?: Record<string, any>): Promise<void>;
709
+ /**
710
+ * Track an error event.
711
+ * Gated by captureErrors flag.
712
+ *
713
+ * @param message - Error message
714
+ * @param stack - Optional stack trace
715
+ */
716
+ trackError(message: string, stack?: string): Promise<void>;
717
+ /**
718
+ * Track a crash event.
719
+ * Gated by captureCrashes flag.
720
+ *
721
+ * @param message - Crash message
722
+ * @param stack - Stack trace
723
+ */
724
+ trackCrash(message: string, stack: string): Promise<void>;
725
+ /**
726
+ * Track a feedback submission.
727
+ *
728
+ * @param content - Feedback content
729
+ * @param rating - Optional numeric rating
730
+ */
731
+ trackFeedback(content: string, rating?: number): Promise<void>;
732
+ /**
733
+ * Track task start event.
734
+ *
735
+ * @param taskId - Unique task identifier
736
+ * @param title - Task title
737
+ */
738
+ trackTaskStart(taskId: string, title: string): Promise<void>;
739
+ /**
740
+ * Track task completion event.
741
+ *
742
+ * @param taskId - Unique task identifier
743
+ */
744
+ trackTaskComplete(taskId: string): Promise<void>;
745
+ /**
746
+ * Store a bug report (error or crash).
747
+ *
748
+ * @param severity - Severity level ('error' or 'crash')
749
+ * @param message - Error/crash message
750
+ * @param stack - Optional stack trace
751
+ */
752
+ private storeBugReport;
753
+ /**
754
+ * Get event counts for a time period.
755
+ * Internal method for metrics aggregation.
756
+ *
757
+ * @param start - Start timestamp
758
+ * @param end - End timestamp
759
+ * @returns Map of event types to counts
760
+ */
761
+ getEventCounts(start: number, end: number): Promise<Record<string, number>>;
762
+ /**
763
+ * Get unique screen names for a time period.
764
+ * Internal method for metrics aggregation.
765
+ *
766
+ * @param start - Start timestamp
767
+ * @param end - End timestamp
768
+ * @returns Array of unique screen names
769
+ */
770
+ getUniqueScreens(start: number, end: number): Promise<string[]>;
771
+ }
772
+
773
+ /**
774
+ * Validation constants for quality assessment.
775
+ */
776
+ declare const ValidationConstants: {
777
+ minActiveMinutes: number;
778
+ minUniqueScreens: number;
779
+ maxTapsPerMinute: number;
780
+ minSessions: number;
781
+ };
782
+ /**
783
+ * Configuration for MetricsAggregator.
784
+ */
785
+ interface MetricsAggregatorConfig {
786
+ projectId: string;
787
+ testerId: string;
788
+ deviceId: string;
789
+ deviceMetadata: DeviceMetadata;
790
+ appMetadata: AppMetadata;
791
+ }
792
+ /**
793
+ * Metrics aggregator for generating weekly summaries.
794
+ *
795
+ * Aggregates session data, events, feedback, tasks, and bug reports
796
+ * into a comprehensive weekly summary for submission.
797
+ */
798
+ declare class MetricsAggregator {
799
+ private storage;
800
+ private config;
801
+ constructor(storage: IStorage, config: MetricsAggregatorConfig);
802
+ /**
803
+ * Aggregate a weekly summary for the past 7 days.
804
+ *
805
+ * @returns Promise resolving to the generated WeeklySummary
806
+ */
807
+ aggregateWeeklySummary(): Promise<WeeklySummary>;
808
+ /**
809
+ * Aggregate a summary for a specific time period.
810
+ *
811
+ * @param startTime - Start timestamp (milliseconds)
812
+ * @param endTime - End timestamp (milliseconds)
813
+ * @returns Promise resolving to the generated WeeklySummary
814
+ */
815
+ aggregateSummaryForPeriod(startTime: number, endTime: number): Promise<WeeklySummary>;
816
+ /**
817
+ * Store a weekly summary in the local database.
818
+ *
819
+ * @param summary - The summary to store
820
+ */
821
+ storeSummary(summary: WeeklySummary): Promise<void>;
822
+ /**
823
+ * Get pending summaries from the local database.
824
+ *
825
+ * @returns Array of pending WeeklySummary objects
826
+ */
827
+ getPendingSummaries(): Promise<WeeklySummary[]>;
828
+ /**
829
+ * Update summary status.
830
+ *
831
+ * @param summaryId - ID of the summary
832
+ * @param status - New status
833
+ */
834
+ updateSummaryStatus(summaryId: string, status: string): Promise<void>;
835
+ private getSessions;
836
+ private getEventCounts;
837
+ private getUniqueScreens;
838
+ private getFeedbackStats;
839
+ private getTaskStats;
840
+ private getBugReportStats;
841
+ private calculateQualityFlags;
842
+ private generateIntegrityHash;
843
+ private calculateEstimatedPayout;
844
+ }
845
+
846
+ declare class Outbox {
847
+ private storage;
848
+ private apiClient;
849
+ private draining;
850
+ constructor(storage: IStorage, apiClient?: IApiClient);
851
+ initSchema(): Promise<void>;
852
+ recoverInFlight(): Promise<void>;
853
+ /** Enqueue a bug_report item; returns the local UUID immediately. */
854
+ enqueueSync(type: 'bug_report' | 'submission', payload: unknown): string;
855
+ /** Enqueue and wait for the DB insert to complete (for async callers). */
856
+ enqueue(type: 'bug_report' | 'submission', payload: unknown): Promise<string>;
857
+ private _insertRow;
858
+ /**
859
+ * Map DB state → OutboxItemStatus.
860
+ * Returns null when the item is not found (means it was sent and deleted).
861
+ */
862
+ getStatus(localId: string): Promise<OutboxItemStatus | null>;
863
+ /**
864
+ * Schedule a drain on the next microtask. Fire-and-forget.
865
+ * Callers (submitBugReport / createSubmission) call this after enqueue.
866
+ */
867
+ scheduleDrain(): void;
868
+ /**
869
+ * Process all pending outbox items. Idempotent — safe to call concurrently
870
+ * (guarded by draining flag). No-ops when apiClient is absent.
871
+ */
872
+ drain(): Promise<void>;
873
+ private _drainLoop;
874
+ private _processRow;
875
+ private _uploadBugReport;
876
+ private _uploadSubmission;
877
+ /** Register a window.online listener that triggers a drain. */
878
+ registerOnlineListener(): void;
879
+ private _extractStatusCode;
880
+ }
881
+
882
+ /**
883
+ * Manages a locally-generated UUIDv4 device id persisted in storage.
884
+ *
885
+ * Contract: invariants.device_id
886
+ * - Generates a new id on first use.
887
+ * - Rotates (new id) after 30 days.
888
+ * - config.deviceId overrides this (passed through, not persisted here).
889
+ */
890
+ declare class DeviceIdManager {
891
+ private storage;
892
+ constructor(storage: IStorage);
893
+ /**
894
+ * Ensure the sdk_meta table exists. Schema is the adapter's responsibility;
895
+ * this is now a no-op kept for backwards-compatible call-sites.
896
+ */
897
+ initSchema(): Promise<void>;
898
+ /**
899
+ * Return the stored device id, creating or rotating it as needed.
900
+ *
901
+ * Rotation policy: if the id is older than 30 days, a new one is generated.
902
+ */
903
+ getOrCreate(): Promise<string>;
904
+ private _upsert;
905
+ }
906
+
907
+ export { DeviceIdManager, EventTracker, MetricsAggregator, Outbox, SessionManager, TesterPayKit, ValidationConstants };
908
+ export type { CaptureFlags, MetricsAggregatorConfig, SessionEndReason, TesterPayKitConfig };