@testerpaykit/api-client 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.
package/dist/index.mjs ADDED
@@ -0,0 +1,528 @@
1
+ // src/TesterPayKitApiClient.ts
2
+ import axios from "axios";
3
+ import {
4
+ TokenManager
5
+ } from "@testerpaykit/core";
6
+ var TesterPayKitApiClient = class {
7
+ constructor(config) {
8
+ this.apiKey = config.apiKey;
9
+ this.tokenManager = config.tokenManager || new TokenManager();
10
+ this.client = axios.create({
11
+ baseURL: config.baseURL || "https://api.testerpaykit.com",
12
+ headers: {
13
+ "Content-Type": "application/json",
14
+ "X-API-Key": this.apiKey
15
+ }
16
+ });
17
+ this.setupInterceptors();
18
+ }
19
+ /**
20
+ * Setup request/response interceptors for JWT authentication.
21
+ */
22
+ setupInterceptors() {
23
+ this.client.interceptors.request.use(async (config) => {
24
+ const token = await this.tokenManager.ensureValidToken();
25
+ if (token) {
26
+ config.headers.Authorization = `Bearer ${token}`;
27
+ }
28
+ return config;
29
+ });
30
+ this.client.interceptors.response.use(
31
+ (response) => response,
32
+ async (error) => {
33
+ if (error.response?.status === 401) {
34
+ this.tokenManager.clear();
35
+ }
36
+ return Promise.reject(error);
37
+ }
38
+ );
39
+ }
40
+ /**
41
+ * Authenticate a tester with email/password.
42
+ * Stores tokens in TokenManager and sets up refresh callback.
43
+ */
44
+ async login(request) {
45
+ const response = await this.client.post("/auth/login", request);
46
+ if (response.data.accessToken && response.data.refreshToken) {
47
+ this.tokenManager.setTokens(response.data.accessToken, response.data.refreshToken);
48
+ this.tokenManager.setRefreshCallback(async (refreshToken) => {
49
+ const refreshResponse = await this.refreshToken(refreshToken);
50
+ return refreshResponse.accessToken;
51
+ });
52
+ }
53
+ return response.data;
54
+ }
55
+ /**
56
+ * Refresh access token using refresh token.
57
+ * Updates TokenManager with new access token.
58
+ */
59
+ async refreshToken(refreshToken) {
60
+ const response = await this.client.post("/v1/auth/refresh", {
61
+ refreshToken
62
+ });
63
+ if (response.data.accessToken) {
64
+ this.tokenManager.setTokens(response.data.accessToken, refreshToken);
65
+ }
66
+ return response.data;
67
+ }
68
+ /**
69
+ * Submit a weekly summary for payment.
70
+ * POST /v1/submissions
71
+ */
72
+ async submitSummary(summary) {
73
+ const response = await this.client.post(
74
+ "/v1/submissions",
75
+ summary
76
+ );
77
+ return response.data;
78
+ }
79
+ /**
80
+ * Get submissions for the authenticated tester.
81
+ * GET /v1/submissions
82
+ */
83
+ async getPendingSubmissions(params) {
84
+ const response = await this.client.get("/v1/submissions", { params });
85
+ return response.data;
86
+ }
87
+ /**
88
+ * Fetch the set of submission IDs the server already holds.
89
+ * GET /v1/submissions?limit=100
90
+ * Soft-fail: returns empty set on any error.
91
+ */
92
+ async fetchServerSubmissionIds() {
93
+ try {
94
+ const submissions = await this.getPendingSubmissions({ limit: 100 });
95
+ return new Set(submissions.map((s) => s.id));
96
+ } catch {
97
+ return /* @__PURE__ */ new Set();
98
+ }
99
+ }
100
+ /**
101
+ * Set access token manually (for testing or external auth flows).
102
+ */
103
+ setAccessToken(token) {
104
+ this.tokenManager.setTokens(token, "");
105
+ }
106
+ /**
107
+ * Acquire an anonymous tester JWT by trading a {projectId, code}
108
+ * pair for an access + refresh token. No email/password required.
109
+ *
110
+ * Server-side this hits POST /auth/tester/anonymous; a synthetic
111
+ * email derived from {projectId, code} is the dedup key so the
112
+ * same code resolves to the same tester row every time.
113
+ */
114
+ async loginAnonymous(projectId, code) {
115
+ const response = await this.client.post(
116
+ "/auth/tester/anonymous",
117
+ { projectId, code }
118
+ );
119
+ if (response.data.accessToken) {
120
+ this.tokenManager.setTokens(
121
+ response.data.accessToken,
122
+ response.data.refreshToken
123
+ );
124
+ }
125
+ return { ...response.data, testerId: response.data.tester?.id };
126
+ }
127
+ /**
128
+ * Request a passwordless magic-link sign-in for a tester (or coordinator).
129
+ * POST /auth/magic-link/request. The server emails a single-use link; when
130
+ * `returnUrl` is a first-party *.moinsen.dev origin the link returns there
131
+ * with the token, otherwise it points at the console. `country` (DE/AT/CH)
132
+ * enables open tester self-signup for unknown emails. Always resolves; the
133
+ * response is intentionally generic (no user enumeration).
134
+ */
135
+ async requestMagicLink(input) {
136
+ const response = await this.client.post("/auth/magic-link/request", {
137
+ email: input.email,
138
+ ...input.returnUrl && { returnUrl: input.returnUrl },
139
+ ...input.country && { country: input.country },
140
+ ...input.then && { then: input.then }
141
+ });
142
+ return response.data;
143
+ }
144
+ /**
145
+ * Consume a magic-link token (from the returned URL). POST
146
+ * /auth/magic-link/consume. On success stores the minted JWTs and returns
147
+ * the tester/coordinator payload.
148
+ */
149
+ async consumeMagicLink(token) {
150
+ const response = await this.client.post("/auth/magic-link/consume", { token });
151
+ const data = response.data;
152
+ if (data.accessToken) {
153
+ this.tokenManager.setTokens(data.accessToken, data.refreshToken ?? "");
154
+ }
155
+ return data;
156
+ }
157
+ /**
158
+ * Submit a bug report to the server. Hits
159
+ * POST /v1/testers/me/bug-reports with the tester JWT already
160
+ * attached by the request interceptor (call loginAnonymous /
161
+ * loginCoordinator first).
162
+ *
163
+ * Server-side enum constraints are enforced — see the typedef
164
+ * for valid {type, severity, category} values. Sending an
165
+ * out-of-band string returns 500 with a detail message in
166
+ * development mode.
167
+ */
168
+ async submitBugReport(payload, options) {
169
+ const headers = {};
170
+ if (options?.idempotencyKey) {
171
+ headers["X-Idempotency-Key"] = options.idempotencyKey;
172
+ }
173
+ const response = await this.client.post(
174
+ "/v1/testers/me/bug-reports",
175
+ payload,
176
+ Object.keys(headers).length ? { headers } : void 0
177
+ );
178
+ return response.data;
179
+ }
180
+ /**
181
+ * List the bug reports this tester submitted (newest first), with their
182
+ * current status. Hits GET /v1/testers/me/bug-reports. Mirrors the
183
+ * Flutter SDK's getMyBugReports — powers the "Meine Bugs" screen.
184
+ */
185
+ async listMyBugReports(params) {
186
+ const response = await this.client.get(
187
+ "/v1/testers/me/bug-reports",
188
+ { params }
189
+ );
190
+ return response.data;
191
+ }
192
+ /**
193
+ * The tester's in-app notifications (newest first) + the unread count.
194
+ * GET /v1/testers/me/notifications. Mirrors the Flutter SDK's
195
+ * getMyNotifications — powers the "Nachrichten" inbox.
196
+ */
197
+ async getMyNotifications(params) {
198
+ const response = await this.client.get(
199
+ "/v1/testers/me/notifications",
200
+ { params }
201
+ );
202
+ return response.data;
203
+ }
204
+ /**
205
+ * Mark notifications read. Pass an `id` to mark one, or omit to mark all.
206
+ * POST /v1/testers/me/notifications/read. Returns the new unread count.
207
+ */
208
+ async markNotificationsRead(params) {
209
+ const response = await this.client.post(
210
+ "/v1/testers/me/notifications/read",
211
+ params?.id ? { id: params.id } : {}
212
+ );
213
+ return response.data.unreadCount;
214
+ }
215
+ /**
216
+ * Attach a file (screenshot, log, voice note) to an already-
217
+ * submitted bug report. Hits POST /v1/testers/me/bug-reports/
218
+ * [id]/attachments. Base64-encoded payload, server stores blob
219
+ * + returns metadata.
220
+ */
221
+ async attachToBugReport(bugReportId, attachment) {
222
+ const response = await this.client.post(
223
+ `/v1/testers/me/bug-reports/${bugReportId}/attachments`,
224
+ attachment
225
+ );
226
+ return response.data;
227
+ }
228
+ /**
229
+ * Start a server-side tester session. The API uses snake_case
230
+ * field names here because this maps directly to the sessions
231
+ * table and existing Flutter SDK contract.
232
+ */
233
+ async startTesterSession(input) {
234
+ const body = {
235
+ project_id: input.projectId,
236
+ ...input.deviceInfo && { device_info: input.deviceInfo },
237
+ ...input.appVersion && { app_version: input.appVersion },
238
+ ...input.sdkVersion && { sdk_version: input.sdkVersion },
239
+ ...input.deviceId && { device_id: input.deviceId }
240
+ };
241
+ const response = await this.client.post("/v1/testers/sessions", body);
242
+ return response.data.session;
243
+ }
244
+ /** End a server-side tester session with optional counters. */
245
+ async endTesterSession(input) {
246
+ await this.client.put(`/v1/testers/sessions/${input.sessionId}`, {
247
+ ended_at: (input.endedAt ?? /* @__PURE__ */ new Date()).toISOString(),
248
+ ...input.bugsFound != null && { bugs_found: input.bugsFound },
249
+ ...input.tasksCompleted != null && {
250
+ tasks_completed: input.tasksCompleted
251
+ },
252
+ ...input.endReason && { end_reason: input.endReason },
253
+ ...input.foregroundSeconds != null && {
254
+ foreground_seconds: input.foregroundSeconds
255
+ }
256
+ });
257
+ }
258
+ /**
259
+ * Add one or more timeline events to an active tester session.
260
+ * Hits POST /v1/testers/sessions/:id/events in batch mode.
261
+ */
262
+ async addSessionEvents(sessionId, events) {
263
+ const response = await this.client.post(
264
+ `/v1/testers/sessions/${sessionId}/events`,
265
+ {
266
+ events: events.map((event) => ({
267
+ event_type: event.eventType,
268
+ ...event.eventData && { event_data: event.eventData },
269
+ ...event.screenRoute && { screen_route: event.screenRoute },
270
+ ...event.timestamp && {
271
+ timestamp: formatTimestamp(event.timestamp)
272
+ }
273
+ }))
274
+ }
275
+ );
276
+ return response.data;
277
+ }
278
+ /**
279
+ * Add one or more breadcrumbs to an active tester session.
280
+ * Hits POST /v1/testers/sessions/:id/breadcrumbs in batch mode.
281
+ */
282
+ async addSessionBreadcrumbs(sessionId, breadcrumbs) {
283
+ const response = await this.client.post(
284
+ `/v1/testers/sessions/${sessionId}/breadcrumbs`,
285
+ {
286
+ breadcrumbs: breadcrumbs.map((breadcrumb) => ({
287
+ breadcrumb_type: breadcrumb.breadcrumbType,
288
+ message: breadcrumb.message,
289
+ ...breadcrumb.metadata && { metadata: breadcrumb.metadata },
290
+ ...breadcrumb.timestamp && {
291
+ timestamp: formatTimestamp(breadcrumb.timestamp)
292
+ }
293
+ }))
294
+ }
295
+ );
296
+ return response.data;
297
+ }
298
+ /**
299
+ * Fetch the tester's assigned tasks. Server-side filter by
300
+ * status / project_id. Hits GET /v1/testers/tasks.
301
+ */
302
+ async getMyTasks(filter = {}) {
303
+ const response = await this.client.get(
304
+ "/v1/testers/tasks",
305
+ { params: filter }
306
+ );
307
+ return response.data;
308
+ }
309
+ /**
310
+ * Mark a task assignment in-progress. PUT /v1/testers/tasks/{id}/start.
311
+ * The server only completes an in-progress task, so callers start first.
312
+ */
313
+ async startTaskAssignment(assignmentId) {
314
+ await this.client.put(`/v1/testers/tasks/${assignmentId}/start`);
315
+ }
316
+ /** Complete a task assignment. PUT /v1/testers/tasks/{id}/complete. */
317
+ async completeTaskAssignment(assignmentId) {
318
+ await this.client.put(`/v1/testers/tasks/${assignmentId}/complete`);
319
+ }
320
+ /**
321
+ * Enroll the authenticated tester in a project. Idempotent —
322
+ * a second enroll on the same project resolves to the existing
323
+ * enrollment row. POST /v1/testers/projects/:id/enroll.
324
+ */
325
+ async enrollInProject(projectId) {
326
+ const response = await this.client.post(
327
+ `/v1/testers/projects/${projectId}/enroll`
328
+ );
329
+ return response.data;
330
+ }
331
+ /**
332
+ * Reverse of enrollInProject. POST /v1/testers/projects/:id/unenroll.
333
+ */
334
+ async unenrollFromProject(projectId) {
335
+ await this.client.post(`/v1/testers/projects/${projectId}/unenroll`);
336
+ }
337
+ /**
338
+ * Tester profile (handle, points, rating, etc.).
339
+ * GET /v1/testers/me/profile.
340
+ */
341
+ async getMyProfile() {
342
+ const response = await this.client.get(
343
+ "/v1/testers/me/profile"
344
+ );
345
+ return response.data;
346
+ }
347
+ /** GET /v1/testers/me/points — current point balance + breakdown. */
348
+ async getMyPoints() {
349
+ const response = await this.client.get(
350
+ "/v1/testers/me/points"
351
+ );
352
+ return response.data;
353
+ }
354
+ /** GET /v1/testers/earnings/summary — totals, current balance, this month. */
355
+ async getEarningsSummary() {
356
+ const response = await this.client.get(
357
+ "/v1/testers/earnings/summary"
358
+ );
359
+ return response.data;
360
+ }
361
+ /** GET /v1/testers/earnings/payouts — paginated payout history. */
362
+ async getMyPayouts(params) {
363
+ const response = await this.client.get("/v1/testers/earnings/payouts", { params });
364
+ return response.data;
365
+ }
366
+ /**
367
+ * GET /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base
368
+ *
369
+ * Lists the markdown docs the coordinator attached to this project.
370
+ * Feeds the SDK widget's "ask a question about the project" flow.
371
+ * No content in the list response — call `getKnowledgeFile` for the
372
+ * full body. Accepts either the project's bundle id (what the host
373
+ * SDK already knows from its build) or its UUID.
374
+ */
375
+ async listKnowledgeFiles(bundleIdOrProjectId) {
376
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
377
+ const response = await this.client.get(
378
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base`
379
+ );
380
+ return response.data;
381
+ }
382
+ /**
383
+ * GET /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base/:fileId
384
+ *
385
+ * Fetches one markdown doc's full content. Caller is expected to
386
+ * scope the fetch — passing the same `bundleIdOrProjectId` that
387
+ * `listKnowledgeFiles` was called with is the natural pattern.
388
+ */
389
+ async getKnowledgeFile(bundleIdOrProjectId, fileId) {
390
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
391
+ const fileSegment = encodeURIComponent(fileId);
392
+ const response = await this.client.get(
393
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base/${fileSegment}`
394
+ );
395
+ return response.data.file;
396
+ }
397
+ /**
398
+ * POST /v1/testers/me/projects/:bundleIdOrUuid/knowledge-base/query
399
+ *
400
+ * RAG over the project's knowledge-base markdown files. Embeds the
401
+ * question, retrieves top-K nearest chunks via pgvector cosine
402
+ * similarity, and asks gpt-4o-mini to synthesise an answer that
403
+ * STRICTLY cites those chunks. Answer language tracks the
404
+ * question (English / German).
405
+ *
406
+ * Returns {answer, citations}. The widget UI surfaces the answer
407
+ * + a "Sources" disclosure with the citations so the tester knows
408
+ * which doc the answer came from. `citations[*].content` is the
409
+ * exact span the model saw — ready to render as a snippet.
410
+ */
411
+ async askKnowledgeBase(bundleIdOrProjectId, question) {
412
+ const projectSegment = encodeURIComponent(bundleIdOrProjectId);
413
+ const response = await this.client.post(
414
+ `/v1/testers/me/projects/${projectSegment}/knowledge-base/query`,
415
+ { question }
416
+ );
417
+ return response.data;
418
+ }
419
+ /**
420
+ * GET /v1/tasks
421
+ * List available task presets for a project.
422
+ */
423
+ async getTasks(params) {
424
+ const response = await this.client.get("/v1/tasks", { params });
425
+ return response.data;
426
+ }
427
+ /**
428
+ * POST /v1/testers/me/devices
429
+ * Register (or upsert) this device for push notifications.
430
+ * Server keys on device_token — a second POST with the same token updates the row.
431
+ */
432
+ async registerDevice(input) {
433
+ const body = {
434
+ device_token: input.deviceToken,
435
+ device_type: input.deviceType
436
+ };
437
+ if (input.deviceModel) body.device_model = input.deviceModel;
438
+ if (input.osVersion) body.os_version = input.osVersion;
439
+ if (input.appVersion) body.app_version = input.appVersion;
440
+ const response = await this.client.post(
441
+ "/v1/testers/me/devices",
442
+ body
443
+ );
444
+ return response.data;
445
+ }
446
+ /**
447
+ * POST /v1/session-feedback
448
+ * Submit end-of-session feedback (rating, comments, etc.).
449
+ */
450
+ async submitSessionEndFeedback(payload) {
451
+ const response = await this.client.post(
452
+ "/v1/session-feedback",
453
+ payload
454
+ );
455
+ return response.data;
456
+ }
457
+ /**
458
+ * Upload an attachment directly (not tied to a specific bug report).
459
+ * POST /v1/attachments — alternate path from the contract alongside
460
+ * /v1/testers/me/bug-reports/{id}/attachments.
461
+ */
462
+ async uploadAttachment(attachment) {
463
+ const response = await this.client.post(
464
+ "/v1/attachments",
465
+ attachment
466
+ );
467
+ return response.data;
468
+ }
469
+ /**
470
+ * GET /v1/testers/me/retests
471
+ * List bug reports assigned to this tester for re-verification.
472
+ */
473
+ async getMyRetests(params) {
474
+ const response = await this.client.get(
475
+ "/v1/testers/me/retests",
476
+ { params }
477
+ );
478
+ return response.data;
479
+ }
480
+ /**
481
+ * POST /v1/testers/me/retests/{bugId}/verify
482
+ * Mark a retest as verified (bug is fixed).
483
+ */
484
+ async verifyRetest(bugId) {
485
+ await this.client.post(`/v1/testers/me/retests/${bugId}/verify`);
486
+ }
487
+ /**
488
+ * POST /v1/testers/me/retests/{bugId}/reopen
489
+ * Reopen a retest (bug is still present), optionally with a reason.
490
+ */
491
+ async reopenRetest(bugId, reason) {
492
+ await this.client.post(`/v1/testers/me/retests/${bugId}/reopen`, {
493
+ ...reason ? { reason } : {}
494
+ });
495
+ }
496
+ /**
497
+ * POST /v1/testers/me/bug-reports/voice-extract
498
+ * Contract: wire.bug_reports.voiceExtractBugFields
499
+ *
500
+ * Sends base64-encoded audio to the server. The server runs Whisper
501
+ * (transcription) + gpt-4o-mini (structured extraction) and returns
502
+ * pre-filled bug-report fields in the tester's language.
503
+ *
504
+ * Wire body uses snake_case per contract. Timeout is 60 s because
505
+ * Whisper + Chat round-trip can take 10-30 s on long recordings.
506
+ */
507
+ async voiceExtractBugFields(request) {
508
+ const body = {
509
+ audio_base64: request.audioBase64,
510
+ mime_type: request.mimeType
511
+ };
512
+ if (request.sourceLanguage) body.source_language = request.sourceLanguage;
513
+ if (request.projectId) body.project_id = request.projectId;
514
+ if (request.preClassification) body.pre_classification = request.preClassification;
515
+ const response = await this.client.post(
516
+ "/v1/testers/me/bug-reports/voice-extract",
517
+ body,
518
+ { timeout: 6e4 }
519
+ );
520
+ return response.data;
521
+ }
522
+ };
523
+ function formatTimestamp(timestamp) {
524
+ return timestamp instanceof Date ? timestamp.toISOString() : timestamp;
525
+ }
526
+ export {
527
+ TesterPayKitApiClient
528
+ };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@testerpaykit/api-client",
3
+ "version": "1.1.0",
4
+ "description": "API client for TesterPayKit backend",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "axios": "^1.6.2",
17
+ "@testerpaykit/core": "1.0.1"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "^20.10.0",
21
+ "tsup": "^8.0.1",
22
+ "typescript": "^5.3.3",
23
+ "vitest": "^1.0.4"
24
+ },
25
+ "keywords": [
26
+ "testerpaykit",
27
+ "api",
28
+ "client",
29
+ "typescript"
30
+ ],
31
+ "author": "TesterPayKit Team",
32
+ "license": "MIT",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup src/index.ts --format cjs,esm --dts",
38
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
39
+ "test": "vitest",
40
+ "lint": "eslint src --ext .ts"
41
+ }
42
+ }