@timeback/powerpath 0.2.1 → 0.2.2-beta.20260331190459

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.d.ts CHANGED
@@ -1,1177 +1,1522 @@
1
- import * as _timeback_internal_client_infra from '@timeback/internal-client-infra';
2
- import { PowerPathPaths, RequestOptions, PaginatedResponse, ClientConfig, TransportOnlyConfig, ProviderClientConfig, BaseTransportConfig, Paginator as Paginator$1, ListParams, ProviderRegistry, TimebackProvider, AuthCheckResult, BaseTransport } from '@timeback/internal-client-infra';
3
- export { AuthCheckResult, EnvAuth, Environment, ExplicitAuth, ListParams, PageResult } from '@timeback/internal-client-infra';
1
+ import { ExternalTestCreateResponse, InternalTestCreateResponse, CreateAttemptResponse, FinalizeAssessmentResponse, GetAssessmentProgressResponse, GetAttemptsResponse, GetNextQuestionResponse, ImportExternalResultsResponse, MakeExternalTestAssignmentResponse, ResetAttemptResponse, TestOutResponse, UpdateStudentQuestionResponseResult, LessonPlanCreateResponse, LessonPlanResponse, LessonPlanOperationsResponse, LessonPlanOperationResult, LessonPlanSyncResult, LessonPlanCourseSyncResult, CourseProgressResponse, UpdateStudentItemResponseResult, GetAllPlacementTestsResponse, GetCurrentLevelResponse, GetNextPlacementTestResponse, GetSubjectProgressResponse, ResetPlacementResponse, RenderConfigUpsertResponse, RenderConfigGetResponse, RenderConfigDeleteResponse, ScreeningResultsResponse, ScreeningSessionResponse, ScreeningResetSessionResponse, ScreeningAssignTestResponse, SyllabusResponse, TestAssignment, TestAssignmentsListResponse, AssignmentResult, BulkResult, GetTestOutEligibilityResponse, MakeExternalStudentTestOutAssignmentResponse } from '@timeback/types/protocols/powerpath';
2
+ export { AssignmentResult, Attempt, BulkResult, CourseProgressResponse, CreateAttemptResponse, ExternalTestCapableLessonType, ExternalTestCreateResponse, FinalizeAssessmentResponse, GetAllPlacementTestsResponse, GetAssessmentProgressResponse, GetAttemptsResponse, GetCurrentLevelResponse, GetNextPlacementTestResponse, GetNextQuestionResponse, GetSubjectProgressResponse, GetTestOutEligibilityResponse, ImportExternalResultsResponse, InternalTestCreateResponse, LessonPlanCourseSyncResult, LessonPlanCreateResponse, LessonPlanOperation, LessonPlanOperationResult, LessonPlanOperationsResponse, LessonPlanResponse, LessonPlanSyncResult, MakeExternalStudentTestOutAssignmentResponse, MakeExternalTestAssignmentResponse, PaginationMeta, PowerPath100ProgressResponse, PowerPath100UpdateResponseResult, PowerPathLessonType, PowerPathQuestionContent, PowerPathQuestionDifficulty, PowerPathQuestionResult, PowerPathTestQuestion, QuizLikeLessonType, ResetAttemptResponse, ResetPlacementResponse, ResponseResult, ResponseResultFeedback, ScoreStatus, ScreeningAssignTestResponse, ScreeningResetSessionResponse, ScreeningResultsResponse, ScreeningSessionResponse, StandardProgressResponse, StandardUpdateResponseResult, SyllabusResponse, TestAssignment, TestAssignmentStatus, TestAssignmentsListResponse, TestOutResponse, UpdateStudentItemResponseResult, UpdateStudentQuestionResponseResult } from '@timeback/types/protocols/powerpath';
3
+ import { CreateExternalPlacementTestInput, CreateExternalTestOutInput, CreateInternalTestInput, CreateNewAttemptInput, FinalStudentAssessmentResponseInput, GetAssessmentProgressParams, GetAttemptsParams, GetNextQuestionParams, ImportExternalTestAssignmentResultsParams, MakeExternalTestAssignmentInput, ResetAttemptInput, TestOutParams, UpdateStudentQuestionResponseInput, LessonPlansCreateInput, LessonPlanOperationsInput, LessonPlanUpdateStudentItemResponseInput, PlacementQueryParams, PlacementResetUserPlacementInput, RenderConfigUpsertInput, ScreeningResetSessionInput, ScreeningAssignTestInput, SyllabusQueryParams, TestAssignmentsListParams, TestAssignmentsCreateInput, TestAssignmentsUpdateInput, TestAssignmentsAdminParams, TestAssignmentsBulkInput, TestAssignmentsImportInput, MakeExternalStudentTestOutAssignmentInput } from '@timeback/types/zod';
4
+ export { CreateExternalPlacementTestInput, CreateExternalTestOutInput, CreateInternalTestInput, CreateNewAttemptInput, FinalStudentAssessmentResponseInput, GetAssessmentProgressParams, GetAttemptsParams, GetNextQuestionParams, ImportExternalTestAssignmentResultsParams, LessonPlanOperationInput, LessonPlanOperationsInput, LessonPlanUpdateStudentItemResponseInput, LessonPlansCreateInput, MakeExternalStudentTestOutAssignmentInput, MakeExternalTestAssignmentInput, PlacementQueryParams, PlacementResetUserPlacementInput, ResetAttemptInput, ScreeningAssignTestInput, ScreeningResetSessionInput, SyllabusQueryParams, TestAssignmentsAdminParams, TestAssignmentsBulkInput, TestAssignmentsCreateInput, TestAssignmentsImportInput, TestAssignmentsListParams, TestAssignmentsUpdateInput, TestOutParams, UpdateStudentQuestionResponseInput } from '@timeback/types/zod';
4
5
 
5
6
  /**
6
- * PowerPath Base Types
7
+ * Interface for obtaining OAuth2 access tokens.
7
8
  *
8
- * Common types and enums for PowerPath API responses.
9
+ * Implementations handle token caching and refresh automatically.
9
10
  */
10
-
11
- // ═══════════════════════════════════════════════════════════════════════════════
12
- // ENUMS
13
- // ═══════════════════════════════════════════════════════════════════════════════
11
+ interface TokenProvider {
12
+ /**
13
+ * Get a valid access token.
14
+ *
15
+ * Returns a cached token if still valid, otherwise fetches a new one.
16
+ *
17
+ * @returns A valid access token string
18
+ * @throws {Error} If token acquisition fails
19
+ */
20
+ getToken(): Promise<string>;
21
+ /**
22
+ * Invalidate the cached token.
23
+ *
24
+ * Forces the next getToken() call to fetch a fresh token.
25
+ * Should be called when a request fails with 401 Unauthorized.
26
+ *
27
+ * Optional - not all implementations may support invalidation.
28
+ */
29
+ invalidate?(): void;
30
+ }
14
31
 
15
32
  /**
16
- * Test assignment status values.
33
+ * All supported platforms.
17
34
  */
18
- type TestAssignmentStatus =
19
- | 'assigned'
20
- | 'in_progress'
21
- | 'completed'
22
- | 'failed'
23
- | 'expired'
24
- | 'cancelled'
35
+ declare const PLATFORMS: readonly ["BEYOND_AI", "LEARNWITH_AI"];
25
36
 
26
37
  /**
27
- * Lesson types for PowerPath assessments.
38
+ * Type Definitions for `@timeback/internal-logger`
39
+ *
40
+ * Central type definitions used across all logger components.
41
+ * These types define the contract between the logger, formatters, and consumers.
28
42
  */
29
- type PowerPathLessonType =
30
- | 'powerpath-100'
31
- | 'quiz'
32
- | 'test-out'
33
- | 'placement'
34
- | 'unit-test'
35
- | 'alpha-read-article'
36
-
37
43
  /**
38
- * Lesson types that behave like quizzes (static tests with finalization).
44
+ * Log severity levels, ordered from least to most severe.
39
45
  *
40
- * These types can be finalized via `finalStudentAssessmentResponse`,
41
- * return score 0 while not finalized, and support both internal and external tests.
46
+ * - debug: Detailed diagnostic information for developers
47
+ * - info: General operational messages (app started, request received)
48
+ * - warn: Something unexpected but not breaking (deprecated API used)
49
+ * - error: Something failed (request failed, database connection lost)
42
50
  */
43
- type QuizLikeLessonType = 'quiz' | 'test-out' | 'placement' | 'unit-test'
44
-
51
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
45
52
  /**
46
- * Lesson types that support external test assignment via third-party tools.
53
+ * Runtime environments that determine how logs are formatted.
47
54
  *
48
- * These types can use `makeExternalTestAssignment` and
49
- * `importExternalTestAssignmentResults`.
55
+ * - terminal: Local development with colors and icons
56
+ * - ci: CI/CD pipelines with plain text (no ANSI codes)
57
+ * - production: JSON lines for log aggregation (DataDog, CloudWatch, etc.)
58
+ * - browser: Browser console with CSS styling
59
+ * - test: Test environment with no output
50
60
  */
51
- type ExternalTestCapableLessonType = 'test-out' | 'placement' | 'unit-test'
52
-
61
+ type Environment$2 = 'terminal' | 'ci' | 'production' | 'browser' | 'test';
53
62
  /**
54
- * Score status values for assessment attempts.
63
+ * Arbitrary key-value data attached to log entries.
64
+ *
65
+ * Context is merged into log output - in production it becomes top-level
66
+ * JSON fields, in terminal it's displayed as key=value pairs.
67
+ *
68
+ * @example
69
+ * log.info('User created', { userId: 123, email: 'foo@bar.com' })
55
70
  */
56
- type ScoreStatus =
57
- | 'exempt'
58
- | 'fully graded'
59
- | 'not submitted'
60
- | 'partially graded'
61
- | 'submitted'
62
-
71
+ type LogContext = Record<string, unknown>;
63
72
  /**
64
- * Question difficulty levels.
73
+ * Configuration options for creating a logger instance.
65
74
  */
66
- type PowerPathQuestionDifficulty = 'easy' | 'medium' | 'hard'
67
-
68
- // ═══════════════════════════════════════════════════════════════════════════════
69
- // PAGINATION
70
- // ═══════════════════════════════════════════════════════════════════════════════
75
+ interface LoggerOptions {
76
+ /**
77
+ * Logger scope/namespace for categorizing logs.
78
+ * Child loggers append to this with colons: "api" → "api:users"
79
+ */
80
+ scope?: string;
81
+ /**
82
+ * Minimum log level to output.
83
+ * Logs below this level are silently ignored.
84
+ * @default 'info' (or 'debug' if DEBUG env var is set)
85
+ */
86
+ minLevel?: LogLevel;
87
+ /**
88
+ * Override automatic environment detection.
89
+ * Useful for testing or forcing a specific format.
90
+ */
91
+ environment?: Environment$2;
92
+ /**
93
+ * Default context added to every log entry from this logger.
94
+ * Useful for request IDs, user IDs, etc.
95
+ */
96
+ defaultContext?: LogContext;
97
+ }
71
98
 
72
99
  /**
73
- * Pagination metadata from PowerPath list responses.
74
- */
75
- interface PaginationMeta {
76
- /** Total items across all pages */
77
- totalCount: number
78
- /** Total number of pages */
79
- pageCount: number
80
- /** Current page number (1-indexed) */
81
- pageNumber: number
82
- /**
83
- * Offset for the next page of results.
84
- *
85
- * This API uses offset pagination: request `offset` is the number of items to skip.
86
- * List responses also include an `offset` field; treat it as the server-provided
87
- * next offset (and fall back to `currentOffset + limit` when implementing iterators).
88
- */
89
- offset: number
90
- /** Items per page (default 100, max 3000) */
91
- limit: number
100
+ * Logger instance with environment-aware formatting.
101
+ *
102
+ * Instances are lightweight and can be created freely.
103
+ * Common pattern: one logger per module/component.
104
+ */
105
+ declare class Logger {
106
+ /** Namespace for this logger (e.g., "api", "api:users") */
107
+ private scope?;
108
+ /** Minimum level to output (logs below this are ignored) */
109
+ private minLevel;
110
+ /** The detected or configured environment */
111
+ private environment;
112
+ /** Function that formats and outputs log entries */
113
+ private formatter;
114
+ /** Context added to every log entry from this logger */
115
+ private defaultContext;
116
+ /**
117
+ * Create a new Logger instance.
118
+ *
119
+ * Usually you'd use createLogger() instead of new Logger().
120
+ */
121
+ constructor(options?: LoggerOptions);
122
+ /**
123
+ * Create a child logger with an additional scope segment.
124
+ *
125
+ * Child loggers inherit minLevel and defaultContext from parent.
126
+ * Scope is appended with a colon separator.
127
+ *
128
+ * @param scope - Additional scope segment to append
129
+ * @returns New Logger instance with extended scope
130
+ *
131
+ * @example
132
+ * const api = createLogger({ scope: 'api' })
133
+ * const users = api.child('users')
134
+ * users.info('Created') // scope: "api:users"
135
+ */
136
+ child(scope: string): Logger;
137
+ /**
138
+ * Create a logger with additional default context.
139
+ *
140
+ * The new context is merged with existing default context.
141
+ * Useful for adding request IDs, user IDs, etc.
142
+ *
143
+ * @param context - Additional context to include in all logs
144
+ * @returns New Logger instance with extended context
145
+ *
146
+ * @example
147
+ * const requestLog = log.withContext({ requestId: 'abc123' })
148
+ * requestLog.info('Processing') // requestId included automatically
149
+ */
150
+ withContext(context: LogContext): Logger;
151
+ /**
152
+ * Log a debug message.
153
+ *
154
+ * Use for detailed diagnostic information useful during development.
155
+ * These are typically filtered out in production.
156
+ *
157
+ * @param message - The log message
158
+ * @param context - Optional key-value context to include with the log
159
+ */
160
+ debug(message: string, context?: LogContext): void;
161
+ /**
162
+ * Log an info message.
163
+ *
164
+ * Use for general operational information.
165
+ * Examples: server started, request received, job completed.
166
+ *
167
+ * @param message - The log message
168
+ * @param context - Optional key-value context to include with the log
169
+ */
170
+ info(message: string, context?: LogContext): void;
171
+ /**
172
+ * Log a warning message.
173
+ *
174
+ * Use for unexpected but non-breaking issues.
175
+ * Examples: deprecated API used, retrying operation, approaching limit.
176
+ *
177
+ * @param message - The log message
178
+ * @param context - Optional key-value context to include with the log
179
+ */
180
+ warn(message: string, context?: LogContext): void;
181
+ /**
182
+ * Log an error message.
183
+ *
184
+ * Use for failures that need attention.
185
+ * Examples: request failed, database error, unhandled exception.
186
+ *
187
+ * @param message - The log message
188
+ * @param context - Optional key-value context to include with the log
189
+ */
190
+ error(message: string, context?: LogContext): void;
191
+ /**
192
+ * Internal method that builds the log entry and passes it to the formatter.
193
+ *
194
+ * All public log methods (debug, info, warn, error) delegate here.
195
+ *
196
+ * @param level - The log level
197
+ * @param message - The log message
198
+ * @param context - Optional key-value context to include with the log
199
+ */
200
+ private log;
92
201
  }
93
202
 
94
203
  /**
95
- * PowerPath Response Types
204
+ * Where Clause Types
96
205
  *
97
- * Entity types returned by PowerPath API endpoints.
206
+ * Type-safe object syntax for building filter expressions.
98
207
  */
99
-
100
-
101
-
102
- // ═══════════════════════════════════════════════════════════════════════════════
103
- // TEST ASSIGNMENTS
104
- // ═══════════════════════════════════════════════════════════════════════════════
105
-
106
208
  /**
107
- * A single test assignment entity.
108
- */
109
- interface TestAssignment {
110
- sourcedId: string
111
- studentSourcedId: string
112
- studentEmail: string
113
- assignedByUserSourcedId: string | null
114
- subject: string
115
- grade: string
116
- assignmentStatus: TestAssignmentStatus
117
- testName?: string | null
118
- assignedAt?: string | null
119
- expiresAt?: string | null
120
- completedAt?: string | null
121
- resourceSourcedId?: string | null
122
- componentResourceSourcedId?: string | null
123
- }
124
-
209
+ * Primitive value types that can be used in filters.
210
+ */
211
+ type FilterValue = string | number | boolean | Date;
125
212
  /**
126
- * List response for test assignments.
213
+ * Operators for a single field.
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * { status: { ne: 'deleted' } }
218
+ * { score: { gt: 90 } }
219
+ * { email: { contains: '@school.edu' } }
220
+ * { role: { in: ['teacher', 'aide'] } }
221
+ * ```
127
222
  */
128
- interface TestAssignmentsListResponse extends PaginationMeta {
129
- testAssignments: TestAssignment[]
223
+ interface FieldOperators<T> {
224
+ /** Not equal */
225
+ ne?: T;
226
+ /** Greater than */
227
+ gt?: T;
228
+ /** Greater than or equal */
229
+ gte?: T;
230
+ /** Less than */
231
+ lt?: T;
232
+ /** Less than or equal */
233
+ lte?: T;
234
+ /** Contains substring (strings only) */
235
+ contains?: T extends string ? string : never;
236
+ /** Match any of the values */
237
+ in?: T[];
238
+ /** Match none of the values */
239
+ notIn?: T[];
130
240
  }
131
-
132
241
  /**
133
- * Result from creating a test assignment.
242
+ * A field condition can be:
243
+ * - A direct value (implies equality)
244
+ * - An object with operators
134
245
  */
135
- interface AssignmentResult {
136
- assignmentId: string
137
- lessonId: string
138
- resourceId: string
139
- }
140
-
246
+ type FieldCondition<T> = T | FieldOperators<T>;
141
247
  /**
142
- * Result from bulk operations.
248
+ * Map filter field types to field conditions.
249
+ *
250
+ * Each field in F becomes an optional filter condition.
251
+ *
252
+ * @typeParam F - Filter fields type (e.g., UserFilterFields)
143
253
  */
144
- interface BulkResult {
145
- success: boolean
146
- results: AssignmentResult[]
147
- errors: Array<{ row: number; message: string }>
148
- }
149
-
150
- // ═══════════════════════════════════════════════════════════════════════════════
151
- // QUESTIONS
152
- // ═══════════════════════════════════════════════════════════════════════════════
153
-
254
+ type FilterFields<F> = {
255
+ [K in keyof F]?: FieldCondition<F[K] & FilterValue>;
256
+ };
154
257
  /**
155
- * QTI content associated with a question.
258
+ * OR condition for combining multiple field conditions.
156
259
  */
157
- interface PowerPathQuestionContent {
158
- /** The type of the question (e.g., choiceInteraction) */
159
- type?: string
160
- /** The raw XML question in QTI format */
161
- rawXml: string
260
+ interface OrCondition<F> {
261
+ OR: WhereClause<F>[];
162
262
  }
263
+ /**
264
+ * A where clause for filtering entities.
265
+ *
266
+ * The type parameter F should be a filter fields type that defines
267
+ * the available fields and their value types for filtering.
268
+ *
269
+ * Multiple fields at the same level are combined with AND.
270
+ * Use `OR` for explicit OR logic.
271
+ *
272
+ * @typeParam F - Filter fields type (e.g., UserFilterFields)
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * // Simple equality (implicit AND)
277
+ * { status: 'active', role: 'teacher' }
278
+ * // → status='active' AND role='teacher'
279
+ * ```
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * // With operators
284
+ * { status: { ne: 'deleted' }, score: { gte: 90 } }
285
+ * // → status!='deleted' AND score>=90
286
+ * ```
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * // OR condition
291
+ * { OR: [{ role: 'teacher' }, { role: 'aide' }] }
292
+ * // → role='teacher' OR role='aide'
293
+ * ```
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * // Match multiple values
298
+ * { role: { in: ['teacher', 'aide'] } }
299
+ * // → role='teacher' OR role='aide'
300
+ * ```
301
+ */
302
+ type WhereClause<F> = FilterFields<F> | OrCondition<F>;
163
303
 
164
304
  /**
165
- * Result of evaluating a student's response to a question.
305
+ * Shared Types
306
+ *
307
+ * Common types for API client infrastructure.
166
308
  */
167
- interface PowerPathQuestionResult {
168
- /** Score assigned considering the student's response */
169
- score: number
170
- /** Feedback — plain string from updateStudentQuestionResponse, structured object from progress/next-question responses */
171
- feedback: string | { value: string; identifier: string }
172
- /** Outcome variables from response processing (values may be strings or numbers) */
173
- outcomes?: Record<string, string | number>
174
- }
175
309
 
176
310
  /**
177
- * A question in a PowerPath test.
178
- *
179
- * Represents a question with its metadata, optional QTI content,
180
- * and (when answered) the student's response and result.
181
- */
182
- interface PowerPathTestQuestion {
183
- /** ID that represents the question in the test */
184
- id: string
185
- /** Index of the question in the test */
186
- index: number
187
- /** Title of the question */
188
- title: string
189
- /** URL of the QTI question */
190
- url: string
191
- /** Difficulty of the question */
192
- difficulty: PowerPathQuestionDifficulty
193
- /** Whether the question has been approved by a human */
194
- humanApproved?: boolean | null
195
- /** QTI content of the question */
196
- content?: PowerPathQuestionContent
197
- /** Student's response (single value or array) */
198
- response?: string | string[]
199
- /** Student's responses keyed by response identifier */
200
- responses?: Record<string, string | string[]>
201
- /** Whether the student's response is correct */
202
- correct?: boolean
203
- /** Result of evaluating the response */
204
- result?: PowerPathQuestionResult
205
- /** sourcedId of the AssessmentResult for this question attempt */
206
- resultId?: string
207
- /** Learning objective IDs associated with the question */
208
- learningObjectives?: string[]
311
+ * Fetch function signature for HTTP requests.
312
+ * Avoids Bun-specific extensions on `typeof fetch`.
313
+ */
314
+ type FetchFn$1 = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
315
+ /**
316
+ * Supported Timeback platform implementations.
317
+ */
318
+ type Platform$1 = (typeof PLATFORMS)[number];
319
+ /**
320
+ * Supported deployment environments.
321
+ */
322
+ type Environment$1 = 'staging' | 'production';
323
+ /**
324
+ * Auth credentials for environment mode.
325
+ * Token URL is derived automatically from environment.
326
+ */
327
+ interface EnvAuth$1 {
328
+ clientId: string;
329
+ clientSecret: string;
209
330
  }
210
-
211
- // ═══════════════════════════════════════════════════════════════════════════════
212
- // ASSESSMENTS
213
- // ═══════════════════════════════════════════════════════════════════════════════
214
-
215
331
  /**
216
- * Result from creating an external test (test-out or placement).
217
- */
218
- interface ExternalTestCreateResponse {
219
- /** Type of lesson created. */
220
- lessonType: PowerPathLessonType
221
- /** The sourcedId of the created lesson (ComponentResource). */
222
- lessonId: string
223
- /** The sourcedId of the component (unit) containing the test. */
224
- courseComponentId: string
225
- /** The sourcedId of the resource representing the external test. */
226
- resourceId: string
227
- /** URL to the external test system. */
228
- launchUrl?: string
229
- /** The tool provider identifier (e.g. 'edulastic', 'mastery-track'). */
230
- toolProvider: string
231
- /** The ID of the test in the vendor's system. */
232
- vendorId?: string
233
- /** The courseId to enroll the student in on failure (placement tests). */
234
- courseIdOnFail?: string | null
235
- /** Grade levels for the resource. */
236
- grades?: Array<number | string>
332
+ * Auth credentials for explicit mode.
333
+ * Includes authUrl for custom APIs.
334
+ * @deprecated Use separate authUrl and ProviderAuth fields instead
335
+ */
336
+ interface ExplicitAuth$1 {
337
+ clientId: string;
338
+ clientSecret: string;
339
+ authUrl: string;
237
340
  }
238
-
239
341
  /**
240
- * Result from creating an internal test (QTI or assessment-bank).
241
- */
242
- interface InternalTestCreateResponse {
243
- /** Type of lesson created. */
244
- lessonType: PowerPathLessonType
245
- /** The internal test type. */
246
- testType: 'qti' | 'assessment-bank'
247
- /** The sourcedId of the created lesson (ComponentResource). */
248
- lessonId: string
249
- /** The sourcedId of the component (unit) containing the test. */
250
- courseComponentId: string
251
- /** The sourcedId of the main resource (parent for assessment-bank). */
252
- resourceId: string
253
- /** Child resource IDs (only for assessment-bank type). */
254
- childResourceIds?: string[]
255
- /** The courseId to enroll the student in on failure (placement tests). */
256
- courseIdOnFail?: string | null
257
- /** Grade levels for the resource. */
258
- grades?: Array<number | string>
342
+ * Base configuration options shared by all modes.
343
+ */
344
+ interface BaseConfig$1 {
345
+ /** Request timeout in milliseconds */
346
+ timeout?: number;
347
+ /** Custom fetch implementation */
348
+ fetch?: FetchFn$1;
259
349
  }
260
-
261
350
  /**
262
- * A single attempt record.
263
- *
264
- * Matches the backend `PowerPath100AttemptSchema` with full metadata
265
- * including XP, timestamps, and typed score status.
266
- */
267
- interface Attempt {
268
- /** Attempt number, or null if not yet started. */
269
- attempt: number | null
270
- /** Current score for this attempt. */
271
- score: number
272
- /** Grading status of this attempt. */
273
- scoreStatus: ScoreStatus
274
- /** XP earned in this attempt. */
275
- xp: number | null
276
- /** When this attempt was started. */
277
- startedAt: string | null
278
- /** When this attempt was completed. */
279
- completedAt: string | null
351
+ * Environment-based configuration for Timeback APIs.
352
+ */
353
+ interface EnvConfig extends BaseConfig$1 {
354
+ /** Timeback platform implementation (defaults to 'BEYOND_AI') */
355
+ platform?: Platform$1;
356
+ /** Target environment - determines base URL and token URL */
357
+ env: Environment$1;
358
+ /** OAuth2 client credentials */
359
+ auth: EnvAuth$1;
280
360
  }
281
-
282
361
  /**
283
- * Result from creating a new attempt.
362
+ * Environment-based configuration with shared token provider.
284
363
  */
285
- interface CreateAttemptResponse {
286
- attempt: Attempt
364
+ interface TokenProviderEnvConfig extends BaseConfig$1 {
365
+ /** Timeback platform implementation (defaults to 'BEYOND_AI') */
366
+ platform?: Platform$1;
367
+ /** Target environment - determines base URL */
368
+ env: Environment$1;
369
+ /** Shared token provider (from @timeback/auth) */
370
+ tokenProvider: TokenProvider;
287
371
  }
288
-
289
372
  /**
290
- * Result from getting attempts for a lesson.
373
+ * Explicit URL configuration for custom APIs.
374
+ * Supports both authenticated and public/no-auth services.
291
375
  */
292
- interface GetAttemptsResponse {
293
- attempts: Attempt[]
376
+ interface ExplicitConfig extends BaseConfig$1 {
377
+ /** API base URL */
378
+ baseUrl: string;
379
+ /**
380
+ * OAuth2 token URL. Omit for public/no-auth services.
381
+ * Can also be provided via auth.authUrl (legacy format).
382
+ */
383
+ authUrl?: string;
384
+ /**
385
+ * OAuth2 credentials. Required if authUrl is provided.
386
+ * Supports both ExplicitAuth (with authUrl) and ProviderAuth (without).
387
+ */
388
+ auth?: ExplicitAuth$1 | ProviderAuth;
389
+ /**
390
+ * Use a built-in path profile by name.
391
+ * Defaults to 'BEYOND_AI' if neither pathProfile nor paths is specified.
392
+ */
393
+ pathProfile?: Platform$1;
394
+ /** Custom path overrides (takes precedence over pathProfile) */
395
+ paths?: Partial<PlatformPaths>;
396
+ /** Not applicable to explicit config — use `EnvConfig` instead */
397
+ env?: never;
294
398
  }
295
-
296
399
  /**
297
- * Result from resetting an attempt.
400
+ * Use pre-configured transport.
298
401
  */
299
- interface ResetAttemptResponse {
300
- success: boolean
301
- score: number
402
+ interface TransportConfig extends BaseConfig$1 {
403
+ /** Transport configuration */
404
+ transport: TransportLike;
302
405
  }
303
-
304
- // ═══════════════════════════════════════════════════════════════════════════════
305
- // ASSESSMENT PROGRESS (getAssessmentProgress)
306
- // ═══════════════════════════════════════════════════════════════════════════════
307
-
308
406
  /**
309
- * Progress for a PowerPath 100 lesson.
310
- *
311
- * Uses `seenQuestions` (not `questions`) and includes remaining question counts
312
- * per difficulty level.
313
- */
314
- interface PowerPath100ProgressResponse {
315
- lessonType: 'powerpath-100'
316
- /** Remaining question counts per difficulty level */
317
- remainingQuestionsPerDifficulty: {
318
- easy: number
319
- medium: number
320
- hard: number
321
- }
322
- /** Current score for this attempt */
323
- score: number
324
- /** Questions the student has seen */
325
- seenQuestions: PowerPathTestQuestion[]
326
- /** sourcedId of the parent test AssessmentResult */
327
- testResultId?: string
328
- /** Attempt number */
329
- attempt: number
330
- /** XP earned in the lesson */
331
- xp: number | null
332
- /** Multiplier for XP */
333
- multiplier: number | null
334
- /** Accuracy of the student's attempted questions */
335
- accuracy: number
336
- /** Number of correct questions answered */
337
- correctQuestions: number
338
- /** Total number of questions in the lesson */
339
- totalQuestions: number
407
+ * HTTP request options.
408
+ */
409
+ interface RequestOptions$1 {
410
+ /** HTTP method */
411
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
412
+ /** Query parameters to append to the URL */
413
+ params?: Record<string, string | number | boolean | undefined>;
414
+ /** Request body (will be JSON-serialized) */
415
+ body?: unknown;
416
+ /** Additional headers to include */
417
+ headers?: Record<string, string>;
418
+ /**
419
+ * Unique identifier for this request.
420
+ * Used for log correlation and debugging.
421
+ * Auto-generated if not provided.
422
+ */
423
+ requestId?: string;
340
424
  }
341
-
342
425
  /**
343
- * Progress for quiz, test-out, placement, or unit-test lessons.
344
- *
345
- * Uses `questions` (not `seenQuestions`). Includes `finalized` to indicate
346
- * whether the lesson has been completed.
347
- */
348
- interface StandardProgressResponse {
349
- lessonType: 'quiz' | 'test-out' | 'placement' | 'unit-test'
350
- /** Whether the lesson has been finalized in the current attempt */
351
- finalized: boolean
352
- /** Current score for this attempt */
353
- score?: number
354
- /** Questions in the test */
355
- questions: PowerPathTestQuestion[]
356
- /** Tool provider of the lesson if external */
357
- toolProvider: string | null
358
- /** Whether auto-enrollment failed (only for finalized external tests) */
359
- enrollmentFailed?: boolean
360
- /** sourcedId of the parent test AssessmentResult */
361
- testResultId?: string
362
- /** Attempt number */
363
- attempt: number
364
- /** XP earned in the lesson */
365
- xp: number | null
366
- /** Multiplier for XP */
367
- multiplier: number | null
368
- /** Accuracy of the student's attempted questions */
369
- accuracy: number
370
- /** Number of correct questions answered */
371
- correctQuestions: number
372
- /** Total number of questions in the lesson */
373
- totalQuestions: number
426
+ * Duck-typed transport interface for testing and advanced use.
427
+ */
428
+ interface TransportLike {
429
+ /** Base URL of the API */
430
+ baseUrl: string;
431
+ /** Make an authenticated request */
432
+ request<T>(path: string, options?: RequestOptions$1): Promise<T>;
374
433
  }
375
-
376
434
  /**
377
- * Result from getting assessment progress.
435
+ * Configuration using a pre-configured transport.
378
436
  *
379
- * Discriminated union on `lessonType`:
380
- * - `'powerpath-100'` uses `seenQuestions` and `remainingQuestionsPerDifficulty`
381
- * - `'quiz' | 'test-out' | 'placement' | 'unit-test'` — uses `questions` and `finalized`
437
+ * For advanced use cases like sharing a transport between clients
438
+ * or using a custom transport implementation.
439
+ *
440
+ * @template T - Transport type (defaults to TransportLike, clients should specify their full transport type)
382
441
  */
383
- type GetAssessmentProgressResponse = PowerPath100ProgressResponse | StandardProgressResponse
384
-
385
- // ═══════════════════════════════════════════════════════════════════════════════
386
- // GET NEXT QUESTION (getNextQuestion)
387
- // ═══════════════════════════════════════════════════════════════════════════════
388
-
442
+ interface TransportOnlyConfig<T extends TransportLike = TransportLike> {
443
+ /** Existing transport instance */
444
+ transport: T;
445
+ }
389
446
  /**
390
- * Result from getting the next question in a PowerPath 100 lesson.
447
+ * Union of all client configuration types.
391
448
  */
392
- interface GetNextQuestionResponse {
393
- /** Current PowerPath score of the student in this lesson */
394
- score: number
395
- /** The next question to present */
396
- question: PowerPathTestQuestion
397
- }
398
-
399
- // ═══════════════════════════════════════════════════════════════════════════════
400
- // UPDATE STUDENT QUESTION RESPONSE (updateStudentQuestionResponse)
401
- // ═══════════════════════════════════════════════════════════════════════════════
402
-
449
+ type ClientConfig = EnvConfig | TokenProviderEnvConfig | ExplicitConfig | TransportConfig | Partial<ExplicitConfig>;
403
450
  /**
404
- * Response feedback for a student's answer.
451
+ * Parameters for listing resources with pagination, sorting, and filtering.
452
+ *
453
+ * Common across all Timeback APIs (OneRoster, Edubridge, QTI, etc.).
454
+ *
455
+ * @typeParam T - Entity type for type-safe `where` clause (defaults to unknown)
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * // Type-safe where
460
+ * client.users.list({
461
+ * where: { status: 'active', role: 'teacher' },
462
+ * sort: 'familyName',
463
+ * })
464
+ * ```
405
465
  */
406
- interface ResponseResultFeedback {
407
- identifier?: string
408
- value?: string
466
+ interface ListParams<T = unknown> {
467
+ /**
468
+ * Maximum items per page.
469
+ * @default 100
470
+ */
471
+ limit?: number;
472
+ /**
473
+ * Number of items to skip (for pagination).
474
+ * @default 0
475
+ */
476
+ offset?: number;
477
+ /**
478
+ * Field name to sort results by.
479
+ *
480
+ * Type-safe: only valid field names for this resource are accepted.
481
+ *
482
+ * @example
483
+ * ```typescript
484
+ * sort: 'familyName'
485
+ * ```
486
+ */
487
+ sort?: keyof T & string;
488
+ /**
489
+ * Sort direction.
490
+ * @default "asc"
491
+ */
492
+ orderBy?: 'asc' | 'desc';
493
+ /**
494
+ * Type-safe filter using object syntax.
495
+ *
496
+ * Multiple fields are combined with AND. Use `OR` for OR logic.
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * // Simple equality
501
+ * where: { status: 'active' }
502
+ * ```
503
+ *
504
+ * @example
505
+ * ```typescript
506
+ * // Multiple fields (AND)
507
+ * where: { status: 'active', role: 'teacher' }
508
+ * ```
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * // With operators
513
+ * where: { score: { gte: 90 }, status: { ne: 'deleted' } }
514
+ * ```
515
+ *
516
+ * @example
517
+ * ```typescript
518
+ * // OR condition
519
+ * where: { role: { in: ['teacher', 'aide'] } }
520
+ * ```
521
+ */
522
+ where?: WhereClause<T>;
523
+ /**
524
+ * Fields to include in the response.
525
+ * Reduces payload size by requesting only needed fields.
526
+ * @example ['sourcedId', 'givenName', 'familyName']
527
+ */
528
+ fields?: string[];
529
+ /**
530
+ * Free-text search across multiple fields (proprietary extension).
531
+ * For users: searches givenName, familyName, email.
532
+ * @example "john@example.com"
533
+ */
534
+ search?: string;
535
+ /**
536
+ * Maximum total items to return across all pages.
537
+ *
538
+ * Unlike `limit` (which sets page size), `max` caps the total number
539
+ * of items yielded by the paginator. Pagination stops once this many
540
+ * items have been returned.
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * // Get at most 50 users total
545
+ * client.users.list({ max: 50 })
546
+ * ```
547
+ */
548
+ max?: number;
409
549
  }
410
-
411
550
  /**
412
- * Result of processing a student's response.
551
+ * Response from a paginated API request.
413
552
  */
414
- interface ResponseResult {
415
- /** Whether the student's response is correct */
416
- isCorrect: boolean
417
- /** Score for this specific response (0 or 1) */
418
- score: number
419
- /** Optional feedback */
420
- feedback?: ResponseResultFeedback
553
+ interface PaginatedResponse<T> {
554
+ /** Array of items in this page */
555
+ data: T[];
556
+ /** Whether more pages are available */
557
+ hasMore: boolean;
558
+ /** Total count of items (if provided by server) */
559
+ total?: number;
421
560
  }
422
-
423
561
  /**
424
- * Result from updating a student's response in a PowerPath 100 lesson.
425
- *
426
- * Includes the updated PowerPath score, response correctness, and accuracy stats.
427
- */
428
- interface PowerPath100UpdateResponseResult {
429
- lessonType: 'powerpath-100'
430
- /** Updated PowerPath score */
431
- powerpathScore: number
432
- /** Result of processing the response */
433
- responseResult: ResponseResult
434
- /** Assessment result for the question (for debugging) */
435
- questionResult?: unknown
436
- /** Assessment result for the test (for debugging) */
437
- testResult?: unknown
438
- /** Accuracy of the student's attempted questions */
439
- accuracy: number
440
- /** Number of correct questions answered */
441
- correctQuestions: number
442
- /** Total number of questions */
443
- totalQuestions: number
444
- /** XP earned */
445
- xp: number | null
446
- /** XP multiplier */
447
- multiplier: number | null
562
+ * Result of fetching a single page of resources.
563
+ *
564
+ * @typeParam T - The type of items in the page
565
+ */
566
+ interface PageResult<T> {
567
+ /** Array of items in this page */
568
+ data: T[];
569
+ /** Whether more pages are available */
570
+ hasMore: boolean;
571
+ /** Total count of items (if provided by server) */
572
+ total?: number;
573
+ /** Offset to use for fetching the next page */
574
+ nextOffset?: number;
448
575
  }
449
-
450
576
  /**
451
- * Result from updating a student's response in a quiz/test-out/placement/unit-test lesson.
452
- *
453
- * Minimal response — correctness is evaluated at finalization.
577
+ * Options for toArray() method.
454
578
  */
455
- interface StandardUpdateResponseResult {
456
- lessonType: 'quiz' | 'test-out' | 'placement' | 'unit-test'
457
- /** Assessment result for the question (for debugging) */
458
- questionResult?: unknown
579
+ interface ToArrayOptions {
580
+ /**
581
+ * Maximum number of items to collect.
582
+ *
583
+ * Throws an error if this limit is exceeded, preventing OOM on large datasets.
584
+ * Use `for await...of` to stream results instead.
585
+ *
586
+ * @default 10_000
587
+ * @example Set to Infinity to disable (use with caution!)
588
+ */
589
+ maxItems?: number;
459
590
  }
460
-
461
591
  /**
462
- * Result from updating a student question response.
463
- *
464
- * Discriminated union on `lessonType`:
465
- * - `'powerpath-100'` — includes score, accuracy, and response correctness
466
- * - Other lesson types — minimal, evaluated at finalization
592
+ * Function that fetches a page of results.
593
+ * Provided by the transport layer.
467
594
  */
468
- type UpdateStudentQuestionResponseResult =
469
- | PowerPath100UpdateResponseResult
470
- | StandardUpdateResponseResult
471
-
472
- // ═══════════════════════════════════════════════════════════════════════════════
473
- // FINALIZE ASSESSMENT (finalStudentAssessmentResponse)
474
- // ═══════════════════════════════════════════════════════════════════════════════
475
-
595
+ type PageFetcher<T> = (path: string, options: {
596
+ params: Record<string, string | number | boolean | undefined>;
597
+ }) => Promise<PaginatedResponse<T>>;
476
598
  /**
477
- * Result from finalizing a test assessment.
599
+ * Pagination style for API requests.
478
600
  *
479
- * Returned after all questions have been answered and the lesson is
480
- * evaluated. Only applicable to quiz-like lesson types (quiz, test-out,
481
- * placement, unit-test). Not applicable to `powerpath-100`.
601
+ * - `'offset'`: Uses limit/offset parameters (default, e.g., OneRoster)
602
+ * - `'page'`: Uses limit/page parameters (1-indexed, e.g., QTI)
603
+ */
604
+ type PaginationStyle = 'offset' | 'page';
605
+ /**
606
+ * Options for creating a Paginator.
482
607
  */
483
- interface FinalizeAssessmentResponse {
484
- /** Type of the lesson that was finalized (quiz-like only). */
485
- lessonType: QuizLikeLessonType
486
- /** Whether the lesson has been finalized. */
487
- finalized: boolean
488
- /** The attempt number. */
489
- attempt: number
608
+ interface PaginatorOptions<T, F = unknown> {
609
+ /** Function to fetch a page of results */
610
+ fetcher: PageFetcher<T>;
611
+ /** API endpoint path */
612
+ path: string;
613
+ /** List parameters (filter, sort, limit, offset) */
614
+ params?: ListParams<F>;
615
+ /** Maximum total items to return across all pages (client-side cap) */
616
+ max?: number;
617
+ /** Response key containing the items array (e.g., "users") */
618
+ unwrapKey?: string;
619
+ /** Logger instance (defaults to client-common logger) */
620
+ logger?: Logger;
621
+ /** Optional transform function applied to each item before yielding */
622
+ transform?: (item: T) => T;
623
+ /**
624
+ * Pagination style to use for API requests.
625
+ *
626
+ * - `'offset'` (default): Sends `limit` and `offset` params
627
+ * - `'page'`: Sends `limit` and `page` params (1-indexed)
628
+ *
629
+ * @default 'offset'
630
+ */
631
+ paginationStyle?: PaginationStyle;
490
632
  }
491
-
492
- // ═══════════════════════════════════════════════════════════════════════════════
493
- // TEST OUT (testOut)
494
- // ═══════════════════════════════════════════════════════════════════════════════
495
-
496
633
  /**
497
- * Result from getting the test-out lesson for a student/course.
498
- *
499
- * Returns the test-out lesson reference, finalization status,
500
- * and optional external tool credentials.
501
- */
502
- interface TestOutResponse {
503
- lessonType: 'test-out'
504
- /** ID of the test-out lesson, or null if none exists */
505
- lessonId: string | null
506
- /** Whether the test-out has been finalized in the current attempt */
507
- finalized: boolean
508
- /** Tool provider for the test-out lesson, or null if internal */
509
- toolProvider: string | null
510
- /** Attempt number */
511
- attempt?: number
512
- /** Credentials for accessing the assigned test on external tool */
513
- credentials?: {
514
- email: string
515
- password: string
516
- }
517
- /** Assignment ID on external tool for results retrieval */
518
- assignmentId?: string
519
- /** Class ID on external tool for results retrieval */
520
- classId?: string
521
- /** URL of the test on external tool */
522
- testUrl?: string
523
- /** ID of the test on external tool */
524
- testId?: string
634
+ * Result of an auth check operation.
635
+ */
636
+ interface AuthCheckResult$1 {
637
+ /** Whether auth succeeded */
638
+ ok: boolean;
639
+ /** Time taken to complete the check (ms) */
640
+ latencyMs: number;
641
+ /** Error message if failed */
642
+ error?: string;
643
+ /** Detailed check results */
644
+ checks: {
645
+ /** Token acquisition succeeded */
646
+ tokenAcquisition: boolean;
647
+ };
525
648
  }
526
649
 
527
- // ═══════════════════════════════════════════════════════════════════════════════
528
- // IMPORT EXTERNAL RESULTS (importExternalTestAssignmentResults)
529
- // ═══════════════════════════════════════════════════════════════════════════════
650
+ /**
651
+ * Config Types
652
+ *
653
+ * Types for TimebackProvider and provider resolution.
654
+ */
530
655
 
531
656
  /**
532
- * Result from importing external test assignment results.
533
- *
534
- * Contains the lesson reference, finalization status, and optional
535
- * external tool credentials/assignment data.
536
- */
537
- interface ImportExternalResultsResponse {
538
- /** Lesson type (external-capable types only). */
539
- lessonType: ExternalTestCapableLessonType
540
- /** The sourcedId of the lesson (ComponentResource). */
541
- lessonId: string | null
542
- /** The tool provider for the lesson. */
543
- toolProvider: string | null
544
- /** Whether the test has been finalized in the current attempt. */
545
- finalized: boolean
546
- /** Attempt number. */
547
- attempt: number
548
- /** Credentials for accessing the assigned test on external tool. */
549
- credentials?: {
550
- email: string
551
- password: string
552
- }
553
- /** Assignment ID on external tool for results retrieval. */
554
- assignmentId?: string
555
- /** Class ID on external tool for results retrieval. */
556
- classId?: string
557
- /** URL of the test on external tool. */
558
- testUrl?: string
559
- /** ID of the test on external tool. */
560
- testId?: string
657
+ * Caliper API path profile.
658
+ * Defines paths for Caliper operations. Use `null` for unsupported operations.
659
+ */
660
+ interface CaliperPaths {
661
+ /** Path for sending events (POST) */
662
+ send: string;
663
+ /** Path for validating events (POST), null if not supported */
664
+ validate: string | null;
665
+ /** Path for listing events (GET), null if not supported */
666
+ list: string | null;
667
+ /** Path template for getting single event (GET), use {id} placeholder */
668
+ get: string | null;
669
+ /** Path template for job status (GET), use {id} placeholder */
670
+ jobStatus: string | null;
561
671
  }
562
-
563
- // ═══════════════════════════════════════════════════════════════════════════════
564
- // MAKE EXTERNAL TEST ASSIGNMENT (makeExternalTestAssignment)
565
- // ═══════════════════════════════════════════════════════════════════════════════
566
-
567
672
  /**
568
- * Result from assigning an external test to a student.
569
- *
570
- * Contains the tool provider, lesson type, attempt number, and optional
571
- * external tool credentials/assignment data.
572
- */
573
- interface MakeExternalTestAssignmentResponse {
574
- /** The tool provider (e.g. 'edulastic', 'mastery-track'). */
575
- toolProvider: string
576
- /** Lesson type (external-capable types only). */
577
- lessonType: ExternalTestCapableLessonType
578
- /** Attempt number. */
579
- attempt: number
580
- /** Credentials for accessing the assigned test on external tool. */
581
- credentials?: {
582
- email: string
583
- password: string
584
- }
585
- /** Assignment ID on external tool for results retrieval. */
586
- assignmentId?: string
587
- /** Class ID on external tool for results retrieval. */
588
- classId?: string
589
- /** URL of the test on external tool. */
590
- testUrl?: string
591
- /** ID of the test on external tool. */
592
- testId?: string
673
+ * Webhook API path profile.
674
+ * Defines paths for webhook management operations.
675
+ * Nullability is at the platform level (`webhooks: WebhookPaths | null` in PlatformPaths).
676
+ */
677
+ interface WebhookPaths {
678
+ /** Path for listing webhooks (GET) */
679
+ webhookList: string;
680
+ /** Path template for getting a single webhook (GET), use {id} placeholder */
681
+ webhookGet: string;
682
+ /** Path for creating a webhook (POST) */
683
+ webhookCreate: string;
684
+ /** Path template for updating a webhook (PUT), use {id} placeholder */
685
+ webhookUpdate: string;
686
+ /** Path template for deleting a webhook (DELETE), use {id} placeholder */
687
+ webhookDelete: string;
688
+ /** Path template for activating a webhook (PUT), use {id} placeholder */
689
+ webhookActivate: string;
690
+ /** Path template for deactivating a webhook (PUT), use {id} placeholder */
691
+ webhookDeactivate: string;
692
+ /** Path for listing all webhook filters (GET) */
693
+ webhookFilterList: string;
694
+ /** Path template for getting a single webhook filter (GET), use {id} placeholder */
695
+ webhookFilterGet: string;
696
+ /** Path for creating a webhook filter (POST) */
697
+ webhookFilterCreate: string;
698
+ /** Path template for updating a webhook filter (PUT), use {id} placeholder */
699
+ webhookFilterUpdate: string;
700
+ /** Path template for deleting a webhook filter (DELETE), use {id} placeholder */
701
+ webhookFilterDelete: string;
702
+ /** Path template for listing filters by webhook (GET), use {webhookId} placeholder */
703
+ webhookFiltersByWebhook: string;
593
704
  }
594
-
595
- // ═══════════════════════════════════════════════════════════════════════════════
596
- // PLACEMENT
597
- // ═══════════════════════════════════════════════════════════════════════════════
598
-
599
705
  /**
600
- * Result from getting all placement tests.
601
- */
602
- interface GetAllPlacementTestsResponse {
603
- placementTests: unknown[]
706
+ * Reporting API path profile.
707
+ * Defines paths for reporting MCP and REST operations.
708
+ * Nullability is at the platform level (`reporting: ReportingPaths | null` in PlatformPaths).
709
+ */
710
+ interface ReportingPaths {
711
+ /** Path for the reporting MCP JSON-RPC endpoint (POST) */
712
+ mcp: string;
713
+ /** Path template for executing a saved query (GET), use {id} placeholder */
714
+ savedQueryExecute: string;
715
+ /** Path template for checking reporting group membership (GET), use {email} placeholder */
716
+ adminGroupCheck: string;
717
+ /** Path template for adding a user to the reporting group (POST), use {email} placeholder */
718
+ adminGroupAdd: string;
719
+ /** Path template for removing a user from the reporting group (DELETE), use {email} placeholder */
720
+ adminGroupRemove: string;
604
721
  }
605
-
606
722
  /**
607
- * Result from getting current placement level.
723
+ * OneRoster API path profile.
724
+ * Defines the base path prefix for all OneRoster resources.
608
725
  */
609
- interface GetCurrentLevelResponse {
610
- gradeLevel?: unknown
611
- onboarded?: boolean
612
- availableTests: number
726
+ interface OneRosterPaths {
727
+ /** Base path prefix for rostering resources (users, schools, classes, etc.) */
728
+ rostering: string;
729
+ /** Base path prefix for gradebook resources (lineItems, results, etc.) */
730
+ gradebook: string;
731
+ /** Base path prefix for resources API (digital learning resources) */
732
+ resources: string;
613
733
  }
614
-
615
734
  /**
616
- * Result from getting the next placement test.
735
+ * Edubridge API path profile.
736
+ * Defines path prefixes for Edubridge operations.
617
737
  */
618
- interface GetNextPlacementTestResponse {
619
- availableTests: number
620
- lesson: string
738
+ interface EdubridgePaths {
739
+ /** Base path prefix for all Edubridge resources */
740
+ base: string;
621
741
  }
622
-
623
742
  /**
624
- * Result from getting subject progress.
743
+ * PowerPath API path profile.
744
+ * Defines path prefixes for PowerPath operations.
625
745
  */
626
- interface GetSubjectProgressResponse {
627
- progress: unknown[]
746
+ interface PowerPathPaths {
747
+ /** Base path prefix for all PowerPath resources */
748
+ base: string;
628
749
  }
629
-
630
750
  /**
631
- * Result from resetting placement.
751
+ * CASE API path profile.
752
+ * Defines path prefix for CASE (Competency and Academic Standards Exchange) operations.
632
753
  */
633
- interface ResetPlacementResponse {
634
- success: boolean
635
- placementResultsDeleted: number
636
- onboardingReset: boolean
754
+ interface CasePaths {
755
+ /** Base path prefix for all CASE resources */
756
+ base: string;
637
757
  }
638
-
639
- // ═══════════════════════════════════════════════════════════════════════════════
640
- // SCREENING
641
- // ═══════════════════════════════════════════════════════════════════════════════
642
-
643
758
  /**
644
- * Result from screening getResults.
645
- * Response shape depends on MAP integration configuration.
759
+ * CLR API path profile.
760
+ * Defines path prefixes for CLR (Comprehensive Learner Record) operations.
646
761
  */
647
- interface ScreeningResultsResponse {
648
- [key: string]: unknown
762
+ interface ClrPaths {
763
+ /** Path for upserting CLR credentials (POST) */
764
+ credentials: string;
765
+ /** Path for API discovery (GET) */
766
+ discovery: string;
649
767
  }
650
-
651
768
  /**
652
- * Result from screening getSession.
653
- * Response shape depends on MAP integration configuration.
769
+ * Platform path profiles for all services.
770
+ * Use `null` to indicate a service is not supported on the platform.
771
+ */
772
+ interface PlatformPaths {
773
+ caliper: CaliperPaths;
774
+ oneroster: OneRosterPaths;
775
+ webhooks: WebhookPaths | null;
776
+ reporting: ReportingPaths | null;
777
+ edubridge: EdubridgePaths | null;
778
+ powerpath: PowerPathPaths | null;
779
+ clr: ClrPaths | null;
780
+ case: CasePaths | null;
781
+ }
782
+ /**
783
+ * Services that have path configuration.
784
+ * Subset of ServiceName - excludes services without path profiles (e.g., 'qti').
785
+ */
786
+ type PathEnabledService = keyof PlatformPaths;
787
+ /**
788
+ * Supported Timeback platform implementations.
789
+ */
790
+ type Platform = (typeof PLATFORMS)[number];
791
+ /**
792
+ * Supported deployment environments.
654
793
  */
655
- interface ScreeningSessionResponse {
656
- [key: string]: unknown
794
+ type Environment = 'staging' | 'production';
795
+ /**
796
+ * Supported service names.
797
+ */
798
+ type ServiceName = 'oneroster' | 'caliper' | 'webhooks' | 'reporting' | 'edubridge' | 'qti' | 'powerpath' | 'clr' | 'case';
799
+ /**
800
+ * Resolved endpoint for a single service.
801
+ */
802
+ interface ResolvedEndpoint {
803
+ /** Base URL for the service API */
804
+ baseUrl: string;
805
+ /** OAuth2 token URL for this endpoint. Undefined for public/no-auth services. */
806
+ authUrl?: string;
657
807
  }
658
-
659
808
  /**
660
- * Result from resetting a screening session.
809
+ * Auth credentials for a provider.
661
810
  */
662
- interface ScreeningResetSessionResponse {
663
- success?: boolean
664
- [key: string]: unknown
811
+ interface ProviderAuth {
812
+ clientId: string;
813
+ clientSecret: string;
665
814
  }
666
-
667
815
  /**
668
- * Result from assigning a screening test.
816
+ * Configuration for environment-based provider.
817
+ * Uses known Timeback platform endpoints.
818
+ */
819
+ interface ProviderEnvConfig {
820
+ /** Timeback platform (defaults to 'BEYOND_AI') */
821
+ platform?: Platform;
822
+ /** Target environment */
823
+ env: Environment;
824
+ /** OAuth2 credentials */
825
+ auth: ProviderAuth;
826
+ /** Request timeout in milliseconds */
827
+ timeout?: number;
828
+ }
829
+ /**
830
+ * Configuration for explicit URL provider.
831
+ * Single base URL for all services.
669
832
  */
670
- interface ScreeningAssignTestResponse {
671
- success?: boolean
672
- [key: string]: unknown
833
+ interface ProviderExplicitConfig {
834
+ /** Base URL for all services */
835
+ baseUrl: string;
836
+ /** OAuth2 token URL. Omit for public/no-auth services. */
837
+ authUrl?: string;
838
+ /** OAuth2 credentials. Required if authUrl is provided. */
839
+ auth?: ProviderAuth;
840
+ /** Request timeout in milliseconds */
841
+ timeout?: number;
842
+ /**
843
+ * Use a built-in path profile by name.
844
+ * Defaults to 'BEYOND_AI' if neither pathProfile nor paths is specified.
845
+ */
846
+ pathProfile?: Platform;
847
+ /** Custom path overrides (takes precedence over pathProfile) */
848
+ paths?: Partial<PlatformPaths>;
673
849
  }
674
-
675
- // ═══════════════════════════════════════════════════════════════════════════════
676
- // LESSON PLANS
677
- // ═══════════════════════════════════════════════════════════════════════════════
678
-
679
850
  /**
680
- * Result from creating a lesson plan.
851
+ * Configuration for multi-service provider.
852
+ * Different URLs for different services.
853
+ */
854
+ interface ProviderServicesConfig {
855
+ /** Per-service base URLs */
856
+ services: Partial<Record<ServiceName, string>>;
857
+ /** OAuth2 token URL. Omit for public/no-auth services. */
858
+ authUrl?: string;
859
+ /** OAuth2 credentials. Required if authUrl is provided. */
860
+ auth?: ProviderAuth;
861
+ /** Request timeout in milliseconds */
862
+ timeout?: number;
863
+ /**
864
+ * Use a built-in path profile by name.
865
+ * Defaults to 'BEYOND_AI' if neither pathProfile nor paths is specified.
866
+ */
867
+ pathProfile?: Platform;
868
+ /** Custom path overrides (takes precedence over pathProfile) */
869
+ paths?: Partial<PlatformPaths>;
870
+ }
871
+ /**
872
+ * Union of all provider configuration types.
681
873
  */
682
- interface LessonPlanCreateResponse {
683
- lessonPlanId: string
874
+ type TimebackProviderConfig = ProviderEnvConfig | ProviderExplicitConfig | ProviderServicesConfig;
875
+ /**
876
+ * Provider template - endpoints without auth.
877
+ * Used internally to define available platform+env combinations.
878
+ */
879
+ interface ProviderTemplate {
880
+ platform: Platform;
881
+ env: Environment;
684
882
  }
685
-
686
883
  /**
687
- * A lesson plan operation record.
884
+ * Registry of provider templates indexed by platform and environment.
885
+ *
886
+ * Use `satisfies ProviderRegistry` when defining a registry for type checking.
887
+ *
888
+ * @example
889
+ * const myRegistry = {
890
+ * defaultPlatform: 'MY_PLATFORM',
891
+ * templates: {
892
+ * MY_PLATFORM: {
893
+ * staging: { platform: 'BEYOND_AI', env: 'staging' },
894
+ * production: { platform: 'BEYOND_AI', env: 'production' },
895
+ * },
896
+ * },
897
+ * } satisfies ProviderRegistry
688
898
  */
689
- interface LessonPlanOperation {
690
- id: string
691
- type: string
692
- payload?: unknown
693
- reason?: string
694
- createdAt: string
695
- sequenceNumber: number
696
- createdBy?: string
899
+ interface ProviderRegistry {
900
+ /** Default platform when none specified */
901
+ defaultPlatform: string;
902
+ /** Available templates indexed by platform → env */
903
+ templates: Record<string, Record<string, ProviderTemplate>>;
697
904
  }
698
-
699
905
  /**
700
- * Response containing lesson plan operations.
906
+ * Client config that accepts a pre-built provider.
701
907
  */
702
- interface LessonPlanOperationsResponse {
703
- operations: LessonPlanOperation[]
908
+ interface ProviderClientConfig {
909
+ /** Pre-built provider */
910
+ provider: TimebackProvider;
704
911
  }
705
912
 
706
913
  /**
707
- * Result from a single lesson plan operation.
914
+ * Timeback Provider
915
+ *
916
+ * Encapsulates platform connection configuration including endpoints and auth.
917
+ * Providers are complete "connection" objects that clients consume.
708
918
  */
709
- interface LessonPlanOperationResult {
710
- success: boolean
711
- message?: string
712
- operationId?: string
713
- }
714
919
 
715
920
  /**
716
- * Result from syncing lesson plan operations.
921
+ * Timeback Provider - encapsulates a complete platform connection.
922
+ *
923
+ * A provider contains everything needed to connect to Timeback APIs:
924
+ * - Service endpoints (URLs)
925
+ * - Authentication credentials
926
+ * - Configuration options
927
+ *
928
+ * Providers can be created from:
929
+ * - Platform + environment (uses known Timeback endpoints)
930
+ * - Explicit base URL (single URL for all services)
931
+ * - Per-service URLs (different URLs for each service)
932
+ *
933
+ * @example
934
+ * ```typescript
935
+ * // Environment-based provider (Timeback hosted)
936
+ * const provider = new TimebackProvider({
937
+ * platform: 'BEYOND_AI',
938
+ * env: 'staging',
939
+ * auth: { clientId: '...', clientSecret: '...' },
940
+ * })
941
+ * ```
942
+ *
943
+ * @example
944
+ * ```typescript
945
+ * // Explicit URL provider (self-hosted)
946
+ * const provider = new TimebackProvider({
947
+ * baseUrl: 'https://api.myschool.edu',
948
+ * authUrl: 'https://auth.myschool.edu/oauth/token',
949
+ * auth: { clientId: '...', clientSecret: '...' },
950
+ * })
951
+ * ```
952
+ *
953
+ * @example
954
+ * ```typescript
955
+ * // Per-service URLs
956
+ * const provider = new TimebackProvider({
957
+ * services: {
958
+ * oneroster: 'https://roster.myschool.edu',
959
+ * caliper: 'https://analytics.myschool.edu',
960
+ * },
961
+ * authUrl: 'https://auth.myschool.edu/oauth/token',
962
+ * auth: { clientId: '...', clientSecret: '...' },
963
+ * })
964
+ * ```
717
965
  */
718
- interface LessonPlanSyncResult {
719
- success: boolean
720
- message?: string
721
- operationCount: number
722
- operationResults: Array<{ success: boolean; errors?: Array<{ message: string }> }>
966
+ declare class TimebackProvider {
967
+ /** Platform identifier (if using known platform) */
968
+ readonly platform?: Platform;
969
+ /** Environment (if using known platform) */
970
+ readonly env?: Environment;
971
+ /** OAuth2 credentials. Undefined for public/no-auth services. */
972
+ readonly auth?: ProviderAuth;
973
+ /** Request timeout in milliseconds */
974
+ readonly timeout: number;
975
+ /** Resolved endpoints for each service */
976
+ /** @internal */
977
+ readonly _endpoints: Partial<Record<ServiceName, ResolvedEndpoint>>;
978
+ /** Token URL for authentication. Undefined for public/no-auth services. */
979
+ /** @internal */
980
+ readonly _authUrl?: string;
981
+ /** OAuth2 scope to request with access tokens. */
982
+ /** @internal */
983
+ readonly _tokenScope?: string;
984
+ /** API path profiles for this platform */
985
+ /** @internal */
986
+ readonly _pathProfiles: PlatformPaths;
987
+ /** Cached TokenManagers by authUrl (for token sharing) */
988
+ /** @internal */
989
+ readonly _tokenManagers: Map<string, TokenProvider>;
990
+ /**
991
+ * Create a new TimebackProvider.
992
+ *
993
+ * @param config - Provider configuration (env-based, explicit URL, or per-service)
994
+ * @throws {Error} If configuration is invalid or missing required fields
995
+ */
996
+ constructor(config: TimebackProviderConfig);
997
+ /**
998
+ * Get the resolved endpoint for a specific service.
999
+ *
1000
+ * @param service - Service name (oneroster, caliper, edubridge, qti, powerpath)
1001
+ * @returns Resolved endpoint with baseUrl and authUrl
1002
+ * @throws If the service is not configured in this provider
1003
+ */
1004
+ getEndpoint(service: ServiceName): ResolvedEndpoint;
1005
+ /**
1006
+ * Check if a service is available in this provider.
1007
+ *
1008
+ * @param service - Service name to check
1009
+ * @returns True if the service is configured
1010
+ */
1011
+ hasService(service: ServiceName): boolean;
1012
+ /**
1013
+ * Get all configured service names.
1014
+ *
1015
+ * @returns Array of service names available in this provider
1016
+ */
1017
+ getAvailableServices(): ServiceName[];
1018
+ /**
1019
+ * Get the token URL for this provider.
1020
+ * @returns The token URL for authentication
1021
+ */
1022
+ getTokenUrl(): string | undefined;
1023
+ /**
1024
+ * Get endpoint with paths for a service that has path configuration.
1025
+ *
1026
+ * @param service - Service name that has paths in PlatformPaths
1027
+ * @returns Resolved endpoint with baseUrl, authUrl, and paths
1028
+ * @throws If service is not configured or not supported on this platform
1029
+ */
1030
+ getEndpointWithPaths<S extends PathEnabledService>(service: S & ServiceName): ResolvedEndpoint & {
1031
+ paths: NonNullable<PlatformPaths[S]>;
1032
+ };
1033
+ /**
1034
+ * Get all path profiles for this provider (raw, may contain nulls).
1035
+ *
1036
+ * @returns Platform path profiles
1037
+ */
1038
+ getPaths(): PlatformPaths;
1039
+ /**
1040
+ * Get paths for a specific service.
1041
+ *
1042
+ * @param service - Service name
1043
+ * @returns Path configuration for the service
1044
+ * @throws If the service is not supported on this platform
1045
+ */
1046
+ getServicePaths<S extends PathEnabledService>(service: S): NonNullable<PlatformPaths[S]>;
1047
+ /**
1048
+ * Check if a service is supported on this platform.
1049
+ *
1050
+ * @param service - Service name
1051
+ * @returns true if the service has path configuration
1052
+ */
1053
+ hasServiceSupport(service: PathEnabledService): boolean;
1054
+ /**
1055
+ * Get a TokenProvider for a specific service.
1056
+ *
1057
+ * TokenProviders are cached by authUrl, so services sharing the same
1058
+ * token endpoint will share the same cached OAuth tokens.
1059
+ *
1060
+ * @param service - Service name (oneroster, caliper, edubridge, qti, powerpath)
1061
+ * @returns Cached TokenProvider for the service's token endpoint, or undefined for public/no-auth services
1062
+ * @throws If the service is not configured in this provider
1063
+ * @throws If auth is required but not configured
1064
+ */
1065
+ getTokenProvider(service: ServiceName): TokenProvider | undefined;
1066
+ /**
1067
+ * Verify that OAuth authentication is working.
1068
+ *
1069
+ * Attempts to acquire a token using the provider's credentials.
1070
+ * Returns a health check result with success/failure and latency info.
1071
+ *
1072
+ * @returns Auth check result
1073
+ * @throws {Error} If no auth is configured on this provider
1074
+ */
1075
+ checkAuth(): Promise<AuthCheckResult$1>;
1076
+ /**
1077
+ * Invalidate all cached OAuth tokens.
1078
+ *
1079
+ * Call this when closing the client or when tokens need to be refreshed.
1080
+ * New tokens will be acquired on the next API call.
1081
+ */
1082
+ invalidateTokens(): void;
723
1083
  }
724
1084
 
725
1085
  /**
726
- * Result from syncing a course.
1086
+ * Transport Types
1087
+ *
1088
+ * Types for HTTP transport layer.
727
1089
  */
728
- interface LessonPlanCourseSyncResult {
729
- lessonPlansAffected: string[]
730
- }
731
1090
 
732
1091
  /**
733
- * Response containing a lesson plan.
1092
+ * Fetch function signature for HTTP requests.
1093
+ * Avoids Bun-specific extensions on `typeof fetch`.
734
1094
  */
735
- interface LessonPlanResponse {
736
- lessonPlan: Record<string, unknown>
1095
+ type FetchFn = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
1096
+ /**
1097
+ * HTTP request options.
1098
+ */
1099
+ interface RequestOptions {
1100
+ /** HTTP method */
1101
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
1102
+ /** Query parameters to append to the URL */
1103
+ params?: Record<string, string | number | boolean | undefined>;
1104
+ /** Request body (will be JSON-serialized) */
1105
+ body?: unknown;
1106
+ /** Additional headers to include */
1107
+ headers?: Record<string, string>;
1108
+ /**
1109
+ * Unique identifier for this request.
1110
+ * Used for log correlation and debugging.
1111
+ * Auto-generated if not provided.
1112
+ */
1113
+ requestId?: string;
737
1114
  }
738
-
739
1115
  /**
740
- * Response containing course progress.
1116
+ * Auth credentials for environment mode.
1117
+ * Token URL is derived automatically from environment.
741
1118
  */
742
- interface CourseProgressResponse {
743
- lineItems: Record<string, unknown>[]
1119
+ interface EnvAuth {
1120
+ clientId: string;
1121
+ clientSecret: string;
744
1122
  }
745
-
746
1123
  /**
747
- * Result from updating student item response.
1124
+ * Auth credentials for explicit mode.
1125
+ * Requires explicit authUrl for custom APIs.
748
1126
  */
749
- interface UpdateStudentItemResponseResult {
750
- success?: boolean
751
- [key: string]: unknown
1127
+ interface ExplicitAuth {
1128
+ clientId: string;
1129
+ clientSecret: string;
1130
+ authUrl: string;
752
1131
  }
753
-
754
- // ═══════════════════════════════════════════════════════════════════════════════
755
- // TEST OUT (self-elected)
756
- // ═══════════════════════════════════════════════════════════════════════════════
757
-
758
1132
  /**
759
- * Result from checking test-out eligibility for a student/subject.
1133
+ * Base configuration options shared by all modes.
760
1134
  */
761
- interface GetTestOutEligibilityResponse {
762
- eligible: boolean
763
- reason?: string
1135
+ interface BaseConfig {
1136
+ /** Request timeout in milliseconds */
1137
+ timeout?: number;
1138
+ /** Custom fetch implementation */
1139
+ fetch?: FetchFn;
764
1140
  }
765
-
766
1141
  /**
767
- * Result from creating a self-elected test-out assignment.
1142
+ * Internal resolved transport configuration.
768
1143
  */
769
- interface MakeExternalStudentTestOutAssignmentResponse {
770
- success: boolean
771
- data?: Record<string, unknown>
1144
+ interface ResolvedTransportConfig {
1145
+ /** Base URL of the API */
1146
+ baseUrl: string;
1147
+ /** Request timeout in milliseconds */
1148
+ timeout: number;
1149
+ /** Fetch implementation */
1150
+ fetch: FetchFn;
1151
+ /** Token provider for authentication. Undefined for public/no-auth services. */
1152
+ tokenProvider?: TokenProvider;
772
1153
  }
773
-
774
- // ═══════════════════════════════════════════════════════════════════════════════
775
- // RENDER CONFIG
776
- // ═══════════════════════════════════════════════════════════════════════════════
777
-
778
1154
  /**
779
- * Result from upserting render configs for one or more courses.
1155
+ * Transport configuration with explicit auth.
780
1156
  */
781
- interface RenderConfigUpsertResponse {
782
- updated: string[]
1157
+ interface TransportConfigWithAuth extends BaseConfig {
1158
+ baseUrl: string;
1159
+ auth: ExplicitAuth;
1160
+ tokenProvider?: never;
783
1161
  }
784
-
785
1162
  /**
786
- * Render config for a single course.
1163
+ * Transport configuration with shared token provider.
787
1164
  */
788
- interface RenderConfigGetResponse {
789
- courseId: string
790
- rendererId: string
791
- rendererUrl: string
792
- rendererVersion?: string | null
793
- suppressFeedback: boolean
794
- suppressCorrectResponse: boolean
1165
+ interface TransportConfigWithTokenProvider extends BaseConfig {
1166
+ baseUrl: string;
1167
+ tokenProvider: TokenProvider;
1168
+ auth?: never;
795
1169
  }
796
-
797
1170
  /**
798
- * Result from deleting a render config.
1171
+ * Transport configuration for public/no-auth services.
799
1172
  */
800
- interface RenderConfigDeleteResponse {
801
- deleted: string
1173
+ interface TransportConfigNoAuth extends BaseConfig {
1174
+ baseUrl: string;
1175
+ auth?: never;
1176
+ tokenProvider?: never;
802
1177
  }
803
-
804
- // ═══════════════════════════════════════════════════════════════════════════════
805
- // SYLLABUS
806
- // ═══════════════════════════════════════════════════════════════════════════════
807
-
808
1178
  /**
809
- * Response containing syllabus data.
1179
+ * Configuration for BaseTransport.
1180
+ */
1181
+ type BaseTransportConfig = TransportConfigWithAuth | TransportConfigWithTokenProvider | TransportConfigNoAuth;
1182
+ /**
1183
+ * Options for creating a BaseTransport.
810
1184
  */
811
- interface SyllabusResponse {
812
- syllabus?: unknown
1185
+ interface BaseTransportOptions {
1186
+ /** Transport configuration */
1187
+ config: BaseTransportConfig;
1188
+ /** Logger instance for request/response logging */
1189
+ logger: Logger;
813
1190
  }
814
-
815
- type input<T> = T extends {
816
- _zod: {
817
- input: any;
1191
+ /**
1192
+ * Result of an auth check operation.
1193
+ */
1194
+ interface AuthCheckResult {
1195
+ /** Whether auth succeeded */
1196
+ ok: boolean;
1197
+ /** Time taken to complete the check (ms) */
1198
+ latencyMs: number;
1199
+ /** Error message if failed */
1200
+ error?: string;
1201
+ /** Detailed check results */
1202
+ checks: {
1203
+ /** Token acquisition succeeded */
1204
+ tokenAcquisition: boolean;
818
1205
  };
819
- } ? T["_zod"]["input"] : unknown;
1206
+ }
820
1207
 
821
1208
  /**
822
- * PowerPath Schemas
1209
+ * Base Transport Layer
1210
+ *
1211
+ * HTTP transport with OAuth2 authentication, retries, and error handling.
1212
+ * Clients can extend this for protocol-specific features.
823
1213
  *
824
- * Zod schemas for the PowerPath adaptive learning API.
825
1214
  */
1215
+ /**
1216
+ * Base HTTP transport layer for API communication.
1217
+ *
1218
+ * Handles OAuth2 authentication, request/response lifecycle,
1219
+ * and automatic retries for transient failures.
1220
+ *
1221
+ * Clients can extend this class to add protocol-specific features
1222
+ * like custom error parsing or pagination.
1223
+ */
1224
+ declare class BaseTransport {
1225
+ protected readonly config: ResolvedTransportConfig;
1226
+ protected readonly log: Logger;
1227
+ /**
1228
+ * Create a new BaseTransport instance.
1229
+ *
1230
+ * @param options - Transport options with config and logger
1231
+ */
1232
+ constructor(options: BaseTransportOptions);
1233
+ /**
1234
+ * The base URL for API requests.
1235
+ * @returns The base URL
1236
+ */
1237
+ get baseUrl(): string;
1238
+ /**
1239
+ * Make an authenticated request to the API.
1240
+ *
1241
+ * Automatically retries on transient failures (429, 503).
1242
+ *
1243
+ * @template T - Expected response type
1244
+ * @param path - API endpoint path
1245
+ * @param options - Request options including method, params, body
1246
+ * @returns Parsed JSON response
1247
+ * @throws {ApiError} On API errors (4xx/5xx responses)
1248
+ */
1249
+ request<T>(path: string, options?: RequestOptions): Promise<T>;
1250
+ /**
1251
+ * Check whether a resource exists at the given path.
1252
+ *
1253
+ * Returns `true` for successful 2xx responses, `false` only for 404 Not Found,
1254
+ * and rethrows all other errors.
1255
+ *
1256
+ * @param path - API endpoint path
1257
+ * @param options - Request options including method, params, body
1258
+ * @returns Promise resolving to whether the resource exists
1259
+ */
1260
+ exists(path: string, options?: RequestOptions): Promise<boolean>;
1261
+ /**
1262
+ * Make a raw request, returning the Response object.
1263
+ *
1264
+ * ## Retry Behavior
1265
+ * Automatically retries on transient failures (429, 503) with exponential
1266
+ * backoff. Respects Retry-After header when present.
1267
+ *
1268
+ * ## Timeout Behavior
1269
+ * Uses an operation-level timeout that spans ALL retry attempts.
1270
+ * If configured timeout is 30s, the entire operation (including retries
1271
+ * and backoff delays) must complete within 30s total.
1272
+ *
1273
+ * ## Flow
1274
+ * 1. Build URL from path and query params
1275
+ * 2. Start operation timer
1276
+ * 3. Loop up to MAX_RETRIES times:
1277
+ * a. Check if we've exceeded the operation deadline
1278
+ * b. Get OAuth token (may be cached)
1279
+ * c. Make the HTTP request with per-request timeout
1280
+ * d. If 429/503 and not last attempt → calculate backoff and retry
1281
+ * e. If other error → throw appropriate ApiError subclass
1282
+ * f. If success → return response
1283
+ * 4. If all retries exhausted → throw "Max retries exceeded"
1284
+ *
1285
+ * @param path - API endpoint path (relative to baseUrl)
1286
+ * @param options - Request options (method, params, body, headers)
1287
+ * @returns Raw fetch Response for custom handling
1288
+ * @throws {ApiError} On timeout, non-retryable errors, or max retries exceeded
1289
+ */
1290
+ requestRaw(path: string, options?: RequestOptions): Promise<Response>;
1291
+ /**
1292
+ * Get a valid OAuth2 access token.
1293
+ * @returns Promise resolving to access token or undefined
1294
+ */
1295
+ protected getAccessToken(): Promise<string | undefined>;
1296
+ /**
1297
+ * Construct full URL with query parameters.
1298
+ *
1299
+ * @param path - The relative path or absolute URL
1300
+ * @param params - Query parameters
1301
+ * @returns Full URL string
1302
+ * @throws {Error} If path is an absolute URL (security protection)
1303
+ */
1304
+ protected buildUrl(path: string, params?: Record<string, string | number | boolean | undefined>): string;
1305
+ /**
1306
+ * Parse successful response or delegate to error handler.
1307
+ * @param response - The fetch Response
1308
+ * @returns Parsed response as type T
1309
+ */
1310
+ protected handleResponse<T>(response: Response): Promise<T>;
1311
+ /**
1312
+ * Parse JSON response with context-preserving error handling.
1313
+ *
1314
+ * Unlike raw `response.json()`, this method:
1315
+ * - Logs structured error context (URL, status, content-type, body preview)
1316
+ * - Throws `ApiError` with `parseError` and `body` in the response object
1317
+ * - Aids debugging when upstream services return malformed JSON
1318
+ *
1319
+ * @template T - Expected shape of the parsed response
1320
+ * @param response - The fetch Response to parse
1321
+ * @returns Parsed JSON as type T
1322
+ * @throws {ApiError} When JSON parsing fails, with status code and body preview
1323
+ */
1324
+ protected parseJsonResponse<T>(response: Response): Promise<T>;
1325
+ /**
1326
+ * Parse error response and throw appropriate ApiError subclass.
1327
+ *
1328
+ * Handles both JSON and non-JSON error responses gracefully.
1329
+ * Clients can override this to add protocol-specific error parsing.
1330
+ *
1331
+ * @param response - The error Response (status >= 400)
1332
+ * @param requestId - Request ID for log correlation
1333
+ * @throws {UnauthorizedError} For 401 responses (also invalidates token)
1334
+ * @throws {ForbiddenError} For 403 responses
1335
+ * @throws {NotFoundError} For 404 responses
1336
+ * @throws {ValidationError} For 422 responses
1337
+ * @throws {ApiError} For all other error status codes
1338
+ */
1339
+ protected handleErrorResponse(response: Response, requestId?: string): Promise<never>;
1340
+ /**
1341
+ * Extract error message from response body.
1342
+ *
1343
+ * Checks common error formats:
1344
+ * - `message` (most APIs)
1345
+ * - `error` (some APIs)
1346
+ * - `imsx_description` (IMS Global: OneRoster, Caliper, QTI)
1347
+ *
1348
+ * Override in client transports for API-specific error formats
1349
+ * not covered here (e.g., Edubridge's `errors[]` array format).
1350
+ *
1351
+ * @param body - The error response body
1352
+ * @param fallback - Fallback message if none found
1353
+ * @returns Extracted error message
1354
+ */
1355
+ protected extractErrorMessage(body: unknown, fallback: string): string;
1356
+ /**
1357
+ * Delay execution for retry backoff.
1358
+ *
1359
+ * @param ms - Number of milliseconds to delay
1360
+ * @returns Promise that resolves after delay
1361
+ */
1362
+ protected sleep(ms: number): Promise<void>;
1363
+ /**
1364
+ * Parse Retry-After header value.
1365
+ *
1366
+ * Handles both formats per RFC 7231:
1367
+ * - Numeric seconds: "120"
1368
+ * - HTTP-date: "Wed, 21 Oct 2025 07:28:00 GMT"
1369
+ *
1370
+ * @param retryAfter - Retry-After header value
1371
+ * @param attempt - Current attempt number (0-based)
1372
+ * @returns Delay in milliseconds
1373
+ */
1374
+ protected parseRetryAfter(retryAfter: string | null, attempt: number): number;
1375
+ }
826
1376
 
1377
+ /**
1378
+ * Pagination Utilities
1379
+ *
1380
+ * Helpers for iterating over paginated API responses.
1381
+ */
827
1382
 
828
-
829
- declare const ExternalTestOut = ExternalTestBase.extend({
830
- lessonType: z.literal('test-out'),
831
- xp: z.number(),
832
- })
833
-
834
- declare const ExternalPlacement = ExternalTestBase.extend({
835
- lessonType: z.literal('placement'),
836
- courseIdOnFail: NonEmptyString.nullable().optional(),
837
- xp: z.number().optional(),
838
- })
839
-
840
- declare const PowerPathCreateExternalPlacementTestInput = ExternalPlacement
841
-
842
- declare const PowerPathCreateExternalTestOutInput = ExternalTestOut
843
-
844
- declare const PowerPathCreateInternalTestInput = z.discriminatedUnion('testType', [
845
- InternalTestBase.extend({
846
- testType: z.literal('qti'),
847
- qti: z.object({
848
- url: z.url(),
849
- title: NonEmptyString.optional(),
850
- metadata: z.record(z.string(), z.unknown()).optional(),
851
- }),
852
- }),
853
- InternalTestBase.extend({
854
- testType: z.literal('assessment-bank'),
855
- assessmentBank: z.object({
856
- resources: z
857
- .array(
858
- z.object({
859
- url: z.url(),
860
- title: NonEmptyString.optional(),
861
- metadata: z.record(z.string(), z.unknown()).optional(),
862
- }),
863
- )
864
- .min(1),
865
- }),
866
- }),
867
- ])
868
-
869
- declare const PowerPathCreateNewAttemptInput = z.object({
870
- student: NonEmptyString,
871
- lesson: NonEmptyString,
872
- })
873
-
874
- declare const PowerPathFinalStudentAssessmentResponseInput = z.object({
875
- student: NonEmptyString,
876
- lesson: NonEmptyString,
877
- })
878
-
879
- declare const PowerPathLessonPlansCreateInput = z.object({
880
- courseId: NonEmptyString,
881
- userId: NonEmptyString,
882
- classId: NonEmptyString.optional(),
883
- })
884
-
885
- declare const PowerPathLessonPlanOperationInput = z.union([
886
- z.object({
887
- type: z.literal('set-skipped'),
888
- payload: z.object({
889
- target: LessonPlanTarget,
890
- value: z.boolean(),
891
- }),
892
- }),
893
- z.object({
894
- type: z.literal('add-custom-resource'),
895
- payload: z.object({
896
- resource_id: NonEmptyString,
897
- parent_component_id: NonEmptyString,
898
- skipped: z.boolean().optional(),
899
- }),
900
- }),
901
- z.object({
902
- type: z.literal('move-item-before'),
903
- payload: z.object({
904
- target: LessonPlanTarget,
905
- reference_id: NonEmptyString,
906
- }),
907
- }),
908
- z.object({
909
- type: z.literal('move-item-after'),
910
- payload: z.object({
911
- target: LessonPlanTarget,
912
- reference_id: NonEmptyString,
913
- }),
914
- }),
915
- z.object({
916
- type: z.literal('move-item-to-start'),
917
- payload: z.object({
918
- target: LessonPlanTarget,
919
- }),
920
- }),
921
- z.object({
922
- type: z.literal('move-item-to-end'),
923
- payload: z.object({
924
- target: LessonPlanTarget,
925
- }),
926
- }),
927
- z.object({
928
- type: z.literal('change-item-parent'),
929
- payload: z.object({
930
- target: LessonPlanTarget,
931
- new_parent_id: NonEmptyString,
932
- position: z.enum(['start', 'end']).optional(),
933
- }),
934
- }),
935
- ])
936
-
937
- declare const PowerPathLessonPlanOperationsInput = z.object({
938
- operation: PowerPathLessonPlanOperationInput,
939
- reason: NonEmptyString.optional(),
940
- })
941
-
942
- declare const PowerPathLessonPlanUpdateStudentItemResponseInput = z.object({
943
- studentId: NonEmptyString,
944
- componentResourceId: NonEmptyString,
945
- result: z.object({
946
- status: z.enum(['active', 'tobedeleted']),
947
- metadata: z.record(z.string(), z.unknown()).optional(),
948
- score: z.number().optional(),
949
- textScore: NonEmptyString.optional(),
950
- scoreDate: z.string().datetime(),
951
- scorePercentile: z.number().optional(),
952
- scoreStatus: ScoreStatus,
953
- comment: NonEmptyString.optional(),
954
- learningObjectiveSet: z
955
- .array(
956
- z.object({
957
- source: NonEmptyString,
958
- learningObjectiveResults: z.array(
959
- z.object({
960
- learningObjectiveId: NonEmptyString,
961
- score: z.number().optional(),
962
- textScore: NonEmptyString.optional(),
963
- }),
964
- ),
965
- }),
966
- )
967
- .optional(),
968
- inProgress: NonEmptyString.optional(),
969
- incomplete: NonEmptyString.optional(),
970
- late: NonEmptyString.optional(),
971
- missing: NonEmptyString.optional(),
972
- }),
973
- })
974
-
975
- declare const PowerPathMakeExternalTestAssignmentInput = z.object({
976
- student: NonEmptyString,
977
- lesson: NonEmptyString,
978
- applicationName: NonEmptyString.optional(),
979
- testId: NonEmptyString.optional(),
980
- skipCourseEnrollment: z.boolean().optional(),
981
- })
982
-
983
- declare const PowerPathPlacementResetUserPlacementInput = z.object({
984
- student: NonEmptyString,
985
- subject: TimebackSubject,
986
- })
987
-
988
- declare const PowerPathResetAttemptInput = z.object({
989
- student: NonEmptyString,
990
- lesson: NonEmptyString,
991
- })
992
-
993
- declare const PowerPathScreeningResetSessionInput = z.object({
994
- userId: NonEmptyString,
995
- })
996
-
997
- declare const PowerPathScreeningAssignTestInput = z.object({
998
- userId: NonEmptyString,
999
- subject: z.enum(['Math', 'Reading', 'Language', 'Science']),
1000
- })
1001
-
1002
- declare const PowerPathTestAssignmentsCreateInput = z.object({
1003
- student: NonEmptyString,
1004
- subject: TimebackSubject,
1005
- grade: TimebackGrade,
1006
- testName: NonEmptyString.optional(),
1007
- })
1008
-
1009
- declare const PowerPathTestAssignmentsUpdateInput = z.object({
1010
- testName: NonEmptyString,
1011
- })
1012
-
1013
- declare const PowerPathTestAssignmentsBulkInput = z.object({
1014
- items: z.array(PowerPathTestAssignmentItemInput),
1015
- })
1016
-
1017
- declare const PowerPathTestAssignmentsImportInput = z.object({
1018
- spreadsheetUrl: z.url(),
1019
- sheet: NonEmptyString,
1020
- })
1021
-
1022
- declare const PowerPathTestAssignmentsListParams = z.object({
1023
- student: NonEmptyString,
1024
- status: z
1025
- .enum(['assigned', 'in_progress', 'completed', 'failed', 'expired', 'cancelled'])
1026
- .optional(),
1027
- subject: NonEmptyString.optional(),
1028
- grade: TimebackGrade.optional(),
1029
- limit: z.number().int().positive().max(3000).optional(),
1030
- offset: z.number().int().nonnegative().optional(),
1031
- })
1032
-
1033
- declare const PowerPathTestAssignmentsAdminParams = z.object({
1034
- student: NonEmptyString.optional(),
1035
- status: z
1036
- .enum(['assigned', 'in_progress', 'completed', 'failed', 'expired', 'cancelled'])
1037
- .optional(),
1038
- subject: NonEmptyString.optional(),
1039
- grade: TimebackGrade.optional(),
1040
- limit: z.number().int().positive().max(3000).optional(),
1041
- offset: z.number().int().nonnegative().optional(),
1042
- })
1043
-
1044
- declare const PowerPathUpdateStudentQuestionResponseInput = z
1045
- .object({
1046
- student: NonEmptyString,
1047
- question: NonEmptyString,
1048
- response: z.union([NonEmptyString, z.array(NonEmptyString)]).optional(),
1049
- responses: z
1050
- .record(z.string(), z.union([NonEmptyString, z.array(NonEmptyString)]))
1051
- .optional(),
1052
- lesson: NonEmptyString,
1053
- rendererOutcomes: z
1054
- .object({
1055
- score: z.number(),
1056
- maxScore: z.number().min(0),
1057
- isCorrect: z.boolean(),
1058
- })
1059
- .optional(),
1060
- playerState: z.string().optional(),
1061
- })
1062
- .refine(data => data.response !== undefined || data.responses !== undefined, {
1063
- message: "Either 'response' or 'responses' must be provided",
1064
- path: ['response', 'responses'],
1065
- })
1066
- .transform(data => {
1067
- if (data.response !== undefined && data.responses === undefined) {
1068
- return { ...data, responses: { RESPONSE: data.response } }
1069
- }
1070
-
1071
- return data
1072
- })
1073
-
1074
- declare const PowerPathGetAssessmentProgressParams = z.object({
1075
- student: NonEmptyString,
1076
- lesson: NonEmptyString,
1077
- attempt: z.number().int().positive().optional(),
1078
- })
1079
-
1080
- declare const PowerPathGetNextQuestionParams = z.object({
1081
- student: NonEmptyString,
1082
- lesson: NonEmptyString,
1083
- })
1084
-
1085
- declare const PowerPathGetAttemptsParams = z.object({
1086
- student: NonEmptyString,
1087
- lesson: NonEmptyString,
1088
- })
1089
-
1090
- declare const PowerPathTestOutParams = z.object({
1091
- student: NonEmptyString,
1092
- course: NonEmptyString,
1093
- })
1094
-
1095
- declare const PowerPathImportExternalTestAssignmentResultsParams = z.object({
1096
- student: NonEmptyString,
1097
- lesson: NonEmptyString,
1098
- applicationName: NonEmptyString.optional(),
1099
- })
1100
-
1101
- declare const PowerPathPlacementQueryParams = z.object({
1102
- student: NonEmptyString,
1103
- subject: TimebackSubject,
1104
- })
1105
-
1106
- declare const PowerPathMakeExternalStudentTestOutAssignmentInput = z.object({
1107
- oneRosterSourcedId: NonEmptyString,
1108
- subject: NonEmptyString,
1109
- })
1110
-
1111
- declare const PowerPathRenderConfigUpsertInput = z.object({
1112
- courseIds: z.array(NonEmptyString).min(1),
1113
- rendererId: NonEmptyString,
1114
- rendererUrl: z.url(),
1115
- rendererVersion: NonEmptyString.optional(),
1116
- suppressFeedback: z.boolean().optional(),
1117
- suppressCorrectResponse: z.boolean().optional(),
1118
- })
1119
-
1120
- declare const PowerPathSyllabusQueryParams = z.object({
1121
- status: z.enum(['active', 'tobedeleted']).optional(),
1122
- })
1123
-
1124
- // ═══════════════════════════════════════════════════════════════════════════════
1125
- // TYPE EXPORTS (REQUEST INPUTS)
1126
- // ═══════════════════════════════════════════════════════════════════════════════
1127
-
1128
- // Shorter type aliases (like OneRoster pattern: schema = OneRosterFoo, type = Foo)
1129
- type CreateExternalPlacementTestInput = input<
1130
- typeof PowerPathCreateExternalPlacementTestInput
1131
- >
1132
- type CreateExternalTestOutInput = input<typeof PowerPathCreateExternalTestOutInput>
1133
- type CreateInternalTestInput = input<typeof PowerPathCreateInternalTestInput>
1134
- type CreateNewAttemptInput = input<typeof PowerPathCreateNewAttemptInput>
1135
- type FinalStudentAssessmentResponseInput = input<
1136
- typeof PowerPathFinalStudentAssessmentResponseInput
1137
- >
1138
- type LessonPlansCreateInput = input<typeof PowerPathLessonPlansCreateInput>
1139
- type LessonPlanOperationInput = input<typeof PowerPathLessonPlanOperationInput>
1140
- type LessonPlanOperationsInput = input<typeof PowerPathLessonPlanOperationsInput>
1141
- type LessonPlanUpdateStudentItemResponseInput = input<
1142
- typeof PowerPathLessonPlanUpdateStudentItemResponseInput
1143
- >
1144
- type MakeExternalTestAssignmentInput = input<
1145
- typeof PowerPathMakeExternalTestAssignmentInput
1146
- >
1147
- type PlacementResetUserPlacementInput = input<
1148
- typeof PowerPathPlacementResetUserPlacementInput
1149
- >
1150
- type ResetAttemptInput = input<typeof PowerPathResetAttemptInput>
1151
- type ScreeningResetSessionInput = input<typeof PowerPathScreeningResetSessionInput>
1152
- type ScreeningAssignTestInput = input<typeof PowerPathScreeningAssignTestInput>
1153
- type TestAssignmentsCreateInput = input<typeof PowerPathTestAssignmentsCreateInput>
1154
- type TestAssignmentsUpdateInput = input<typeof PowerPathTestAssignmentsUpdateInput>
1155
- type TestAssignmentsBulkInput = input<typeof PowerPathTestAssignmentsBulkInput>
1156
- type TestAssignmentsImportInput = input<typeof PowerPathTestAssignmentsImportInput>
1157
- type TestAssignmentsListParams = input<typeof PowerPathTestAssignmentsListParams>
1158
- type TestAssignmentsAdminParams = input<typeof PowerPathTestAssignmentsAdminParams>
1159
- type UpdateStudentQuestionResponseInput = input<
1160
- typeof PowerPathUpdateStudentQuestionResponseInput
1161
- >
1162
- type GetAssessmentProgressParams = input<typeof PowerPathGetAssessmentProgressParams>
1163
- type GetNextQuestionParams = input<typeof PowerPathGetNextQuestionParams>
1164
- type GetAttemptsParams = input<typeof PowerPathGetAttemptsParams>
1165
- type TestOutParams = input<typeof PowerPathTestOutParams>
1166
- type ImportExternalTestAssignmentResultsParams = input<
1167
- typeof PowerPathImportExternalTestAssignmentResultsParams
1168
- >
1169
- type MakeExternalStudentTestOutAssignmentInput = input<
1170
- typeof PowerPathMakeExternalStudentTestOutAssignmentInput
1171
- >
1172
- type PlacementQueryParams = input<typeof PowerPathPlacementQueryParams>
1173
- type RenderConfigUpsertInput = input<typeof PowerPathRenderConfigUpsertInput>
1174
- type SyllabusQueryParams = input<typeof PowerPathSyllabusQueryParams>
1383
+ /**
1384
+ * Async iterator for paginated API responses.
1385
+ *
1386
+ * Automatically fetches subsequent pages as you iterate, making it easy
1387
+ * to process large datasets without manual pagination handling.
1388
+ *
1389
+ * @typeParam T - The type of items being paginated
1390
+ *
1391
+ * @example
1392
+ * ```typescript
1393
+ * // Iterate over all items
1394
+ * for await (const user of paginator) {
1395
+ * console.log(user.name)
1396
+ * }
1397
+ * ```
1398
+ *
1399
+ * @example
1400
+ * ```typescript
1401
+ * // Collect all items into an array
1402
+ * const allUsers = await paginator.toArray()
1403
+ * ```
1404
+ *
1405
+ * @example
1406
+ * ```typescript
1407
+ * // Get just the first page
1408
+ * const page = await paginator.firstPage()
1409
+ * console.log(`Got ${page.data.length} of ${page.total} users`)
1410
+ * ```
1411
+ */
1412
+ declare class Paginator$1<T, F = unknown> implements AsyncIterable<T> {
1413
+ private readonly fetcher;
1414
+ private readonly path;
1415
+ private readonly params;
1416
+ private readonly max?;
1417
+ private readonly unwrapKey?;
1418
+ private readonly log;
1419
+ private readonly transform?;
1420
+ private readonly paginationStyle;
1421
+ /**
1422
+ * Create a new Paginator.
1423
+ *
1424
+ * @param options - Paginator configuration
1425
+ */
1426
+ constructor(options: PaginatorOptions<T, F>);
1427
+ /**
1428
+ * Builds query parameters for the paginated request.
1429
+ *
1430
+ * Converts the type-safe `where` clause to a filter string for the API,
1431
+ * and merges with other list parameters (sort, orderBy, fields, search).
1432
+ * Excludes client-side params like `max` that shouldn't be sent to the API.
1433
+ *
1434
+ * Uses the configured pagination style:
1435
+ * - `'offset'`: Sends `{ limit, offset }` params
1436
+ * - `'page'`: Sends `{ limit, page }` params (1-indexed)
1437
+ *
1438
+ * @param limit - Maximum items per page
1439
+ * @param offset - Number of items to skip (converted to page if using page style)
1440
+ * @returns Query parameters ready for the request
1441
+ */
1442
+ private buildRequestParams;
1443
+ /**
1444
+ * Extracts and validates items from response data.
1445
+ *
1446
+ * Handles two response formats:
1447
+ * - Direct array: `[item1, item2, ...]`
1448
+ * - Wrapped object: `{ users: [item1, item2, ...] }` (when unwrapKey is set)
1449
+ *
1450
+ * @param data - Raw response data from the API
1451
+ * @param pageNumber - Current page number (for error messages)
1452
+ * @returns Validated array of items
1453
+ * @throws {Error} If extracted data is not an array
1454
+ */
1455
+ private extractItems;
1456
+ /**
1457
+ * Validates that extracted data is an array.
1458
+ *
1459
+ * Protects against malformed API responses that could cause:
1460
+ * - Infinite loops (empty non-array values)
1461
+ * - Unexpected iteration (strings yield characters, not items)
1462
+ * - Runtime crashes (objects are not iterable)
1463
+ *
1464
+ * @param data - Data to validate (should be an array)
1465
+ * @param pageNumber - Current page number (for error messages)
1466
+ * @returns The data cast to T[] if valid
1467
+ * @throws {Error} If data is not an array (with helpful message including unwrapKey)
1468
+ */
1469
+ private validateItems;
1470
+ /**
1471
+ * Determines if more pages are available based on response metadata.
1472
+ *
1473
+ * Uses a three-tier fallback strategy:
1474
+ * 1. Link header (most reliable)
1475
+ * 2. X-Total-Count header
1476
+ * 3. Full page heuristic (assumes more if page is full and no total provided)
1477
+ *
1478
+ * Always returns false if the page is empty to prevent infinite loops
1479
+ * from buggy servers that return hasMore: true with no data.
1480
+ * @param response - Response with pagination metadata
1481
+ * @param itemCount - Number of items in current page
1482
+ * @param offset - Current offset
1483
+ * @param limit - Current limit
1484
+ * @returns True if more pages are available
1485
+ */
1486
+ private hasMorePages;
1487
+ /**
1488
+ * Async iterator implementation.
1489
+ *
1490
+ * Yields items one at a time, automatically fetching new pages as needed.
1491
+ * Stops when `max` items have been yielded (if specified).
1492
+ *
1493
+ * @yields Items of type T from paginated responses
1494
+ */
1495
+ [Symbol.asyncIterator](): AsyncIterator<T>;
1496
+ /**
1497
+ * Collect all items into an array.
1498
+ *
1499
+ * **Warning**: Use with caution on large datasets as this loads
1500
+ * all items into memory. Consider iterating with `for await...of`
1501
+ * for better memory efficiency.
1502
+ *
1503
+ * @param options - Optional configuration
1504
+ * @param options.maxItems - Maximum items to collect (default: 10,000).
1505
+ * Throws if limit is reached. Set to `Infinity` to disable.
1506
+ * @returns Promise resolving to an array of all items
1507
+ * @throws {Error} If maxItems limit is exceeded
1508
+ */
1509
+ toArray(options?: ToArrayOptions): Promise<T[]>;
1510
+ /**
1511
+ * Fetch only the first page of results.
1512
+ *
1513
+ * Useful when you need pagination metadata (total count, hasMore)
1514
+ * or want to implement custom pagination UI.
1515
+ *
1516
+ * @returns Promise resolving to the first page with metadata
1517
+ */
1518
+ firstPage(): Promise<PageResult<T>>;
1519
+ }
1175
1520
 
1176
1521
  /**
1177
1522
  * Transport interface for PowerPath client.
@@ -1525,7 +1870,7 @@ declare class TestOutResource {
1525
1870
  declare const PowerPathClient: {
1526
1871
  new (config?: PowerPathClientConfig): {
1527
1872
  readonly transport: PowerPathTransportLike;
1528
- readonly _provider?: _timeback_internal_client_infra.TimebackProvider | undefined;
1873
+ readonly _provider?: TimebackProvider | undefined;
1529
1874
  readonly assessments: AssessmentResource;
1530
1875
  readonly lessonPlans: LessonPlansResource;
1531
1876
  readonly placement: PlacementResource;
@@ -1535,7 +1880,7 @@ declare const PowerPathClient: {
1535
1880
  readonly testAssignments: TestAssignmentsResource;
1536
1881
  readonly testOut: TestOutResource;
1537
1882
  getTransport(): PowerPathTransportLike;
1538
- checkAuth(): Promise<_timeback_internal_client_infra.AuthCheckResult>;
1883
+ checkAuth(): Promise<AuthCheckResult>;
1539
1884
  };
1540
1885
  };
1541
1886
 
@@ -1622,4 +1967,4 @@ declare class Transport extends BaseTransport {
1622
1967
  }
1623
1968
 
1624
1969
  export { Paginator, PowerPathClient, Transport, createPowerPathClient };
1625
- export type { AssignmentResult, Attempt, BulkResult, CourseProgressResponse, CreateAttemptResponse, CreateExternalPlacementTestInput, CreateExternalTestOutInput, CreateInternalTestInput, CreateNewAttemptInput, ExternalTestCapableLessonType, ExternalTestCreateResponse, FinalStudentAssessmentResponseInput, FinalizeAssessmentResponse, GetAllPlacementTestsResponse, GetAssessmentProgressParams, GetAssessmentProgressResponse, GetAttemptsParams, GetAttemptsResponse, GetCurrentLevelResponse, GetNextPlacementTestResponse, GetNextQuestionParams, GetNextQuestionResponse, GetSubjectProgressResponse, GetTestOutEligibilityResponse, ImportExternalResultsResponse, ImportExternalTestAssignmentResultsParams, InternalTestCreateResponse, LessonPlanCourseSyncResult, LessonPlanCreateResponse, LessonPlanOperation, LessonPlanOperationInput, LessonPlanOperationResult, LessonPlanOperationsInput, LessonPlanOperationsResponse, LessonPlanResponse, LessonPlanSyncResult, LessonPlanUpdateStudentItemResponseInput, LessonPlansCreateInput, MakeExternalStudentTestOutAssignmentInput, MakeExternalStudentTestOutAssignmentResponse, MakeExternalTestAssignmentInput, MakeExternalTestAssignmentResponse, PaginationMeta, PlacementQueryParams, PlacementResetUserPlacementInput, PowerPath100ProgressResponse, PowerPath100UpdateResponseResult, PowerPathClientConfig, PowerPathClientInstance, PowerPathLessonType, PowerPathQuestionContent, PowerPathQuestionDifficulty, PowerPathQuestionResult, PowerPathTestQuestion, QuizLikeLessonType, ResetAttemptInput, ResetAttemptResponse, ResetPlacementResponse, ResponseResult, ResponseResultFeedback, ScoreStatus, ScreeningAssignTestInput, ScreeningAssignTestResponse, ScreeningResetSessionInput, ScreeningResetSessionResponse, ScreeningResultsResponse, ScreeningSessionResponse, StandardProgressResponse, StandardUpdateResponseResult, SyllabusQueryParams, SyllabusResponse, TestAssignment, TestAssignmentStatus, TestAssignmentsAdminParams, TestAssignmentsBulkInput, TestAssignmentsCreateInput, TestAssignmentsImportInput, TestAssignmentsListParams, TestAssignmentsListResponse, TestAssignmentsUpdateInput, TestOutParams, TestOutResponse, UpdateStudentItemResponseResult, UpdateStudentQuestionResponseInput, UpdateStudentQuestionResponseResult };
1970
+ export type { AuthCheckResult, EnvAuth, Environment, ExplicitAuth, ListParams, PageResult, PowerPathClientConfig, PowerPathClientInstance };