@speakableio/core 1.0.57 → 1.0.59

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.
@@ -1,3888 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/entry-points/index.native.ts
31
- var index_native_exports = {};
32
- __export(index_native_exports, {
33
- ActivityPageType: () => ActivityPageType,
34
- BASE_MULTIPLE_CHOICE_FIELD_VALUES: () => BASE_MULTIPLE_CHOICE_FIELD_VALUES,
35
- BASE_REPEAT_FIELD_VALUES: () => BASE_REPEAT_FIELD_VALUES,
36
- BASE_RESPOND_FIELD_VALUES: () => BASE_RESPOND_FIELD_VALUES,
37
- CONVERSATION_PAGE_ACTIVITY_TYPES: () => CONVERSATION_PAGE_ACTIVITY_TYPES,
38
- ConversationPageMode: () => ConversationPageMode,
39
- FeedbackTypesCard: () => FeedbackTypesCard,
40
- FsCtx: () => FsCtx,
41
- LENIENCY_OPTIONS: () => LENIENCY_OPTIONS,
42
- LeniencyCard: () => LeniencyCard,
43
- MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES: () => MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES,
44
- REPEAT_PAGE_ACTIVITY_TYPES: () => REPEAT_PAGE_ACTIVITY_TYPES,
45
- RESPOND_AUDIO_PAGE_ACTIVITY_TYPES: () => RESPOND_AUDIO_PAGE_ACTIVITY_TYPES,
46
- RESPOND_PAGE_ACTIVITY_TYPES: () => RESPOND_PAGE_ACTIVITY_TYPES,
47
- RESPOND_WRITE_PAGE_ACTIVITY_TYPES: () => RESPOND_WRITE_PAGE_ACTIVITY_TYPES,
48
- SPEAKABLE_ANALYTICS: () => SPEAKABLE_ANALYTICS,
49
- SPEAKABLE_NOTIFICATIONS: () => SPEAKABLE_NOTIFICATIONS,
50
- STUDENT_LEVELS_OPTIONS: () => STUDENT_LEVELS_OPTIONS,
51
- SpeakableNotificationTypes: () => SpeakableNotificationTypes,
52
- SpeakableProvider: () => SpeakableProvider,
53
- VerificationCardStatus: () => VerificationCardStatus,
54
- assignmentQueryKeys: () => assignmentQueryKeys,
55
- cardsQueryKeys: () => cardsQueryKeys,
56
- checkIsConversationPage: () => checkIsConversationPage,
57
- checkIsMCPage: () => checkIsMCPage,
58
- checkIsMediaPage: () => checkIsMediaPage,
59
- checkIsRepeatPage: () => checkIsRepeatPage,
60
- checkIsRespondAudioPage: () => checkIsRespondAudioPage,
61
- checkIsRespondPage: () => checkIsRespondPage,
62
- checkIsRespondWrittenPage: () => checkIsRespondWrittenPage,
63
- checkIsShortAnswerPage: () => checkIsShortAnswerPage,
64
- checkTypePageActivity: () => checkTypePageActivity,
65
- cleanString: () => cleanString,
66
- createAssignmentRepo: () => createAssignmentRepo,
67
- createCardRepo: () => createCardRepo,
68
- createFsClient: () => createFsClientNative,
69
- createSetRepo: () => createSetRepo,
70
- creditQueryKeys: () => creditQueryKeys,
71
- debounce: () => debounce,
72
- getCardFromCache: () => getCardFromCache,
73
- getLabelPage: () => getLabelPage,
74
- getPageMediaData: () => getPageMediaData,
75
- getPagePrompt: () => getPagePrompt,
76
- getPhraseLength: () => getPhraseLength,
77
- getRespondCardTool: () => getRespondCardTool,
78
- getSetFromCache: () => getSetFromCache,
79
- getSingleMediaPageData: () => getSingleMediaPageData,
80
- getTotalCompletedCards: () => getTotalCompletedCards,
81
- getTranscript: () => getTranscript,
82
- getTranscriptCycle: () => getTranscriptCycle,
83
- getWordHash: () => getWordHash,
84
- purify: () => purify,
85
- refsCardsFiresotre: () => refsCardsFiresotre,
86
- refsSetsFirestore: () => refsSetsFirestore,
87
- scoreQueryKeys: () => scoreQueryKeys,
88
- setsQueryKeys: () => setsQueryKeys,
89
- updateCardInCache: () => updateCardInCache,
90
- updateSetInCache: () => updateSetInCache,
91
- useActivity: () => useActivity,
92
- useActivityFeedbackAccess: () => useActivityFeedbackAccess,
93
- useAssignment: () => useAssignment,
94
- useBaseOpenAI: () => useBaseOpenAI,
95
- useCards: () => useCards,
96
- useClearScore: () => useClearScore,
97
- useClearScoreV2: () => useClearScoreV2,
98
- useCreateCard: () => useCreateCard,
99
- useCreateCards: () => useCreateCards,
100
- useCreateNotification: () => useCreateNotification,
101
- useGetCard: () => useGetCard,
102
- useOrganizationAccess: () => useOrganizationAccess,
103
- useScore: () => useScore,
104
- useSet: () => useSet,
105
- useSpeakableApi: () => useSpeakableApi,
106
- useSpeakableTranscript: () => useSpeakableTranscript,
107
- useSpeakableTranscriptCycle: () => useSpeakableTranscriptCycle,
108
- useSubmitAssignmentScore: () => useSubmitAssignmentScore,
109
- useSubmitPracticeScore: () => useSubmitPracticeScore,
110
- useUpdateCardScore: () => useUpdateCardScore,
111
- useUpdateScore: () => useUpdateScore,
112
- useUpdateStudentVocab: () => useUpdateStudentVocab,
113
- useUserCredits: () => useUserCredits
114
- });
115
- module.exports = __toCommonJS(index_native_exports);
116
-
117
- // src/providers/SpeakableProvider.tsx
118
- var import_react = require("react");
119
- var import_jsx_runtime = require("react/jsx-runtime");
120
- var FsCtx = (0, import_react.createContext)(null);
121
- function SpeakableProvider({
122
- user,
123
- children,
124
- queryClient,
125
- permissions,
126
- fsClient
127
- }) {
128
- const [speakableApi, setSpeakableApi] = (0, import_react.useState)(null);
129
- (0, import_react.useEffect)(() => {
130
- setSpeakableApi(fsClient);
131
- }, [fsClient]);
132
- if (!speakableApi) return null;
133
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
134
- FsCtx.Provider,
135
- {
136
- value: {
137
- speakableApi,
138
- queryClient,
139
- user,
140
- permissions
141
- },
142
- children
143
- }
144
- );
145
- }
146
- function useSpeakableApi() {
147
- const ctx = (0, import_react.useContext)(FsCtx);
148
- if (!ctx) throw new Error("useSpeakableApi must be used within a SpeakableProvider");
149
- return ctx;
150
- }
151
-
152
- // src/utils/error-handler.ts
153
- var ServiceError = class extends Error {
154
- constructor(message, originalError, code) {
155
- super(message);
156
- this.originalError = originalError;
157
- this.code = code;
158
- this.name = "ServiceError";
159
- }
160
- };
161
- function withErrorHandler(fn, serviceName) {
162
- return async (...args) => {
163
- try {
164
- return await fn(...args);
165
- } catch (error) {
166
- console.error(`Service ${serviceName} failed with args:`, args);
167
- console.error("Error details:", error);
168
- if (error instanceof Error && "code" in error) {
169
- const firebaseError = error;
170
- throw new ServiceError(
171
- `Error in ${serviceName}: ${firebaseError.message}`,
172
- error,
173
- firebaseError.code
174
- );
175
- }
176
- if (error instanceof Error) {
177
- throw new ServiceError(`Error in ${serviceName}: ${error.message}`, error);
178
- }
179
- throw new ServiceError(`Unknown error in ${serviceName}`, error);
180
- }
181
- };
182
- }
183
-
184
- // src/lib/firebase/api.ts
185
- var FirebaseAPI = class _FirebaseAPI {
186
- // eslint-disable-next-line @typescript-eslint/no-empty-function
187
- constructor() {
188
- this.config = null;
189
- }
190
- static getInstance() {
191
- if (!_FirebaseAPI.instance) {
192
- _FirebaseAPI.instance = new _FirebaseAPI();
193
- }
194
- return _FirebaseAPI.instance;
195
- }
196
- initialize(config) {
197
- this.config = config;
198
- }
199
- get db() {
200
- if (!this.config) throw new Error("Firebase API not initialized");
201
- return this.config.db;
202
- }
203
- get helpers() {
204
- if (!this.config) throw new Error("Firebase API not initialized");
205
- return this.config.helpers;
206
- }
207
- get httpsCallable() {
208
- var _a;
209
- return (_a = this.config) == null ? void 0 : _a.httpsCallable;
210
- }
211
- logEvent(name, data) {
212
- var _a;
213
- (_a = this.config) == null ? void 0 : _a.logEvent(name, data);
214
- }
215
- accessQueryConstraints() {
216
- const { query: query2, orderBy: orderBy2, limit: limit2, startAt: startAt2, startAfter: startAfter2, endAt: endAt2, endBefore: endBefore2, where: where2, increment: increment2 } = this.helpers;
217
- return {
218
- query: query2,
219
- orderBy: orderBy2,
220
- limit: limit2,
221
- startAt: startAt2,
222
- startAfter: startAfter2,
223
- endAt: endAt2,
224
- endBefore: endBefore2,
225
- where: where2,
226
- increment: increment2
227
- };
228
- }
229
- accessHelpers() {
230
- const { doc: doc2, collection: collection2, writeBatch: writeBatch2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = this.helpers;
231
- return {
232
- doc: (path) => doc2(this.db, path),
233
- collection: (path) => collection2(this.db, path),
234
- writeBatch: () => writeBatch2(this.db),
235
- serverTimestamp: serverTimestamp2,
236
- setDoc: setDoc2
237
- };
238
- }
239
- async getDoc(path) {
240
- const { getDoc: getDoc2, doc: doc2 } = this.helpers;
241
- const docRef = doc2(this.db, path);
242
- const docSnap = await getDoc2(docRef);
243
- const data = docSnap.exists() ? {
244
- ...docSnap.data(),
245
- id: docSnap.id
246
- } : null;
247
- return {
248
- id: docSnap.id,
249
- data
250
- };
251
- }
252
- async getDocs(path, ...queryConstraints) {
253
- const { getDocs: getDocs2, query: query2, collection: collection2 } = this.helpers;
254
- const collectionRef = collection2(this.db, path);
255
- const q = queryConstraints.length > 0 ? query2(collectionRef, ...queryConstraints) : collectionRef;
256
- const querySnapshot = await getDocs2(q);
257
- const data = querySnapshot.docs.map((doc2) => ({
258
- data: doc2.data(),
259
- id: doc2.id
260
- }));
261
- return {
262
- data,
263
- querySnapshot,
264
- empty: querySnapshot.empty
265
- };
266
- }
267
- async addDoc(path, data) {
268
- const { addDoc: addDoc2, collection: collection2 } = this.helpers;
269
- const collectionRef = collection2(this.db, path);
270
- const docRef = await addDoc2(collectionRef, data);
271
- return {
272
- ...data,
273
- id: docRef.id
274
- };
275
- }
276
- async setDoc(path, data, options = {}) {
277
- const { setDoc: setDoc2, doc: doc2 } = this.helpers;
278
- const docRef = doc2(this.db, path);
279
- await setDoc2(docRef, data, options);
280
- }
281
- async updateDoc(path, data) {
282
- const { updateDoc: updateDoc2, doc: doc2 } = this.helpers;
283
- const docRef = doc2(this.db, path);
284
- await updateDoc2(docRef, data);
285
- }
286
- async deleteDoc(path) {
287
- const { deleteDoc: deleteDoc2, doc: doc2 } = this.helpers;
288
- const docRef = doc2(this.db, path);
289
- await deleteDoc2(docRef);
290
- }
291
- async runTransaction(updateFunction) {
292
- const { runTransaction: runTransaction2 } = this.helpers;
293
- return runTransaction2(this.db, updateFunction);
294
- }
295
- async runBatch(operations) {
296
- const { writeBatch: writeBatch2 } = this.helpers;
297
- const batch = writeBatch2(this.db);
298
- await Promise.all(operations.map((op) => op()));
299
- await batch.commit();
300
- }
301
- writeBatch() {
302
- const { writeBatch: writeBatch2 } = this.helpers;
303
- const batch = writeBatch2(this.db);
304
- return batch;
305
- }
306
- };
307
- var api = FirebaseAPI.getInstance();
308
-
309
- // src/domains/assignment/assignment.constants.ts
310
- var ASSIGNMENT_ANALYTICS_TYPES = [
311
- "macro" /* Macro */,
312
- "gradebook" /* Gradebook */,
313
- "cards" /* Cards */,
314
- "student" /* Student */,
315
- "student_summary" /* StudentSummary */
316
- ];
317
- var ASSIGNMENTS_COLLECTION = "assignments";
318
- var ANALYTICS_SUBCOLLECTION = "analytics";
319
- var SCORES_SUBCOLLECTION = "scores";
320
- var refsAssignmentFiresotre = {
321
- allAssignments: () => ASSIGNMENTS_COLLECTION,
322
- assignment: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}`,
323
- assignmentAllAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}`,
324
- assignmentAnalytics: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${ANALYTICS_SUBCOLLECTION}/${params.type}`,
325
- assignmentScores: (params) => `${ASSIGNMENTS_COLLECTION}/${params.id}/${SCORES_SUBCOLLECTION}/${params.userId}`
326
- };
327
-
328
- // src/domains/assignment/services/get-assignments-score.service.ts
329
- var _getAssignmentScores = async ({
330
- assignmentId,
331
- analyticType = "macro" /* Macro */,
332
- studentId,
333
- currentUserId
334
- }) => {
335
- if (analyticType === "student" /* Student */) {
336
- const path = refsAssignmentFiresotre.assignmentScores({
337
- id: assignmentId,
338
- userId: currentUserId
339
- });
340
- const response = await api.getDoc(path);
341
- return { scores: response.data, id: assignmentId };
342
- }
343
- if (analyticType === "student_summary" /* StudentSummary */ && studentId) {
344
- const path = refsAssignmentFiresotre.assignmentScores({
345
- id: assignmentId,
346
- userId: studentId
347
- });
348
- const response = await api.getDoc(path);
349
- return { scores: response.data, id: assignmentId };
350
- }
351
- if (analyticType !== "all" /* All */ && ASSIGNMENT_ANALYTICS_TYPES.includes(analyticType)) {
352
- const ref = refsAssignmentFiresotre.assignmentAnalytics({
353
- id: assignmentId,
354
- type: analyticType
355
- });
356
- const docData = await api.getDoc(ref);
357
- return { scores: docData.data, id: assignmentId };
358
- } else if (analyticType === "all" /* All */) {
359
- const ref = refsAssignmentFiresotre.assignmentAllAnalytics({ id: assignmentId });
360
- const response = await api.getDocs(ref);
361
- const data = response.data.reduce((acc, curr) => {
362
- acc[curr.id] = curr;
363
- return acc;
364
- }, {});
365
- return { scores: data, id: assignmentId };
366
- }
367
- };
368
- var getAssignmentScores = withErrorHandler(_getAssignmentScores, "getAssignmentScores");
369
-
370
- // src/domains/assignment/services/attach-score-assignment.service.ts
371
- var _attachScoresAssignment = async ({
372
- assignments,
373
- analyticType,
374
- studentId,
375
- currentUserId
376
- }) => {
377
- const scoresPromises = assignments.map((a) => {
378
- return getAssignmentScores({
379
- assignmentId: a.id,
380
- analyticType,
381
- studentId,
382
- currentUserId
383
- });
384
- });
385
- const scores = await Promise.all(scoresPromises);
386
- const scoresObject = scores.reduce((acc, curr) => {
387
- acc[curr.id] = curr.scores;
388
- return acc;
389
- }, {});
390
- const assignmentsWithScores = assignments.map((a) => {
391
- var _a;
392
- return {
393
- ...a,
394
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/ban-ts-comment
395
- // @ts-ignore
396
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
397
- scores: (_a = scoresObject[a.id]) != null ? _a : null
398
- };
399
- });
400
- return assignmentsWithScores;
401
- };
402
- var attachScoresAssignment = withErrorHandler(
403
- _attachScoresAssignment,
404
- "attachScoresAssignment"
405
- );
406
-
407
- // src/domains/assignment/services/get-all-assignment.service.ts
408
- async function _getAllAssignments() {
409
- const path = refsAssignmentFiresotre.allAssignments();
410
- const response = await api.getDocs(path);
411
- return response.data;
412
- }
413
- var getAllAssignments = withErrorHandler(_getAllAssignments, "getAllAssignments");
414
-
415
- // src/domains/assignment/utils/check-assignment-availability.ts
416
- var import_dayjs = __toESM(require("dayjs"));
417
- var checkAssignmentAvailability = (scheduledTime) => {
418
- if (!scheduledTime) return true;
419
- const scheduledDate = typeof scheduledTime === "string" ? (0, import_dayjs.default)(scheduledTime) : (0, import_dayjs.default)(scheduledTime.toDate());
420
- if (!scheduledDate.isValid()) return true;
421
- return (0, import_dayjs.default)().isAfter(scheduledDate);
422
- };
423
-
424
- // src/domains/assignment/services/get-assignment.service.ts
425
- async function _getAssignment(params) {
426
- var _a;
427
- const path = refsAssignmentFiresotre.assignment({ id: params.assignmentId });
428
- const response = await api.getDoc(path);
429
- if (!response.data) return null;
430
- const assignment = response.data;
431
- const isAvailable = checkAssignmentAvailability(assignment.scheduledTime);
432
- const assignmentWithId = {
433
- ...assignment,
434
- isAvailable,
435
- id: params.assignmentId,
436
- scheduledTime: (_a = assignment.scheduledTime) != null ? _a : null
437
- };
438
- if (params.analyticType) {
439
- const assignmentsWithScores = await attachScoresAssignment({
440
- assignments: [assignmentWithId],
441
- analyticType: params.analyticType,
442
- currentUserId: params.currentUserId
443
- });
444
- return assignmentsWithScores.length > 0 ? assignmentsWithScores[0] : assignmentWithId;
445
- }
446
- return assignmentWithId;
447
- }
448
- var getAssignment = withErrorHandler(_getAssignment, "getAssignment");
449
-
450
- // src/domains/assignment/assignment.repo.ts
451
- var createAssignmentRepo = () => {
452
- return {
453
- getAssignment,
454
- attachScoresAssignment,
455
- getAssignmentScores,
456
- getAllAssignments
457
- };
458
- };
459
-
460
- // src/domains/assignment/hooks/assignment.hooks.ts
461
- var import_react_query = require("@tanstack/react-query");
462
- var assignmentQueryKeys = {
463
- all: ["assignments"],
464
- byId: (id) => [...assignmentQueryKeys.all, id],
465
- list: () => [...assignmentQueryKeys.all, "list"]
466
- };
467
- function useAssignment({
468
- assignmentId,
469
- enabled = true,
470
- analyticType,
471
- userId
472
- }) {
473
- const { speakableApi } = useSpeakableApi();
474
- return (0, import_react_query.useQuery)({
475
- queryKey: assignmentQueryKeys.byId(assignmentId),
476
- queryFn: () => speakableApi.assignmentRepo.getAssignment({
477
- assignmentId,
478
- analyticType,
479
- currentUserId: userId
480
- }),
481
- enabled
482
- });
483
- }
484
-
485
- // src/domains/assignment/hooks/score-hooks.ts
486
- var import_react_query2 = require("@tanstack/react-query");
487
-
488
- // src/utils/debounce.utils.ts
489
- function debounce(func, waitFor) {
490
- let timeoutId;
491
- return (...args) => new Promise((resolve, reject) => {
492
- if (timeoutId) {
493
- clearTimeout(timeoutId);
494
- }
495
- timeoutId = setTimeout(async () => {
496
- try {
497
- const result = await func(...args);
498
- resolve(result);
499
- } catch (error) {
500
- reject(error);
501
- }
502
- }, waitFor);
503
- });
504
- }
505
-
506
- // src/lib/tanstack/handle-optimistic-update-query.ts
507
- var handleOptimisticUpdate = async ({
508
- queryClient,
509
- queryKey,
510
- newData
511
- }) => {
512
- await queryClient.cancelQueries({
513
- queryKey
514
- });
515
- const previousData = queryClient.getQueryData(queryKey);
516
- if (previousData === void 0) {
517
- queryClient.setQueryData(queryKey, newData);
518
- } else {
519
- queryClient.setQueryData(queryKey, { ...previousData, ...newData });
520
- }
521
- return { previousData };
522
- };
523
-
524
- // src/constants/speakable-plans.ts
525
- var FEEDBACK_PLANS = {
526
- FEEDBACK_TRANSCRIPT: "FEEDBACK_TRANSCRIPT",
527
- // Transcript from the audio
528
- FEEDBACK_SUMMARY: "FEEDBACK_SUMMARY",
529
- // Chatty summary (Free plan)
530
- FEEDBACK_GRAMMAR_INSIGHTS: "FEEDBACK_GRAMMAR_INSIGHTS",
531
- // Grammar insights
532
- FEEDBACK_SUGGESTED_RESPONSE: "FEEDBACK_SUGGESTED_RESPONSE",
533
- // Suggested Response
534
- FEEDBACK_RUBRIC: "FEEDBACK_RUBRIC",
535
- // Suggested Response
536
- FEEDBACK_GRADING_STANDARDS: "FEEDBACK_GRADING_STANDARDS",
537
- // ACTFL / WIDA Estimate
538
- FEEDBACK_TARGET_LANGUAGE: "FEEDBACK_TARGET_LANGUAGE",
539
- // Ability to set the feedback language to the target language of the student
540
- FEEDBACK_DISABLE_ALLOW_RETRIES: "FEEDBACK_DISABLE_ALLOW_RETRIES"
541
- // Turn of allow retries
542
- };
543
- var AUTO_GRADING_PLANS = {
544
- AUTO_GRADING_PASS_FAIL: "AUTO_GRADING_PASS_FAIL",
545
- // Pass / fail grading
546
- AUTO_GRADING_RUBRICS: "AUTO_GRADING_RUBRICS",
547
- // Autograded rubrics
548
- AUTO_GRADING_STANDARDS_BASED: "AUTO_GRADING_STANDARDS_BASED"
549
- // Standards based grading
550
- };
551
- var AI_ASSISTANT_PLANS = {
552
- AI_ASSISTANT_DOCUMENT_UPLOADS: "AI_ASSISTANT_DOCUMENT_UPLOADS",
553
- // Allow document uploading
554
- AI_ASSISTANT_UNLIMITED_USE: "AI_ASSISTANT_UNLIMITED_USE"
555
- // Allow unlimited use of AI assistant. Otherwise, limits are used.
556
- };
557
- var ASSIGNMENT_SETTINGS_PLANS = {
558
- ASSESSMENTS: "ASSESSMENTS",
559
- // Ability to create assessment assignment types
560
- GOOGLE_CLASSROOM_GRADE_PASSBACK: "GOOGLE_CLASSROOM_GRADE_PASSBACK"
561
- // Assignment scores can sync with classroom
562
- };
563
- var ANALYTICS_PLANS = {
564
- ANALYTICS_GRADEBOOK: "ANALYTICS_GRADEBOOK",
565
- // Access to the gradebook page
566
- ANALYTICS_CLASSROOM_ANALYTICS: "ANALYTICS_CLASSROOM_ANALYTICS",
567
- // Access to the classroom analytics page
568
- ANALYTICS_STUDENT_PROGRESS_REPORTS: "ANALYTICS_STUDENT_PROGRESS_REPORTS",
569
- // Access to the panel that shows an individual student's progress and assignments
570
- ANALYTICS_ASSIGNMENT_RESULTS: "ANALYTICS_ASSIGNMENT_RESULTS",
571
- // Access to the assigment RESULTS page
572
- ANALYTICS_ORGANIZATION: "ANALYTICS_ORGANIZATION"
573
- // Access to the organization analytics panel (for permitted admins)
574
- };
575
- var SPACES_PLANS = {
576
- SPACES_CREATE_SPACE: "SPACES_CREATE_SPACE",
577
- // Ability to create spaces
578
- SPACES_CHECK_POINTS: "SPACES_CHECK_POINTS"
579
- // Feature not available yet. Ability to create checkpoints for spaces for data aggregation
580
- };
581
- var DISCOVER_PLANS = {
582
- DISCOVER_ORGANIZATION_LIBRARY: "DISCOVER_ORGANIZATION_LIBRARY"
583
- // Access to the organizations shared library
584
- };
585
- var MEDIA_AREA_PLANS = {
586
- MEDIA_AREA_DOCUMENT_UPLOAD: "MEDIA_AREA_DOCUMENT_UPLOAD",
587
- MEDIA_AREA_AUDIO_FILES: "MEDIA_AREA_AUDIO_FILES"
588
- };
589
- var FREE_PLAN = [];
590
- var TEACHER_PRO_PLAN = [
591
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
592
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
593
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
594
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
595
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
596
- SPACES_PLANS.SPACES_CREATE_SPACE
597
- // AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
598
- ];
599
- var SCHOOL_STARTER = [
600
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
601
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
602
- FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
603
- FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
604
- FEEDBACK_PLANS.FEEDBACK_RUBRIC,
605
- FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
606
- FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
607
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
608
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
609
- AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
610
- AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
611
- AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
612
- AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
613
- // ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
614
- ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
615
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
616
- ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
617
- ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
618
- // ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
619
- SPACES_PLANS.SPACES_CREATE_SPACE,
620
- SPACES_PLANS.SPACES_CHECK_POINTS,
621
- // DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
622
- MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
623
- MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
624
- ];
625
- var ORGANIZATION_PLAN = [
626
- FEEDBACK_PLANS.FEEDBACK_TRANSCRIPT,
627
- FEEDBACK_PLANS.FEEDBACK_SUMMARY,
628
- FEEDBACK_PLANS.FEEDBACK_GRAMMAR_INSIGHTS,
629
- FEEDBACK_PLANS.FEEDBACK_SUGGESTED_RESPONSE,
630
- FEEDBACK_PLANS.FEEDBACK_RUBRIC,
631
- FEEDBACK_PLANS.FEEDBACK_GRADING_STANDARDS,
632
- FEEDBACK_PLANS.FEEDBACK_DISABLE_ALLOW_RETRIES,
633
- FEEDBACK_PLANS.FEEDBACK_TARGET_LANGUAGE,
634
- AUTO_GRADING_PLANS.AUTO_GRADING_PASS_FAIL,
635
- AUTO_GRADING_PLANS.AUTO_GRADING_RUBRICS,
636
- AUTO_GRADING_PLANS.AUTO_GRADING_STANDARDS_BASED,
637
- AI_ASSISTANT_PLANS.AI_ASSISTANT_DOCUMENT_UPLOADS,
638
- AI_ASSISTANT_PLANS.AI_ASSISTANT_UNLIMITED_USE,
639
- ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS,
640
- ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK,
641
- ANALYTICS_PLANS.ANALYTICS_GRADEBOOK,
642
- ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS,
643
- ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS,
644
- ANALYTICS_PLANS.ANALYTICS_ORGANIZATION,
645
- SPACES_PLANS.SPACES_CREATE_SPACE,
646
- SPACES_PLANS.SPACES_CHECK_POINTS,
647
- DISCOVER_PLANS.DISCOVER_ORGANIZATION_LIBRARY,
648
- MEDIA_AREA_PLANS.MEDIA_AREA_DOCUMENT_UPLOAD,
649
- MEDIA_AREA_PLANS.MEDIA_AREA_AUDIO_FILES
650
- ];
651
- var SpeakablePlanTypes = {
652
- basic: "basic",
653
- teacher_pro: "teacher_pro",
654
- school_starter: "school_starter",
655
- organization: "organization",
656
- // OLD PLANS
657
- starter: "starter",
658
- growth: "growth",
659
- professional: "professional"
660
- };
661
- var SpeakablePermissionsMap = {
662
- [SpeakablePlanTypes.basic]: FREE_PLAN,
663
- [SpeakablePlanTypes.starter]: TEACHER_PRO_PLAN,
664
- [SpeakablePlanTypes.teacher_pro]: TEACHER_PRO_PLAN,
665
- [SpeakablePlanTypes.growth]: ORGANIZATION_PLAN,
666
- [SpeakablePlanTypes.professional]: ORGANIZATION_PLAN,
667
- [SpeakablePlanTypes.organization]: ORGANIZATION_PLAN,
668
- [SpeakablePlanTypes.school_starter]: SCHOOL_STARTER
669
- };
670
- var SpeakablePlanHierarchy = [
671
- SpeakablePlanTypes.basic,
672
- SpeakablePlanTypes.starter,
673
- SpeakablePlanTypes.teacher_pro,
674
- SpeakablePlanTypes.growth,
675
- SpeakablePlanTypes.professional,
676
- SpeakablePlanTypes.school_starter,
677
- SpeakablePlanTypes.organization
678
- ];
679
-
680
- // src/hooks/usePermissions.ts
681
- var usePermissions = () => {
682
- const { permissions } = useSpeakableApi();
683
- const has = (permission) => {
684
- var _a;
685
- return (_a = permissions.permissions) == null ? void 0 : _a.includes(permission);
686
- };
687
- return {
688
- plan: permissions.plan,
689
- permissionsLoaded: permissions.loaded,
690
- isStripePlan: permissions.isStripePlan,
691
- refreshDate: permissions.refreshDate,
692
- isInstitutionPlan: permissions.isInstitutionPlan,
693
- subscriptionId: permissions.subscriptionId,
694
- contact: permissions.contact,
695
- hasGradebook: has(ANALYTICS_PLANS.ANALYTICS_GRADEBOOK),
696
- hasGoogleClassroomGradePassback: has(ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK),
697
- hasAssessments: has(ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS),
698
- hasSectionAnalytics: has(ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS),
699
- hasStudentReports: has(ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS),
700
- permissions: permissions || [],
701
- hasStudentPortfolios: permissions.hasStudentPortfolios,
702
- isFreeOrgTrial: permissions.type === "free_org_trial",
703
- freeOrgTrialExpired: permissions.freeOrgTrialExpired
704
- };
705
- };
706
- var usePermissions_default = usePermissions;
707
-
708
- // src/domains/notification/notification.constants.ts
709
- var SPEAKABLE_NOTIFICATIONS = {
710
- NEW_ASSIGNMENT: "new_assignment",
711
- ASSESSMENT_SUBMITTED: "assessment_submitted",
712
- ASSESSMENT_SCORED: "assessment_scored",
713
- NEW_COMMENT: "NEW_COMMENT"
714
- };
715
- var SpeakableNotificationTypes = {
716
- NEW_ASSIGNMENT: "NEW_ASSIGNMENT",
717
- FEEDBACK_FROM_TEACHER: "FEEDBACK_FROM_TEACHER",
718
- MESSAGE_FROM_STUDENT: "MESSAGE_FROM_STUDENT",
719
- PHRASE_MARKED_CORRECT: "PHRASE_MARKED_CORRECT",
720
- STUDENT_PROGRESS: "STUDENT_PROGRESS",
721
- PLAYLIST_FOLLOWERS: "PLAYLIST_FOLLOWERS",
722
- PLAYLIST_PLAYS: "PLAYLIST_PLAYS",
723
- // New notifications
724
- ASSESSMENT_SUBMITTED: "ASSESSMENT_SUBMITTED",
725
- // Notification FOR TEACHER when student submits assessment
726
- ASSESSMENT_SCORED: "ASSESSMENT_SCORED",
727
- // Notification FOR STUDENT when teacher scores assessment
728
- // Comment
729
- NEW_COMMENT: "NEW_COMMENT"
730
- };
731
-
732
- // src/domains/notification/services/create-notification.service.ts
733
- var import_dayjs2 = __toESM(require("dayjs"));
734
-
735
- // src/constants/web.constants.ts
736
- var WEB_BASE_URL = "https://app.speakable.io";
737
-
738
- // src/domains/notification/services/send-notification.service.ts
739
- var _sendNotification = async (sendTo, notification) => {
740
- var _a, _b, _c;
741
- const results = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createNotificationV2")) == null ? void 0 : _c({
742
- sendTo,
743
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
744
- notification
745
- }));
746
- return results;
747
- };
748
- var sendNotification = withErrorHandler(_sendNotification, "sendNotification");
749
-
750
- // src/domains/notification/services/create-notification.service.ts
751
- var createNotification = async ({
752
- data,
753
- type,
754
- userId,
755
- profile
756
- }) => {
757
- let result;
758
- switch (type) {
759
- case SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT:
760
- result = await handleAssignNotifPromise({ data, profile });
761
- break;
762
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED:
763
- result = await createAssessmentSubmissionNotification({
764
- data,
765
- profile,
766
- userId
767
- });
768
- break;
769
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED:
770
- result = await createAssessmentScoredNotification({
771
- data,
772
- profile
773
- });
774
- break;
775
- default:
776
- result = null;
777
- break;
778
- }
779
- return result;
780
- };
781
- var handleAssignNotifPromise = async ({
782
- data: assignments,
783
- profile
784
- }) => {
785
- if (!assignments.length) return;
786
- try {
787
- const notifsPromises = assignments.map(async (assignment) => {
788
- const {
789
- section,
790
- section: { members },
791
- ...rest
792
- } = assignment;
793
- if (!section || !members) throw new Error("Invalid assignment data");
794
- const data = { section, sendTo: members, assignment: { ...rest } };
795
- return createNewAssignmentNotification({ data, profile });
796
- });
797
- await Promise.all(notifsPromises);
798
- return {
799
- success: true,
800
- message: "Assignment notifications sent successfully"
801
- };
802
- } catch (error) {
803
- console.error("Error in handleAssignNotifPromise:", error);
804
- throw error;
805
- }
806
- };
807
- var createNewAssignmentNotification = async ({
808
- data,
809
- profile
810
- }) => {
811
- var _a;
812
- const { assignment, sendTo } = data;
813
- const teacherName = profile.displayName || "Your teacher";
814
- const dueDate = assignment.dueDateTimestamp ? (0, import_dayjs2.default)(assignment.dueDateTimestamp.toDate()).format("MMM Do") : null;
815
- const results = await sendNotification(sendTo, {
816
- courseId: assignment.courseId,
817
- type: SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT,
818
- senderName: teacherName,
819
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
820
- messagePreview: `A new assignment "${assignment.name}" is now available. ${dueDate ? `Due ${dueDate}` : ""}`,
821
- title: "New Assignment Available!",
822
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
823
- });
824
- return results;
825
- };
826
- var createAssessmentSubmissionNotification = async ({
827
- data: assignment,
828
- profile,
829
- userId
830
- }) => {
831
- var _a;
832
- const studentName = profile.displayName || "Your student";
833
- const results = await sendNotification(assignment.owners, {
834
- courseId: assignment.courseId,
835
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED,
836
- link: `${WEB_BASE_URL}/a/${assignment.id}?studentId=${userId}`,
837
- title: `Assessment Submitted!`,
838
- senderName: studentName,
839
- messagePreview: `${studentName} has submitted the assessment "${assignment.name}"`,
840
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
841
- });
842
- return results;
843
- };
844
- var createAssessmentScoredNotification = async ({
845
- data,
846
- profile
847
- }) => {
848
- var _a, _b, _c, _d, _e;
849
- const { assignment, sendTo } = data;
850
- const teacherName = profile.displayName || "Your teacher";
851
- const title = `${assignment.isAssessment ? "Assessment" : "Assignment"} Reviewed!`;
852
- const messagePreview = `Your ${assignment.isAssessment ? "assessment" : "assignment"} has been reviewed by your teacher. Click to view the feedback.`;
853
- const results = await sendNotification(sendTo, {
854
- courseId: assignment.courseId,
855
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED,
856
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
857
- title,
858
- messagePreview,
859
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url,
860
- senderName: teacherName
861
- });
862
- await ((_e = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "sendAssessmentScoredEmail")) == null ? void 0 : _e({
863
- assessmentTitle: assignment.name,
864
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
865
- senderImage: ((_d = profile.image) == null ? void 0 : _d.url) || "",
866
- studentId: sendTo[0],
867
- teacherName: profile.displayName
868
- }));
869
- return results;
870
- };
871
-
872
- // src/domains/notification/hooks/notification.hooks.ts
873
- var notificationQueryKeys = {
874
- all: ["notifications"],
875
- byId: (id) => [...notificationQueryKeys.all, id]
876
- };
877
- var useCreateNotification = () => {
878
- const { user, queryClient } = useSpeakableApi();
879
- const handleCreateNotifications = async (type, data) => {
880
- var _a, _b;
881
- const result = await createNotification({
882
- type,
883
- userId: user.auth.uid,
884
- profile: (_a = user == null ? void 0 : user.profile) != null ? _a : {},
885
- data
886
- });
887
- queryClient.invalidateQueries({
888
- queryKey: notificationQueryKeys.byId((_b = user == null ? void 0 : user.auth.uid) != null ? _b : "")
889
- });
890
- return result;
891
- };
892
- return {
893
- createNotification: handleCreateNotifications
894
- };
895
- };
896
-
897
- // src/hooks/useGoogleClassroom.ts
898
- var useGoogleClassroom = () => {
899
- const submitAssignmentToGoogleClassroom = async ({
900
- assignment,
901
- scores,
902
- googleUserId = null
903
- // optional to override the user's googleUserId
904
- }) => {
905
- var _a, _b, _c;
906
- try {
907
- const { googleClassroomUserId = null } = scores;
908
- const googleId = googleUserId || googleClassroomUserId;
909
- if (!googleId)
910
- return {
911
- error: true,
912
- message: "No Google Classroom ID found"
913
- };
914
- const { courseWorkId, maxPoints, owners, courseId } = assignment;
915
- const draftGrade = (scores == null ? void 0 : scores.score) ? (scores == null ? void 0 : scores.score) / 100 * maxPoints : 0;
916
- const result = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentToGoogleClassroomV2")) == null ? void 0 : _c({
917
- teacherId: owners[0],
918
- courseId,
919
- courseWorkId,
920
- userId: googleId,
921
- draftGrade
922
- }));
923
- return result;
924
- } catch (error) {
925
- return { error: true, message: error.message };
926
- }
927
- };
928
- return {
929
- submitAssignmentToGoogleClassroom
930
- };
931
- };
932
-
933
- // src/lib/firebase/firebase-analytics/grading-standard.ts
934
- var logGradingStandardLog = (data) => {
935
- var _a, _b, _c;
936
- if (data.courseId && data.type && data.level) {
937
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
938
- eventType: data.type || "custom",
939
- level: data.level,
940
- courseId: data.courseId
941
- });
942
- }
943
- api.logEvent("logGradingStandard", data);
944
- };
945
-
946
- // src/constants/analytics.constants.ts
947
- var SPEAKABLE_ANALYTICS = {
948
- VOICE_SUCCESS: "voice_success",
949
- VOICE_FALLBACK_SUCCESS: "voice_fallback_success",
950
- VOICE_FALLBACK_FAIL: "voice_fallback_fail",
951
- VOICE_FAIL: "voice_fail",
952
- RESPOND_CARD_SUCCESS: "respond_card_success",
953
- RESPOND_CARD_FAIL: "respond_card_fail",
954
- RESPOND_WRITE_CARD_SUCCESS: "respond_write_card_success",
955
- RESPOND_WRITE_CARD_FAIL: "respond_write_card_fail",
956
- RESPOND_WRITE_CARD_SUBMITTED: "respond_write_card_submitted",
957
- RESPOND_WRITE_CARD_ERROR: "respond_write_card_error",
958
- RESPOND_CARD_ERROR: "respond_card_error",
959
- RESPOND_CARD_SUBMITTED: "respond_card_submitted",
960
- RESPOND_FREE_PLAN: "respond_free_plan",
961
- RESPOND_WRITE_FREE_PLAN: "respond_write_free_plan",
962
- SUBMISSION: "assignment_submitted",
963
- ASSIGNMENT_STARTED: "assignment_started",
964
- CREATE_ASSIGNMENT: "create_assignment",
965
- MC_SUCCESS: "multiple_choice_success",
966
- MC_FAIL: "multiple_choice_fail",
967
- MC_ERROR: "multiple_choice_error",
968
- ACTFL_LEVEL: "actfl_level",
969
- WIDA_LEVEL: "wida_level",
970
- // New events
971
- VIEW_SCORES_MODAL: "view_scores_modal",
972
- SHORT_ANSWER_SUCCESS: "short_answer_success",
973
- SHORT_ANSWER_FAIL: "short_answer_fail",
974
- SHORT_ANSWER_ERROR: "short_answer_error",
975
- RETRY: "retry",
976
- MESSAGE_SENT: "message_sent",
977
- MESSAGE_ERROR: "message_error",
978
- VIEW_DETAILS_CLICK: "view_details_click",
979
- TABS_CLICK: "tabs_click",
980
- VIEW_MEDIA: "view_media",
981
- VIEW_SCORES: "view_scores",
982
- VIEW_GRADING_METHOD: "view_grading_method",
983
- VIEW_FEEDBACK: "view_feedback"
984
- };
985
-
986
- // src/lib/firebase/firebase-analytics/assignment.ts
987
- var logOpenAssignment = (data = {}) => {
988
- api.logEvent("open_assignment", data);
989
- };
990
- var logOpenActivityPreview = (data = {}) => {
991
- api.logEvent("open_activity_preview", data);
992
- };
993
- var logSubmitAssignment = (data = {}) => {
994
- var _a, _b, _c;
995
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
996
- eventType: SPEAKABLE_ANALYTICS.SUBMISSION,
997
- ...data
998
- });
999
- api.logEvent(SPEAKABLE_ANALYTICS.SUBMISSION, data);
1000
- };
1001
- var logStartAssignment = (data = {}) => {
1002
- var _a, _b, _c;
1003
- if (data.courseId) {
1004
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
1005
- eventType: SPEAKABLE_ANALYTICS.ASSIGNMENT_STARTED,
1006
- ...data
1007
- });
1008
- }
1009
- api.logEvent(SPEAKABLE_ANALYTICS.ASSIGNMENT_STARTED, data);
1010
- };
1011
-
1012
- // src/domains/assignment/utils/create-default-score.ts
1013
- var defaultScore = (props) => {
1014
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1015
- const score = {
1016
- progress: 0,
1017
- score: 0,
1018
- startDate: serverTimestamp2(),
1019
- status: "IN_PROGRESS",
1020
- submitted: false,
1021
- cards: {},
1022
- lastPlayed: serverTimestamp2(),
1023
- owners: props.owners,
1024
- userId: props.userId
1025
- };
1026
- if (props.googleClassroomUserId) {
1027
- score.googleClassroomUserId = props.googleClassroomUserId;
1028
- }
1029
- if (props.courseId) {
1030
- score.courseId = props.courseId;
1031
- }
1032
- return score;
1033
- };
1034
-
1035
- // src/domains/assignment/score-practice.constants.ts
1036
- var SCORES_PRACTICE_COLLECTION = "users";
1037
- var SCORES_PRACTICE_SUBCOLLECTION = "practice";
1038
- var refsScoresPractice = {
1039
- practiceScores: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}`,
1040
- practiceScoreHistoryRefDoc: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}/attempts/${params.date}`
1041
- };
1042
-
1043
- // src/domains/assignment/services/create-score.service.ts
1044
- var _updateAssignmentGradebookStatus = async ({
1045
- assignmentId,
1046
- userId,
1047
- status,
1048
- score
1049
- }) => {
1050
- var _a, _b, _c;
1051
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
1052
- assignmentId,
1053
- userId,
1054
- status,
1055
- score
1056
- }));
1057
- };
1058
- var updateAssignmentGradebookStatus = withErrorHandler(
1059
- _updateAssignmentGradebookStatus,
1060
- "updateAssignmentGradebookStatus"
1061
- );
1062
- async function _createScore(params) {
1063
- var _a, _b, _c;
1064
- if (params.isAssignment) {
1065
- const ref = refsAssignmentFiresotre.assignmentScores({
1066
- id: params.activityId,
1067
- userId: params.userId
1068
- });
1069
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
1070
- assignmentId: params.activityId,
1071
- userId: params.userId,
1072
- status: "IN_PROGRESS",
1073
- score: null
1074
- }));
1075
- await api.setDoc(ref, params.scoreData, { merge: true });
1076
- await updateAssignmentGradebookStatus({
1077
- assignmentId: params.activityId,
1078
- userId: params.userId,
1079
- status: "IN_PROGRESS",
1080
- score: null
1081
- });
1082
- return {
1083
- id: params.userId
1084
- };
1085
- } else {
1086
- const ref = refsScoresPractice.practiceScores({
1087
- userId: params.userId,
1088
- setId: params.activityId
1089
- });
1090
- await api.setDoc(ref, params.scoreData);
1091
- return {
1092
- id: params.userId
1093
- };
1094
- }
1095
- }
1096
- var createScore = withErrorHandler(_createScore, "createScore");
1097
-
1098
- // src/domains/assignment/services/get-score.service.ts
1099
- async function getAssignmentScore({
1100
- userId,
1101
- assignment,
1102
- googleClassroomUserId
1103
- }) {
1104
- const path = refsAssignmentFiresotre.assignmentScores({
1105
- id: assignment.id,
1106
- userId
1107
- });
1108
- const response = await api.getDoc(path);
1109
- if (response.data == null) {
1110
- const newScore = {
1111
- ...defaultScore({
1112
- owners: [userId],
1113
- userId,
1114
- courseId: assignment.courseId,
1115
- googleClassroomUserId
1116
- }),
1117
- assignmentId: assignment.id
1118
- };
1119
- logStartAssignment({
1120
- courseId: assignment.courseId
1121
- });
1122
- const result = await createScore({
1123
- activityId: assignment.id,
1124
- userId,
1125
- isAssignment: true,
1126
- scoreData: newScore
1127
- });
1128
- return {
1129
- ...newScore,
1130
- id: result.id
1131
- };
1132
- }
1133
- return response.data;
1134
- }
1135
- async function getPracticeScore({ userId, setId }) {
1136
- const path = refsScoresPractice.practiceScores({ userId, setId });
1137
- const response = await api.getDoc(path);
1138
- if (response.data == null) {
1139
- const newScore = {
1140
- ...defaultScore({
1141
- owners: [userId],
1142
- userId
1143
- }),
1144
- setId
1145
- };
1146
- const result = await createScore({
1147
- activityId: setId,
1148
- userId,
1149
- isAssignment: false,
1150
- scoreData: newScore
1151
- });
1152
- return {
1153
- ...newScore,
1154
- id: result.id
1155
- };
1156
- }
1157
- return response.data;
1158
- }
1159
- async function _getScore(params) {
1160
- if (params.isAssignment) {
1161
- return await getAssignmentScore({
1162
- userId: params.userId,
1163
- assignment: {
1164
- id: params.activityId,
1165
- courseId: params.courseId
1166
- },
1167
- googleClassroomUserId: params.googleClassroomUserId
1168
- });
1169
- } else {
1170
- return await getPracticeScore({
1171
- userId: params.userId,
1172
- setId: params.activityId
1173
- });
1174
- }
1175
- }
1176
- var getScore = withErrorHandler(_getScore, "getScore");
1177
-
1178
- // src/domains/assignment/utils/calculateScoreAndProgress.ts
1179
- var calculateScoreAndProgress = (scores, cardsList, weights) => {
1180
- const filteredScoreCards = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce(
1181
- (acc, cardId) => {
1182
- var _a;
1183
- const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1184
- if (cardScores && !cardScores.media_area_opened) {
1185
- acc[cardId] = cardScores;
1186
- }
1187
- return acc;
1188
- },
1189
- {}
1190
- );
1191
- const totalSetPoints = cardsList.reduce((acc, cardId) => {
1192
- acc += (weights == null ? void 0 : weights[cardId]) || 1;
1193
- return acc;
1194
- }, 0);
1195
- const totalPointsAwarded = Object.keys(filteredScoreCards).reduce((acc, cardId) => {
1196
- var _a;
1197
- const cardScores = filteredScoreCards[cardId];
1198
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1199
- const score2 = (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0 ? Number((_a = cardScores == null ? void 0 : cardScores.score) != null ? _a : 0) : null;
1200
- const weight = (weights == null ? void 0 : weights[cardId]) || 1;
1201
- const fraction = (score2 != null ? score2 : 0) / 100;
1202
- if (score2 || score2 === 0) {
1203
- acc += weight * fraction;
1204
- } else {
1205
- acc += weight;
1206
- }
1207
- }
1208
- return acc;
1209
- }, 0);
1210
- const totalCompletedCards = Object.keys(filteredScoreCards).reduce((acc, cardId) => {
1211
- const cardScores = filteredScoreCards[cardId];
1212
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1213
- acc += 1;
1214
- }
1215
- return acc;
1216
- }, 0);
1217
- const percent = totalPointsAwarded / totalSetPoints;
1218
- const score = Math.round(percent * 100);
1219
- const progress = Math.round(totalCompletedCards / (cardsList.length || 1) * 100);
1220
- return { score, progress };
1221
- };
1222
- var calculateScoreAndProgress_default = calculateScoreAndProgress;
1223
-
1224
- // src/domains/assignment/services/update-score.service.ts
1225
- async function _updateScore(params) {
1226
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1227
- id: params.activityId,
1228
- userId: params.userId
1229
- }) : refsScoresPractice.practiceScores({
1230
- setId: params.activityId,
1231
- userId: params.userId
1232
- });
1233
- await api.updateDoc(path, {
1234
- ...params.data
1235
- });
1236
- }
1237
- var updateScore = withErrorHandler(_updateScore, "updateScore");
1238
- async function _updateCardScore(params) {
1239
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1240
- id: params.activityId,
1241
- userId: params.userId
1242
- }) : refsScoresPractice.practiceScores({
1243
- setId: params.activityId,
1244
- userId: params.userId
1245
- });
1246
- const updates = Object.keys(params.updates.cardScore).reduce(
1247
- (acc, key) => {
1248
- acc[`cards.${params.cardId}.${key}`] = params.updates.cardScore[key];
1249
- return acc;
1250
- },
1251
- {}
1252
- );
1253
- if (params.updates.progress) {
1254
- updates.progress = params.updates.progress;
1255
- }
1256
- if (params.updates.score) {
1257
- updates.score = params.updates.score;
1258
- }
1259
- await api.updateDoc(path, {
1260
- ...updates
1261
- });
1262
- }
1263
- var updateCardScore = withErrorHandler(_updateCardScore, "updateCardScore");
1264
-
1265
- // src/domains/assignment/services/clear-score.service.ts
1266
- var import_dayjs3 = __toESM(require("dayjs"));
1267
- async function clearScore(params) {
1268
- var _a, _b, _c, _d, _e;
1269
- const update = {
1270
- [`cards.${params.cardId}`]: {
1271
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1272
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1273
- // save old score history
1274
- history: [
1275
- {
1276
- ...params.cardScores,
1277
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1278
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1279
- retryTime: (0, import_dayjs3.default)().format("YYYY-MM-DD HH:mm:ss"),
1280
- history: null
1281
- },
1282
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1283
- ...(_e = params.cardScores.history) != null ? _e : []
1284
- ]
1285
- }
1286
- };
1287
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1288
- id: params.activityId,
1289
- userId: params.userId
1290
- }) : refsScoresPractice.practiceScores({
1291
- setId: params.activityId,
1292
- userId: params.userId
1293
- });
1294
- await api.updateDoc(path, update);
1295
- return {
1296
- update,
1297
- activityId: params.activityId
1298
- };
1299
- }
1300
- async function clearScoreV2(params) {
1301
- var _a, _b, _c, _d, _e;
1302
- const update = {
1303
- [`cards.${params.cardId}`]: {
1304
- ...params.cardScores,
1305
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1306
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1307
- history: [
1308
- {
1309
- ...params.cardScores,
1310
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1311
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1312
- retryTime: (0, import_dayjs3.default)().format("YYYY-MM-DD HH:mm:ss"),
1313
- history: null
1314
- },
1315
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1316
- ...(_e = params.cardScores.history) != null ? _e : []
1317
- ]
1318
- }
1319
- };
1320
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1321
- id: params.activityId,
1322
- userId: params.userId
1323
- }) : refsScoresPractice.practiceScores({
1324
- setId: params.activityId,
1325
- userId: params.userId
1326
- });
1327
- await api.updateDoc(path, update);
1328
- return {
1329
- update,
1330
- activityId: params.activityId
1331
- };
1332
- }
1333
-
1334
- // src/domains/assignment/services/submit-assignment-score.service.ts
1335
- var import_dayjs4 = __toESM(require("dayjs"));
1336
- async function _submitAssignmentScore({
1337
- assignment,
1338
- userId,
1339
- status,
1340
- studentName
1341
- }) {
1342
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1343
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1344
- const fieldsUpdated = {
1345
- submitted: true,
1346
- progress: 100,
1347
- submissionDate: serverTimestamp2(),
1348
- status
1349
- };
1350
- if (assignment.isAssessment) {
1351
- const result = await handleAssessment(assignment, userId, fieldsUpdated, studentName);
1352
- return result;
1353
- } else if (assignment.courseId) {
1354
- await handleCourseAssignment(assignment, userId);
1355
- }
1356
- await api.updateDoc(path, { ...fieldsUpdated });
1357
- return { success: true, fieldsUpdated };
1358
- }
1359
- var submitAssignmentScore = withErrorHandler(
1360
- _submitAssignmentScore,
1361
- "submitAssignmentScore"
1362
- );
1363
- async function handleAssessment(assignment, userId, fieldsUpdated, studentName) {
1364
- var _a, _b, _c;
1365
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1366
- const response = await api.getDoc(path);
1367
- if (!response.data) {
1368
- throw new Error("Score not found");
1369
- }
1370
- await api.updateDoc(path, { status: "PENDING_REVIEW" });
1371
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssessment")) == null ? void 0 : _c({
1372
- assignmentId: assignment.id,
1373
- assignmentTitle: assignment.name,
1374
- userId,
1375
- teacherId: assignment.owners[0],
1376
- studentName
1377
- }));
1378
- fieldsUpdated.status = "PENDING_REVIEW";
1379
- return { success: true, fieldsUpdated };
1380
- }
1381
- async function handleCourseAssignment(assignment, userId) {
1382
- var _a, _b, _c;
1383
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentV2")) == null ? void 0 : _c({
1384
- assignmentId: assignment.id,
1385
- userId
1386
- }));
1387
- }
1388
- async function submitPracticeScore({
1389
- setId,
1390
- userId,
1391
- scores
1392
- }) {
1393
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1394
- const date = (0, import_dayjs4.default)().format("YYYY-MM-DD-HH-mm");
1395
- const ref = refsScoresPractice.practiceScoreHistoryRefDoc({ setId, userId, date });
1396
- const fieldsUpdated = {
1397
- ...scores,
1398
- submitted: true,
1399
- progress: 100,
1400
- submissionDate: serverTimestamp2(),
1401
- status: "SUBMITTED"
1402
- };
1403
- await api.setDoc(ref, { ...fieldsUpdated });
1404
- const refScores = refsScoresPractice.practiceScores({ userId, setId });
1405
- await api.deleteDoc(refScores);
1406
- return { success: true, fieldsUpdated };
1407
- }
1408
-
1409
- // src/domains/assignment/hooks/score-hooks.ts
1410
- var scoreQueryKeys = {
1411
- all: ["scores"],
1412
- byId: (id) => [...scoreQueryKeys.all, id],
1413
- list: () => [...scoreQueryKeys.all, "list"]
1414
- };
1415
- function useScore({
1416
- isAssignment,
1417
- activityId,
1418
- userId = "",
1419
- courseId,
1420
- enabled = true,
1421
- googleClassroomUserId
1422
- }) {
1423
- return (0, import_react_query2.useQuery)({
1424
- queryFn: () => getScore({
1425
- userId,
1426
- courseId,
1427
- activityId,
1428
- googleClassroomUserId,
1429
- isAssignment
1430
- }),
1431
- queryKey: scoreQueryKeys.byId(activityId),
1432
- enabled
1433
- });
1434
- }
1435
- var debounceUpdateScore = debounce(updateScore, 500);
1436
- function useUpdateScore() {
1437
- const { queryClient } = useSpeakableApi();
1438
- const mutation = (0, import_react_query2.useMutation)({
1439
- mutationFn: debounceUpdateScore,
1440
- onMutate: (variables) => {
1441
- return handleOptimisticUpdate({
1442
- queryClient,
1443
- queryKey: scoreQueryKeys.byId(variables.activityId),
1444
- newData: variables.data
1445
- });
1446
- },
1447
- onError: (_, variables, context) => {
1448
- if (context == null ? void 0 : context.previousData)
1449
- queryClient.setQueryData(scoreQueryKeys.byId(variables.activityId), context.previousData);
1450
- },
1451
- onSettled: (_, err, variables) => {
1452
- queryClient.invalidateQueries({
1453
- queryKey: scoreQueryKeys.byId(variables.activityId)
1454
- });
1455
- }
1456
- });
1457
- return {
1458
- mutationUpdateScore: mutation
1459
- };
1460
- }
1461
- function useUpdateCardScore({
1462
- isAssignment,
1463
- activityId,
1464
- userId,
1465
- cardIds,
1466
- weights
1467
- }) {
1468
- const { queryClient } = useSpeakableApi();
1469
- const queryKey = scoreQueryKeys.byId(activityId);
1470
- const mutation = (0, import_react_query2.useMutation)({
1471
- mutationFn: async ({ cardId, cardScore }) => {
1472
- const previousScores = queryClient.getQueryData(queryKey);
1473
- const { progress, score, newScoreUpdated, updatedCardScore } = getScoreUpdated({
1474
- previousScores: previousScores != null ? previousScores : {},
1475
- cardId,
1476
- cardScore,
1477
- cardIds,
1478
- weights
1479
- });
1480
- await updateCardScore({
1481
- userId,
1482
- cardId,
1483
- isAssignment,
1484
- activityId,
1485
- updates: {
1486
- cardScore: updatedCardScore,
1487
- progress,
1488
- score
1489
- }
1490
- });
1491
- return { cardId, scoresUpdated: newScoreUpdated };
1492
- },
1493
- onMutate: ({ cardId, cardScore }) => {
1494
- const previousData = queryClient.getQueryData(queryKey);
1495
- queryClient.setQueryData(queryKey, (previousScore) => {
1496
- const updates = handleOptimisticScore({
1497
- score: previousScore,
1498
- cardId,
1499
- cardScore,
1500
- cardIds,
1501
- weights
1502
- });
1503
- return {
1504
- ...previousScore,
1505
- ...updates
1506
- };
1507
- });
1508
- return { previousData };
1509
- },
1510
- onError: (error, variables, context) => {
1511
- console.log("Error updating card score:", error.message);
1512
- if (context == null ? void 0 : context.previousData) {
1513
- queryClient.setQueryData(queryKey, context.previousData);
1514
- }
1515
- },
1516
- onSettled: () => {
1517
- queryClient.invalidateQueries({
1518
- queryKey
1519
- });
1520
- }
1521
- });
1522
- return {
1523
- mutationUpdateCardScore: mutation
1524
- };
1525
- }
1526
- var getScoreUpdated = ({
1527
- cardId,
1528
- cardScore,
1529
- previousScores,
1530
- cardIds,
1531
- weights
1532
- }) => {
1533
- var _a, _b;
1534
- const previousCard = (_a = previousScores.cards) == null ? void 0 : _a[cardId];
1535
- const newCardScore = {
1536
- ...previousCard != null ? previousCard : {},
1537
- ...cardScore
1538
- };
1539
- const newScores = {
1540
- ...previousScores,
1541
- cards: {
1542
- ...(_b = previousScores.cards) != null ? _b : {},
1543
- [cardId]: newCardScore
1544
- }
1545
- };
1546
- const { score, progress } = calculateScoreAndProgress_default(newScores, cardIds, weights);
1547
- return {
1548
- newScoreUpdated: newScores,
1549
- updatedCardScore: cardScore,
1550
- score,
1551
- progress
1552
- };
1553
- };
1554
- var handleOptimisticScore = ({
1555
- score,
1556
- cardId,
1557
- cardScore,
1558
- cardIds,
1559
- weights
1560
- }) => {
1561
- var _a;
1562
- let cards = { ...(_a = score == null ? void 0 : score.cards) != null ? _a : {} };
1563
- cards = {
1564
- ...cards,
1565
- [cardId]: {
1566
- ...cards[cardId],
1567
- ...cardScore
1568
- }
1569
- };
1570
- const { score: scoreValue, progress } = calculateScoreAndProgress_default(
1571
- // @ts-ignore
1572
- {
1573
- ...score != null ? score : {},
1574
- cards
1575
- },
1576
- cardIds,
1577
- weights
1578
- );
1579
- return { cards, score: scoreValue, progress };
1580
- };
1581
- function useClearScore() {
1582
- const { queryClient } = useSpeakableApi();
1583
- const mutation = (0, import_react_query2.useMutation)({
1584
- mutationFn: clearScore,
1585
- onError: (error) => {
1586
- console.log("Error clearing score:", error.message);
1587
- },
1588
- onSettled: (result) => {
1589
- var _a;
1590
- queryClient.invalidateQueries({
1591
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1592
- });
1593
- }
1594
- });
1595
- return {
1596
- mutationClearScore: mutation
1597
- };
1598
- }
1599
- function useClearScoreV2() {
1600
- const { queryClient } = useSpeakableApi();
1601
- const mutation = (0, import_react_query2.useMutation)({
1602
- mutationFn: clearScoreV2,
1603
- onError: (error) => {
1604
- console.log("Error clearing score V2:", error.message);
1605
- },
1606
- onSettled: (result) => {
1607
- var _a;
1608
- queryClient.invalidateQueries({
1609
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1610
- });
1611
- }
1612
- });
1613
- return {
1614
- mutationClearScore: mutation
1615
- };
1616
- }
1617
- function useSubmitAssignmentScore({
1618
- onAssignmentSubmitted,
1619
- studentName
1620
- }) {
1621
- const { queryClient } = useSpeakableApi();
1622
- const { hasGoogleClassroomGradePassback } = usePermissions_default();
1623
- const { submitAssignmentToGoogleClassroom } = useGoogleClassroom();
1624
- const { createNotification: createNotification2 } = useCreateNotification();
1625
- const mutation = (0, import_react_query2.useMutation)({
1626
- mutationFn: async ({
1627
- assignment,
1628
- userId,
1629
- scores,
1630
- status
1631
- }) => {
1632
- try {
1633
- const scoreUpdated = await submitAssignmentScore({
1634
- assignment,
1635
- userId,
1636
- status,
1637
- studentName
1638
- });
1639
- if (assignment.courseWorkId != null && !assignment.isAssessment && hasGoogleClassroomGradePassback) {
1640
- await submitAssignmentToGoogleClassroom({
1641
- assignment,
1642
- scores
1643
- });
1644
- }
1645
- if (assignment.isAssessment) {
1646
- createNotification2(SpeakableNotificationTypes.ASSESSMENT_SUBMITTED, assignment);
1647
- }
1648
- if (assignment == null ? void 0 : assignment.id) {
1649
- logSubmitAssignment({
1650
- courseId: assignment == null ? void 0 : assignment.courseId
1651
- });
1652
- }
1653
- onAssignmentSubmitted(assignment.id);
1654
- queryClient.setQueryData(scoreQueryKeys.byId(assignment.id), {
1655
- ...scores,
1656
- ...scoreUpdated.fieldsUpdated
1657
- });
1658
- return {
1659
- success: true,
1660
- message: "Score submitted successfully"
1661
- };
1662
- } catch (error) {
1663
- return {
1664
- success: false,
1665
- error
1666
- };
1667
- }
1668
- }
1669
- });
1670
- return {
1671
- submitAssignmentScore: mutation.mutateAsync,
1672
- isLoading: mutation.isPending
1673
- };
1674
- }
1675
- function useSubmitPracticeScore() {
1676
- const { queryClient } = useSpeakableApi();
1677
- const mutation = (0, import_react_query2.useMutation)({
1678
- mutationFn: async ({
1679
- setId,
1680
- userId,
1681
- scores
1682
- }) => {
1683
- try {
1684
- await submitPracticeScore({
1685
- setId,
1686
- userId,
1687
- scores
1688
- });
1689
- queryClient.invalidateQueries({
1690
- queryKey: scoreQueryKeys.byId(setId)
1691
- });
1692
- return {
1693
- success: true,
1694
- message: "Score submitted successfully"
1695
- };
1696
- } catch (error) {
1697
- return {
1698
- success: false,
1699
- error
1700
- };
1701
- }
1702
- }
1703
- });
1704
- return {
1705
- submitPracticeScore: mutation.mutateAsync,
1706
- isLoading: mutation.isPending
1707
- };
1708
- }
1709
-
1710
- // src/domains/cards/card.hooks.ts
1711
- var import_react_query3 = require("@tanstack/react-query");
1712
- var import_react2 = require("react");
1713
-
1714
- // src/domains/cards/card.model.ts
1715
- var ConversationPageMode = /* @__PURE__ */ ((ConversationPageMode2) => {
1716
- ConversationPageMode2["VoiceAndText"] = "voice_and_text";
1717
- ConversationPageMode2["PhoneCall"] = "phone_call";
1718
- return ConversationPageMode2;
1719
- })(ConversationPageMode || {});
1720
- var ActivityPageType = /* @__PURE__ */ ((ActivityPageType2) => {
1721
- ActivityPageType2["READ_REPEAT"] = "READ_REPEAT";
1722
- ActivityPageType2["READ_RESPOND"] = "READ_RESPOND";
1723
- ActivityPageType2["FREE_RESPONSE"] = "FREE_RESPONSE";
1724
- ActivityPageType2["REPEAT"] = "REPEAT";
1725
- ActivityPageType2["RESPOND"] = "RESPOND";
1726
- ActivityPageType2["RESPOND_WRITE"] = "RESPOND_WRITE";
1727
- ActivityPageType2["MULTIPLE_CHOICE"] = "MULTIPLE_CHOICE";
1728
- ActivityPageType2["MEDIA_PAGE"] = "MEDIA_PAGE";
1729
- ActivityPageType2["SHORT_ANSWER"] = "SHORT_ANSWER";
1730
- ActivityPageType2["CONVERSATION"] = "CONVERSATION";
1731
- return ActivityPageType2;
1732
- })(ActivityPageType || {});
1733
- var RESPOND_PAGE_ACTIVITY_TYPES = [
1734
- "READ_RESPOND" /* READ_RESPOND */,
1735
- "RESPOND" /* RESPOND */,
1736
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1737
- "FREE_RESPONSE" /* FREE_RESPONSE */
1738
- ];
1739
- var MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES = ["MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */];
1740
- var REPEAT_PAGE_ACTIVITY_TYPES = ["READ_REPEAT" /* READ_REPEAT */, "REPEAT" /* REPEAT */];
1741
- var RESPOND_WRITE_PAGE_ACTIVITY_TYPES = [
1742
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1743
- "FREE_RESPONSE" /* FREE_RESPONSE */
1744
- ];
1745
- var RESPOND_AUDIO_PAGE_ACTIVITY_TYPES = [
1746
- "RESPOND" /* RESPOND */,
1747
- "READ_RESPOND" /* READ_RESPOND */
1748
- ];
1749
- var CONVERSATION_PAGE_ACTIVITY_TYPES = ["CONVERSATION" /* CONVERSATION */];
1750
-
1751
- // src/domains/cards/card.constants.ts
1752
- var FeedbackTypesCard = /* @__PURE__ */ ((FeedbackTypesCard2) => {
1753
- FeedbackTypesCard2["SuggestedResponse"] = "suggested_response";
1754
- FeedbackTypesCard2["Wida"] = "wida";
1755
- FeedbackTypesCard2["GrammarInsights"] = "grammar_insights";
1756
- FeedbackTypesCard2["Actfl"] = "actfl";
1757
- FeedbackTypesCard2["ProficiencyLevel"] = "proficiency_level";
1758
- return FeedbackTypesCard2;
1759
- })(FeedbackTypesCard || {});
1760
- var LeniencyCard = /* @__PURE__ */ ((LeniencyCard2) => {
1761
- LeniencyCard2["CONFIDENCE"] = "confidence";
1762
- LeniencyCard2["EASY"] = "easy";
1763
- LeniencyCard2["NORMAL"] = "normal";
1764
- LeniencyCard2["HARD"] = "hard";
1765
- return LeniencyCard2;
1766
- })(LeniencyCard || {});
1767
- var LENIENCY_OPTIONS = [
1768
- {
1769
- label: "Build Confidence - most lenient",
1770
- value: "confidence" /* CONFIDENCE */
1771
- },
1772
- {
1773
- label: "Very Lenient",
1774
- value: "easy" /* EASY */
1775
- },
1776
- {
1777
- label: "Normal",
1778
- value: "normal" /* NORMAL */
1779
- },
1780
- {
1781
- label: "No leniency - most strict",
1782
- value: "hard" /* HARD */
1783
- }
1784
- ];
1785
- var STUDENT_LEVELS_OPTIONS = [
1786
- {
1787
- label: "Beginner",
1788
- description: "Beginner Level: Just starting out. Can say a few basic words and phrases.",
1789
- value: "beginner"
1790
- },
1791
- {
1792
- label: "Elementary",
1793
- description: "Elementary Level: Can understand simple sentences and have very basic conversations.",
1794
- value: "elementary"
1795
- },
1796
- {
1797
- label: "Intermediate",
1798
- description: "Intermediate Level: Can talk about everyday topics and handle common situations.",
1799
- value: "intermediate"
1800
- },
1801
- {
1802
- label: "Advanced",
1803
- description: "Advanced Level: Can speak and understand with ease, and explain ideas clearly.",
1804
- value: "advanced"
1805
- },
1806
- {
1807
- label: "Fluent",
1808
- description: "Fluent Level: Speaks naturally and easily. Can use the language in work or school settings.",
1809
- value: "fluent"
1810
- },
1811
- {
1812
- label: "Native-like",
1813
- description: "Native-like Level: Understands and speaks like a native. Can discuss complex ideas accurately.",
1814
- value: "nativeLike"
1815
- }
1816
- ];
1817
- var BASE_RESPOND_FIELD_VALUES = {
1818
- title: "",
1819
- allowRetries: true,
1820
- respondTime: 180,
1821
- maxCharacters: 1e4
1822
- };
1823
- var BASE_REPEAT_FIELD_VALUES = {
1824
- repeat: 1
1825
- };
1826
- var BASE_MULTIPLE_CHOICE_FIELD_VALUES = {
1827
- MCQType: "single",
1828
- answer: ["A"],
1829
- choices: [
1830
- { option: "A", value: "Option A" },
1831
- { option: "B", value: "Option B" },
1832
- { option: "C", value: "Option C" }
1833
- ]
1834
- };
1835
- var VerificationCardStatus = /* @__PURE__ */ ((VerificationCardStatus2) => {
1836
- VerificationCardStatus2["VERIFIED"] = "VERIFIED";
1837
- VerificationCardStatus2["WARNING"] = "WARNING";
1838
- VerificationCardStatus2["NOT_RECOMMENDED"] = "NOT_RECOMMENDED";
1839
- VerificationCardStatus2["NOT_WORKING"] = "NOT_WORKING";
1840
- VerificationCardStatus2["NOT_CHECKED"] = "NOT_CHECKED";
1841
- return VerificationCardStatus2;
1842
- })(VerificationCardStatus || {});
1843
- var CARDS_COLLECTION = "flashcards";
1844
- var refsCardsFiresotre = {
1845
- allCards: CARDS_COLLECTION,
1846
- card: (id) => `${CARDS_COLLECTION}/${id}`
1847
- };
1848
-
1849
- // src/domains/cards/services/get-card.service.ts
1850
- async function _getCard(params) {
1851
- const ref = refsCardsFiresotre.card(params.cardId);
1852
- const response = await api.getDoc(ref);
1853
- if (!response.data) return null;
1854
- const type = response.data.type || "READ_REPEAT" /* READ_REPEAT */;
1855
- const cardsMapped = {
1856
- ...response.data,
1857
- type
1858
- };
1859
- return cardsMapped;
1860
- }
1861
- var getCard = withErrorHandler(_getCard, "getCard");
1862
-
1863
- // src/domains/cards/services/create-card.service.ts
1864
- var import_uuid = require("uuid");
1865
-
1866
- // src/utils/text-utils.ts
1867
- var import_js_sha1 = require("js-sha1");
1868
- var purify = (word) => {
1869
- return word.normalize("NFD").replace(/\/([^" "]*)/g, "").replace(/\([^()]*\)/g, "").replace(/([^()]*)/g, "").replace(/[\u0300-\u036f]/g, "").replace(/[-]/g, " ").replace(/[.,/#!¡¿?؟。,.?$%^&*;:{}=\-_`~()’'…\s]/g, "").replace(/\s\s+/g, " ").toLowerCase().trim();
1870
- };
1871
- var cleanString = (words) => {
1872
- const splitWords = words == null ? void 0 : words.split("+");
1873
- if (splitWords && splitWords.length === 1) {
1874
- const newWord = purify(words);
1875
- return newWord;
1876
- } else if (splitWords && splitWords.length > 1) {
1877
- const split = splitWords.map((w) => purify(w));
1878
- return split;
1879
- } else {
1880
- return "";
1881
- }
1882
- };
1883
- var getWordHash = (word, language) => {
1884
- const cleanedWord = cleanString(word);
1885
- const wordHash = (0, import_js_sha1.sha1)(`${language}-${cleanedWord}`);
1886
- console.log("wordHash core library", wordHash);
1887
- return wordHash;
1888
- };
1889
- function getPhraseLength(phrase, input) {
1890
- if (Array.isArray(phrase) && phrase.includes(input)) {
1891
- return phrase[phrase.indexOf(input)].split(" ").length;
1892
- } else {
1893
- return phrase ? phrase.split(" ").length : 0;
1894
- }
1895
- }
1896
-
1897
- // src/domains/cards/services/get-card-verification-status.service.ts
1898
- var charactarLanguages = ["zh", "ja", "ko"];
1899
- var getVerificationStatus = async (target_text, language) => {
1900
- if ((target_text == null ? void 0 : target_text.length) < 3 && !charactarLanguages.includes(language)) {
1901
- return "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1902
- }
1903
- const hash = getWordHash(target_text, language);
1904
- const response = await api.getDoc(`checked-pronunciations/${hash}`);
1905
- try {
1906
- if (response.data) {
1907
- return processRecord(response.data);
1908
- } else {
1909
- return "NOT_CHECKED" /* NOT_CHECKED */;
1910
- }
1911
- } catch (e) {
1912
- return "NOT_CHECKED" /* NOT_CHECKED */;
1913
- }
1914
- };
1915
- var processRecord = (data) => {
1916
- const { pronunciations = 0, fails = 0 } = data;
1917
- const attempts = pronunciations + fails;
1918
- const successRate = attempts > 0 ? pronunciations / attempts * 100 : 0;
1919
- let newStatus = null;
1920
- if (attempts < 6) {
1921
- return "NOT_CHECKED" /* NOT_CHECKED */;
1922
- }
1923
- if (successRate > 25) {
1924
- newStatus = "VERIFIED" /* VERIFIED */;
1925
- } else if (successRate > 10) {
1926
- newStatus = "WARNING" /* WARNING */;
1927
- } else if (fails > 20 && successRate < 10 && pronunciations > 1) {
1928
- newStatus = "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1929
- } else if (pronunciations === 0 && fails > 20) {
1930
- newStatus = "NOT_WORKING" /* NOT_WORKING */;
1931
- } else {
1932
- newStatus = "NOT_CHECKED" /* NOT_CHECKED */;
1933
- }
1934
- return newStatus;
1935
- };
1936
-
1937
- // src/domains/cards/services/create-card.service.ts
1938
- async function _createCard({ data }) {
1939
- const response = await api.addDoc(refsCardsFiresotre.allCards, data);
1940
- return response;
1941
- }
1942
- var createCard = withErrorHandler(_createCard, "createCard");
1943
- async function _createCards({ cards }) {
1944
- const { writeBatch: writeBatch2, doc: doc2 } = api.accessHelpers();
1945
- const batch = writeBatch2();
1946
- const cardsWithId = [];
1947
- for (const card of cards) {
1948
- const cardId = (0, import_uuid.v4)();
1949
- const ref = doc2(refsCardsFiresotre.card(cardId));
1950
- const newCardObject = {
1951
- ...card,
1952
- id: cardId
1953
- };
1954
- if (card.type === "READ_REPEAT" /* READ_REPEAT */ && card.target_text && card.language) {
1955
- const verificationStatus = await getVerificationStatus(card.target_text, card.language);
1956
- newCardObject.verificationStatus = verificationStatus || null;
1957
- }
1958
- cardsWithId.push(newCardObject);
1959
- batch.set(ref, newCardObject);
1960
- }
1961
- await batch.commit();
1962
- return cardsWithId;
1963
- }
1964
- var createCards = withErrorHandler(_createCards, "createCards");
1965
-
1966
- // src/domains/cards/card.hooks.ts
1967
- var cardsQueryKeys = {
1968
- all: ["cards"],
1969
- one: (params) => [...cardsQueryKeys.all, params.cardId]
1970
- };
1971
- function useCards({
1972
- cardIds,
1973
- enabled = true,
1974
- asObject
1975
- }) {
1976
- const queries = (0, import_react_query3.useQueries)({
1977
- queries: cardIds.map((cardId) => ({
1978
- enabled: enabled && cardIds.length > 0,
1979
- queryKey: cardsQueryKeys.one({
1980
- cardId
1981
- }),
1982
- queryFn: () => getCard({ cardId })
1983
- }))
1984
- });
1985
- const cards = queries.map((query2) => query2.data).filter(Boolean);
1986
- const cardsObject = (0, import_react2.useMemo)(() => {
1987
- if (!asObject) return null;
1988
- return cards.reduce((acc, card) => {
1989
- acc[card.id] = card;
1990
- return acc;
1991
- }, {});
1992
- }, [asObject, cards]);
1993
- return {
1994
- cards,
1995
- cardsObject,
1996
- cardsQueries: queries
1997
- };
1998
- }
1999
- function useCreateCard() {
2000
- const { queryClient } = useSpeakableApi();
2001
- const mutationCreateCard = (0, import_react_query3.useMutation)({
2002
- mutationFn: createCard,
2003
- onSuccess: (cardCreated) => {
2004
- queryClient.invalidateQueries({ queryKey: cardsQueryKeys.one({ cardId: cardCreated.id }) });
2005
- }
2006
- });
2007
- return {
2008
- mutationCreateCard
2009
- };
2010
- }
2011
- function useCreateCards() {
2012
- const mutationCreateCards = (0, import_react_query3.useMutation)({
2013
- mutationFn: createCards
2014
- });
2015
- return {
2016
- mutationCreateCards
2017
- };
2018
- }
2019
- function getCardFromCache({
2020
- cardId,
2021
- queryClient
2022
- }) {
2023
- return queryClient.getQueryData(cardsQueryKeys.one({ cardId }));
2024
- }
2025
- function updateCardInCache({
2026
- cardId,
2027
- card,
2028
- queryClient
2029
- }) {
2030
- queryClient.setQueryData(cardsQueryKeys.one({ cardId }), card);
2031
- }
2032
- function useGetCard({ cardId, enabled = true }) {
2033
- const query2 = (0, import_react_query3.useQuery)({
2034
- queryKey: cardsQueryKeys.one({ cardId }),
2035
- queryFn: () => getCard({ cardId }),
2036
- enabled: enabled && !!cardId
2037
- });
2038
- return query2;
2039
- }
2040
-
2041
- // src/domains/cards/card.repo.ts
2042
- var createCardRepo = () => {
2043
- return {
2044
- createCard,
2045
- createCards,
2046
- getCard
2047
- };
2048
- };
2049
-
2050
- // src/domains/cards/utils/check-page-type.ts
2051
- function checkIsRepeatPage(cardType) {
2052
- if (cardType === void 0) return false;
2053
- return REPEAT_PAGE_ACTIVITY_TYPES.includes(cardType);
2054
- }
2055
- function checkIsMCPage(cardType) {
2056
- if (cardType === void 0) return false;
2057
- return MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES.includes(cardType);
2058
- }
2059
- function checkIsRespondPage(cardType) {
2060
- if (cardType === void 0) return false;
2061
- return RESPOND_PAGE_ACTIVITY_TYPES.includes(cardType);
2062
- }
2063
- function checkIsRespondWrittenPage(cardType) {
2064
- if (cardType === void 0) return false;
2065
- return RESPOND_WRITE_PAGE_ACTIVITY_TYPES.includes(cardType);
2066
- }
2067
- function checkIsRespondAudioPage(cardType) {
2068
- if (cardType === void 0) return false;
2069
- return RESPOND_AUDIO_PAGE_ACTIVITY_TYPES.includes(cardType);
2070
- }
2071
- var checkIsMediaPage = (cardType) => {
2072
- if (cardType === void 0) return false;
2073
- return cardType === "MEDIA_PAGE" /* MEDIA_PAGE */;
2074
- };
2075
- var checkIsShortAnswerPage = (cardType) => {
2076
- if (cardType === void 0) return false;
2077
- return cardType === "SHORT_ANSWER" /* SHORT_ANSWER */;
2078
- };
2079
- var checkIsConversationPage = (cardType) => {
2080
- if (cardType === void 0) return false;
2081
- return cardType === "CONVERSATION" /* CONVERSATION */;
2082
- };
2083
- var checkTypePageActivity = (cardType) => {
2084
- const isRespondAudio = checkIsRespondAudioPage(cardType);
2085
- const isRespondWritten = checkIsRespondWrittenPage(cardType);
2086
- const isRespond = checkIsRespondPage(cardType);
2087
- const isMC = checkIsMCPage(cardType);
2088
- const isRepeat = checkIsRepeatPage(cardType);
2089
- const isMediaPage = checkIsMediaPage(cardType);
2090
- const isShortAnswer = checkIsShortAnswerPage(cardType);
2091
- const isConversation = checkIsConversationPage(cardType);
2092
- const isNoOneOfThem = !isRespond && !isMC && !isRepeat && !isMediaPage && !isShortAnswer && !isConversation;
2093
- if (isNoOneOfThem) {
2094
- return {
2095
- isRespondAudio: false,
2096
- isRespondWritten: false,
2097
- isRespond: false,
2098
- isMC: false,
2099
- isRepeat: true,
2100
- isMediaPage: false,
2101
- isShortAnswer: false,
2102
- hasSomeType: false,
2103
- isConversation: false
2104
- };
2105
- }
2106
- return {
2107
- isRespondAudio,
2108
- isRespondWritten,
2109
- isRespond,
2110
- isMC,
2111
- isRepeat,
2112
- isMediaPage,
2113
- isShortAnswer,
2114
- hasSomeType: true,
2115
- isConversation
2116
- };
2117
- };
2118
-
2119
- // src/domains/cards/utils/get-page-prompt.ts
2120
- function extractTextFromRichText(richText) {
2121
- if (!richText) return "";
2122
- return richText.replace(/<[^>]*>/g, "").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").trim();
2123
- }
2124
- function getPagePrompt(card) {
2125
- if (!card) return { has: false, text: "", rich_text: "", isTextEqualToRichText: false };
2126
- const { isMC, isRepeat, isRespond, isShortAnswer, isConversation } = checkTypePageActivity(
2127
- card == null ? void 0 : card.type
2128
- );
2129
- const hidePrompt = (card == null ? void 0 : card.hidePrompt) === true;
2130
- const createReturnObject = (text, richText, extraText) => {
2131
- const plainText = text || "";
2132
- const richTextPlain = extractTextFromRichText(richText);
2133
- return {
2134
- has: true,
2135
- text: plainText,
2136
- rich_text: richText || "",
2137
- isTextEqualToRichText: plainText.trim() === richTextPlain.trim(),
2138
- extraText: extraText || ""
2139
- };
2140
- };
2141
- if (isRepeat) {
2142
- return createReturnObject(card == null ? void 0 : card.target_text, card == null ? void 0 : card.rich_text);
2143
- }
2144
- if (isConversation) {
2145
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text, card == null ? void 0 : card.goal);
2146
- }
2147
- if (isRespond && !hidePrompt) {
2148
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2149
- }
2150
- if (isMC) {
2151
- return createReturnObject(card == null ? void 0 : card.question, card == null ? void 0 : card.rich_text);
2152
- }
2153
- if (isShortAnswer && !hidePrompt) {
2154
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2155
- }
2156
- return {
2157
- has: false,
2158
- text: "",
2159
- rich_text: "",
2160
- isTextEqualToRichText: false,
2161
- extraText: ""
2162
- };
2163
- }
2164
-
2165
- // src/domains/cards/utils/get-completed-pages.ts
2166
- var getTotalCompletedCards = (pageScores) => {
2167
- return Object.values(pageScores != null ? pageScores : {}).reduce((acc, cardScore) => {
2168
- var _a, _b;
2169
- if (((_b = (_a = cardScore.completed) != null ? _a : cardScore.score) != null ? _b : cardScore.score === 0) && !cardScore.media_area_opened) {
2170
- acc++;
2171
- }
2172
- return acc;
2173
- }, 0);
2174
- };
2175
-
2176
- // src/domains/cards/utils/get-label-page.ts
2177
- var labels = {
2178
- repeat: {
2179
- short: "Repeat",
2180
- long: "Listen & Repeat"
2181
- },
2182
- mc: {
2183
- short: "Multiple Choice",
2184
- long: "Multiple Choice"
2185
- },
2186
- mediaPage: {
2187
- short: "Media Page",
2188
- long: "Media Page"
2189
- },
2190
- shortAnswer: {
2191
- short: "Short Answer",
2192
- long: "Short Answer"
2193
- },
2194
- respondWritten: {
2195
- short: "Open Response",
2196
- long: "Written Open Response"
2197
- },
2198
- respondAudio: {
2199
- short: "Open Response",
2200
- long: "Spoken Open Response"
2201
- }
2202
- };
2203
- var getLabelPage = (pageType) => {
2204
- if (!pageType) {
2205
- return {
2206
- short: "",
2207
- long: ""
2208
- };
2209
- }
2210
- const { isRepeat, isMC, isMediaPage, isShortAnswer, isRespondWritten, isRespondAudio } = checkTypePageActivity(pageType);
2211
- if (isRepeat) {
2212
- return labels.repeat;
2213
- }
2214
- if (isMC) {
2215
- return labels.mc;
2216
- }
2217
- if (isMediaPage) {
2218
- return labels.mediaPage;
2219
- }
2220
- if (isShortAnswer) {
2221
- return labels.shortAnswer;
2222
- }
2223
- if (isRespondWritten) {
2224
- return labels.respondWritten;
2225
- }
2226
- if (isRespondAudio) {
2227
- return labels.respondAudio;
2228
- }
2229
- return {
2230
- short: "",
2231
- long: ""
2232
- };
2233
- };
2234
-
2235
- // src/domains/cards/utils/get-page-media-data.ts
2236
- function getPageMediaData(page) {
2237
- var _a, _b, _c, _d;
2238
- const direction = (_a = page.media_area_layout) != null ? _a : "left";
2239
- const { isMediaPage } = checkTypePageActivity(page.type);
2240
- const singleMedia = getSingleMediaPageData(page);
2241
- const resource = {
2242
- id: (_c = (_b = page.media_area_id) != null ? _b : page.media_area_context_ref) != null ? _c : void 0,
2243
- shouldRender: ((_d = page.media_area_id) != null ? _d : page.media_area_context_ref) != null ? true : false
2244
- };
2245
- const promptMedia = {
2246
- direction,
2247
- content: singleMedia,
2248
- shouldRender: singleMedia !== void 0
2249
- };
2250
- return {
2251
- isMediaPage,
2252
- resource,
2253
- promptMedia
2254
- };
2255
- }
2256
- function getSingleMediaPageData(page) {
2257
- if (!page.media) return void 0;
2258
- const media = {
2259
- type: page.media.type,
2260
- content: page.media.url
2261
- };
2262
- return {
2263
- ...media,
2264
- rawObject: page.media
2265
- };
2266
- }
2267
-
2268
- // src/domains/sets/set.hooks.ts
2269
- var import_react_query4 = require("@tanstack/react-query");
2270
-
2271
- // src/domains/sets/set.constants.ts
2272
- var SETS_COLLECTION = "sets";
2273
- var refsSetsFirestore = {
2274
- allSets: SETS_COLLECTION,
2275
- set: (id) => `${SETS_COLLECTION}/${id}`
2276
- };
2277
-
2278
- // src/domains/sets/services/get-set.service.ts
2279
- async function _getSet({ setId }) {
2280
- const response = await api.getDoc(refsSetsFirestore.set(setId));
2281
- return response.data;
2282
- }
2283
- var getSet = withErrorHandler(_getSet, "getSet");
2284
-
2285
- // src/domains/sets/set.hooks.ts
2286
- var setsQueryKeys = {
2287
- all: ["sets"],
2288
- one: (params) => [...setsQueryKeys.all, params.setId]
2289
- };
2290
- var useSet = ({ setId, enabled }) => {
2291
- return (0, import_react_query4.useQuery)({
2292
- queryKey: setsQueryKeys.one({ setId }),
2293
- queryFn: () => getSet({ setId }),
2294
- enabled: setId !== void 0 && setId !== "" && enabled
2295
- });
2296
- };
2297
- function getSetFromCache({
2298
- setId,
2299
- queryClient
2300
- }) {
2301
- if (!setId) return null;
2302
- return queryClient.getQueryData(setsQueryKeys.one({ setId }));
2303
- }
2304
- function updateSetInCache({
2305
- set,
2306
- queryClient
2307
- }) {
2308
- const { id, ...setData } = set;
2309
- queryClient.setQueryData(setsQueryKeys.one({ setId: id }), setData);
2310
- }
2311
-
2312
- // src/domains/sets/set.repo.ts
2313
- var createSetRepo = () => {
2314
- return {
2315
- getSet
2316
- };
2317
- };
2318
-
2319
- // src/utils/ai/detect-transcript-hallucionation.ts
2320
- var HALLUCINATION_THRESHOLDS = {
2321
- // Short repeats
2322
- MIN_CONSECUTIVE_REPEATS: 5,
2323
- // Increased from 3 to allow phrases like "pio pio pio" or "no no no no"
2324
- MIN_WORDS_FOR_RATIO_CHECK: 15,
2325
- // Increased from 10 to require longer text for ratio check
2326
- MAX_UNIQUE_WORDS_FOR_RATIO: 3,
2327
- MIN_REPETITION_RATIO: 4,
2328
- // Increased from 3 to be more permissive
2329
- // Phrase repeats
2330
- MIN_SENTENCE_LENGTH: 15,
2331
- // Increased from 10 to avoid flagging short natural sentences
2332
- MIN_CONSECUTIVE_SIMILAR_SENTENCES: 3,
2333
- // Increased from 2 to allow some natural repetition
2334
- MIN_SENTENCES_FOR_DUPLICATE_CHECK: 4,
2335
- // Increased from 3
2336
- // Cyclic patterns
2337
- MIN_CYCLE_LENGTH: 30,
2338
- // Increased from 20 to focus on longer patterns
2339
- MIN_CYCLE_REPEATS: 3,
2340
- // Entropy detection
2341
- MIN_LENGTH_FOR_ENTROPY_CHECK: 60,
2342
- // Increased from 50
2343
- MAX_ENTROPY_THRESHOLD: 2.2,
2344
- // Decreased from 2.5 to be more strict on entropy (lower = more repetitive needed)
2345
- // Similarity
2346
- SENTENCE_SIMILARITY_THRESHOLD: 0.85,
2347
- // Increased from 0.8 to require more similarity
2348
- SEGMENT_SIMILARITY_THRESHOLD: 0.9
2349
- // Increased from 0.85
2350
- };
2351
- function detectTranscriptHallucinationWithDetails(transcript) {
2352
- if (!transcript || transcript.trim().length === 0) {
2353
- return { isHallucination: false };
2354
- }
2355
- const text = transcript.trim();
2356
- if (text.length < 10) {
2357
- return { isHallucination: false };
2358
- }
2359
- const shortRepeats = detectShortRepeats(text);
2360
- if (shortRepeats) {
2361
- return {
2362
- isHallucination: true,
2363
- reason: "Detected repeated short words or phrases",
2364
- confidence: 0.9
2365
- };
2366
- }
2367
- const phraseRepeats = detectPhraseRepeats(text);
2368
- if (phraseRepeats) {
2369
- return {
2370
- isHallucination: true,
2371
- reason: "Detected repeated sentences or phrases",
2372
- confidence: 0.85
2373
- };
2374
- }
2375
- const cyclicRepeats = detectCyclicPattern(text);
2376
- if (cyclicRepeats) {
2377
- return {
2378
- isHallucination: true,
2379
- reason: "Detected cyclic repetition pattern",
2380
- confidence: 0.8
2381
- };
2382
- }
2383
- if (text.length >= HALLUCINATION_THRESHOLDS.MIN_LENGTH_FOR_ENTROPY_CHECK) {
2384
- const entropy = calculateEntropy(text);
2385
- if (entropy < HALLUCINATION_THRESHOLDS.MAX_ENTROPY_THRESHOLD) {
2386
- return {
2387
- isHallucination: true,
2388
- reason: "Detected low entropy (likely gibberish or excessive repetition)",
2389
- confidence: 0.75
2390
- };
2391
- }
2392
- }
2393
- return { isHallucination: false };
2394
- }
2395
- function detectShortRepeats(text) {
2396
- const words = text.toLowerCase().split(/[\s,;.!?]+/).filter((w) => w.length > 0);
2397
- if (words.length < 4) return false;
2398
- let repeatCount = 1;
2399
- for (let i = 1; i < words.length; i++) {
2400
- if (words[i] === words[i - 1]) {
2401
- repeatCount++;
2402
- if (repeatCount >= HALLUCINATION_THRESHOLDS.MIN_CONSECUTIVE_REPEATS) {
2403
- return true;
2404
- }
2405
- } else {
2406
- repeatCount = 1;
2407
- }
2408
- }
2409
- const uniqueWords = new Set(words);
2410
- const repetitionRatio = words.length / uniqueWords.size;
2411
- if (words.length >= HALLUCINATION_THRESHOLDS.MIN_WORDS_FOR_RATIO_CHECK && uniqueWords.size <= HALLUCINATION_THRESHOLDS.MAX_UNIQUE_WORDS_FOR_RATIO && repetitionRatio >= HALLUCINATION_THRESHOLDS.MIN_REPETITION_RATIO) {
2412
- return true;
2413
- }
2414
- return false;
2415
- }
2416
- function detectPhraseRepeats(text) {
2417
- const sentences = text.split(/[.!?]+/).map((s) => s.trim().toLowerCase()).filter((s) => s.length > HALLUCINATION_THRESHOLDS.MIN_SENTENCE_LENGTH);
2418
- if (sentences.length < 2) return false;
2419
- for (let i = 0; i < sentences.length - 1; i++) {
2420
- let consecutiveRepeats = 1;
2421
- for (let j = i + 1; j < sentences.length; j++) {
2422
- if (isSimilarSentence(sentences[i], sentences[j])) {
2423
- consecutiveRepeats++;
2424
- } else {
2425
- break;
2426
- }
2427
- }
2428
- if (consecutiveRepeats >= HALLUCINATION_THRESHOLDS.MIN_CONSECUTIVE_SIMILAR_SENTENCES) {
2429
- return true;
2430
- }
2431
- }
2432
- const uniqueSentences = new Set(sentences);
2433
- if (sentences.length >= HALLUCINATION_THRESHOLDS.MIN_SENTENCES_FOR_DUPLICATE_CHECK && uniqueSentences.size === 1) {
2434
- return true;
2435
- }
2436
- return false;
2437
- }
2438
- function isSimilarSentence(s1, s2, threshold = HALLUCINATION_THRESHOLDS.SENTENCE_SIMILARITY_THRESHOLD) {
2439
- if (s1 === s2) return true;
2440
- const normalized1 = s1.replace(/\s+/g, " ").trim();
2441
- const normalized2 = s2.replace(/\s+/g, " ").trim();
2442
- if (normalized1 === normalized2) return true;
2443
- const words1 = normalized1.split(/\s+/);
2444
- const words2 = normalized2.split(/\s+/);
2445
- if (Math.abs(words1.length - words2.length) > 2) return false;
2446
- const set1 = new Set(words1);
2447
- const set2 = new Set(words2);
2448
- const intersection = new Set([...set1].filter((w) => set2.has(w)));
2449
- const similarity = intersection.size * 2 / (set1.size + set2.size);
2450
- return similarity >= threshold;
2451
- }
2452
- function detectCyclicPattern(text) {
2453
- const normalized = text.toLowerCase().replace(/\s+/g, " ").trim();
2454
- const length = normalized.length;
2455
- const minCycleLength = HALLUCINATION_THRESHOLDS.MIN_CYCLE_LENGTH;
2456
- const maxCycleLength = Math.floor(length / 2);
2457
- if (maxCycleLength < minCycleLength) return false;
2458
- const step = 5;
2459
- for (let cycleLen = minCycleLength; cycleLen <= maxCycleLength; cycleLen += step) {
2460
- const pattern = normalized.substring(0, cycleLen);
2461
- let matchCount = 0;
2462
- let pos = 0;
2463
- while (pos < length) {
2464
- const segment = normalized.substring(pos, pos + cycleLen);
2465
- if (segment.length < cycleLen) {
2466
- const partialMatch = pattern.startsWith(segment);
2467
- if (partialMatch && matchCount > 0) {
2468
- matchCount++;
2469
- }
2470
- break;
2471
- }
2472
- if (segment === pattern || isSegmentSimilar(segment, pattern)) {
2473
- matchCount++;
2474
- pos += cycleLen;
2475
- } else {
2476
- break;
2477
- }
2478
- }
2479
- if (matchCount >= HALLUCINATION_THRESHOLDS.MIN_CYCLE_REPEATS) {
2480
- return true;
2481
- }
2482
- }
2483
- return false;
2484
- }
2485
- function isSegmentSimilar(s1, s2) {
2486
- if (s1 === s2) return true;
2487
- if (s1.length !== s2.length) return false;
2488
- let matches = 0;
2489
- const minLength = Math.min(s1.length, s2.length);
2490
- for (let i = 0; i < minLength; i++) {
2491
- if (s1[i] === s2[i]) {
2492
- matches++;
2493
- }
2494
- }
2495
- const similarity = matches / minLength;
2496
- return similarity >= HALLUCINATION_THRESHOLDS.SEGMENT_SIMILARITY_THRESHOLD;
2497
- }
2498
- function calculateEntropy(text) {
2499
- if (!text || text.length === 0) {
2500
- return 0;
2501
- }
2502
- const frequencies = /* @__PURE__ */ new Map();
2503
- for (const char of text.toLowerCase()) {
2504
- frequencies.set(char, (frequencies.get(char) || 0) + 1);
2505
- }
2506
- let entropy = 0;
2507
- const length = text.length;
2508
- for (const count of frequencies.values()) {
2509
- const probability = count / length;
2510
- entropy -= probability * Math.log2(probability);
2511
- }
2512
- return entropy;
2513
- }
2514
- function cleanHallucinatedTranscript(transcript) {
2515
- var _a, _b;
2516
- const result = detectTranscriptHallucinationWithDetails(transcript);
2517
- if (result.isHallucination) {
2518
- console.warn(
2519
- "Hallucinated transcript detected and removed:",
2520
- transcript.substring(0, 100),
2521
- `
2522
- Reason: ${(_a = result.reason) != null ? _a : "Unknown"}`,
2523
- `Confidence: ${String((_b = result.confidence) != null ? _b : "Unknown")}`
2524
- );
2525
- return "";
2526
- }
2527
- return transcript;
2528
- }
2529
-
2530
- // src/utils/ai/get-transcript.ts
2531
- async function getTranscript(model, args, cleanHallucinations = true) {
2532
- var _a, _b, _c, _d, _e, _f;
2533
- const getGeminiTranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getGeminiTranscript");
2534
- const getAssemblyAITranscript = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "transcribeAssemblyAIAudio");
2535
- const getWhisperTranscript = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "transcribeAudio");
2536
- if (model === "whisper") {
2537
- try {
2538
- const { data } = await (getWhisperTranscript == null ? void 0 : getWhisperTranscript({
2539
- audioUrl: args.audioUrl,
2540
- language: args.language
2541
- }));
2542
- return cleanHallucinations ? cleanHallucinatedTranscript(data) : data;
2543
- } catch (error) {
2544
- console.error("Error getting transcript from Whisper:", error);
2545
- throw error;
2546
- }
2547
- }
2548
- if (model === "gemini") {
2549
- try {
2550
- const { data } = await (getGeminiTranscript == null ? void 0 : getGeminiTranscript({
2551
- audioUrl: args.audioUrl,
2552
- targetLanguage: args.language,
2553
- prompt: args.prompt
2554
- }));
2555
- return cleanHallucinations ? cleanHallucinatedTranscript(data.transcript) : data.transcript;
2556
- } catch (error) {
2557
- console.error("Error getting transcript from Gemini:", error);
2558
- throw error;
2559
- }
2560
- }
2561
- if (model === "assemblyai") {
2562
- try {
2563
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
2564
- audioUrl: args.audioUrl,
2565
- language: args.language
2566
- }));
2567
- return cleanHallucinations ? cleanHallucinatedTranscript(response.data) : response.data;
2568
- } catch (error) {
2569
- console.error("Error getting transcript from AssemblyAI:", error);
2570
- throw error;
2571
- }
2572
- }
2573
- return null;
2574
- }
2575
- async function getTranscriptCycle(args) {
2576
- const models = ["whisper", "gemini", "assemblyai"];
2577
- let transcript = "";
2578
- let lastError = null;
2579
- for (const model of models) {
2580
- try {
2581
- const transcriptResult = await getTranscript(model, args, false);
2582
- const rawTranscript = transcriptResult || "";
2583
- transcript = cleanHallucinatedTranscript(rawTranscript);
2584
- if (transcript !== "") {
2585
- console.log(`Successfully got transcript from ${model}`);
2586
- break;
2587
- }
2588
- console.warn(`${model} returned empty transcript, trying next model`);
2589
- } catch (e) {
2590
- console.error(`Error with ${model} transcript:`, e);
2591
- lastError = e;
2592
- }
2593
- }
2594
- if (transcript === "") {
2595
- console.error("All transcript models failed or returned empty", lastError);
2596
- return {
2597
- transcript: "",
2598
- success: false
2599
- };
2600
- }
2601
- return {
2602
- transcript,
2603
- success: true
2604
- };
2605
- }
2606
-
2607
- // src/constants/all-langs.json
2608
- var all_langs_default = {
2609
- af: "Afrikaans",
2610
- sq: "Albanian",
2611
- am: "Amharic",
2612
- ar: "Arabic",
2613
- hy: "Armenian",
2614
- az: "Azerbaijani",
2615
- eu: "Basque",
2616
- be: "Belarusian",
2617
- bn: "Bengali",
2618
- bs: "Bosnian",
2619
- bg: "Bulgarian",
2620
- ca: "Catalan",
2621
- ceb: "Cebuano",
2622
- zh: "Chinese",
2623
- co: "Corsican",
2624
- hr: "Croatian",
2625
- cs: "Czech",
2626
- da: "Danish",
2627
- nl: "Dutch",
2628
- en: "English",
2629
- eo: "Esperanto",
2630
- et: "Estonian",
2631
- fi: "Finnish",
2632
- fr: "French",
2633
- fy: "Frisian",
2634
- gl: "Galician",
2635
- ka: "Georgian",
2636
- de: "German",
2637
- el: "Greek",
2638
- gu: "Gujarati",
2639
- ht: "Haitian Creole",
2640
- ha: "Hausa",
2641
- haw: "Hawaiian",
2642
- he: "Hebrew",
2643
- hi: "Hindi",
2644
- hmn: "Hmong",
2645
- hu: "Hungarian",
2646
- is: "Icelandic",
2647
- ig: "Igbo",
2648
- id: "Indonesian",
2649
- ga: "Irish",
2650
- it: "Italian",
2651
- ja: "Japanese",
2652
- jv: "Javanese",
2653
- kn: "Kannada",
2654
- kk: "Kazakh",
2655
- km: "Khmer",
2656
- ko: "Korean",
2657
- ku: "Kurdish",
2658
- ky: "Kyrgyz",
2659
- lo: "Lao",
2660
- la: "Latin",
2661
- lv: "Latvian",
2662
- lt: "Lithuanian",
2663
- lb: "Luxembourgish",
2664
- mk: "Macedonian",
2665
- mg: "Malagasy",
2666
- ms: "Malay",
2667
- ml: "Malayalam",
2668
- mt: "Maltese",
2669
- mi: "Maori",
2670
- mr: "Marathi",
2671
- mn: "Mongolian",
2672
- my: "Myanmar (Burmese)",
2673
- ne: "Nepali",
2674
- no: "Norwegian",
2675
- ny: "Nyanja (Chichewa)",
2676
- ps: "Pashto",
2677
- fa: "Persian",
2678
- pl: "Polish",
2679
- pt: "Portuguese",
2680
- pa: "Punjabi",
2681
- ro: "Romanian",
2682
- ru: "Russian",
2683
- sm: "Samoan",
2684
- gd: "Scots Gaelic",
2685
- sr: "Serbian",
2686
- st: "Sesotho",
2687
- sn: "Shona",
2688
- sd: "Sindhi",
2689
- si: "Sinhala (Sinhalese)",
2690
- sk: "Slovak",
2691
- sl: "Slovenian",
2692
- so: "Somali",
2693
- es: "Spanish",
2694
- su: "Sundanese",
2695
- sw: "Swahili",
2696
- sv: "Swedish",
2697
- tl: "Tagalog (Filipino)",
2698
- tg: "Tajik",
2699
- ta: "Tamil",
2700
- te: "Telugu",
2701
- th: "Thai",
2702
- tr: "Turkish",
2703
- uk: "Ukrainian",
2704
- ur: "Urdu",
2705
- uz: "Uzbek",
2706
- vi: "Vietnamese",
2707
- cy: "Welsh",
2708
- xh: "Xhosa",
2709
- yi: "Yiddish",
2710
- yo: "Yoruba",
2711
- zu: "Zulu"
2712
- };
2713
-
2714
- // src/utils/ai/get-respond-card-tool.ts
2715
- var getRespondCardTool = ({
2716
- language,
2717
- standard = "actfl"
2718
- }) => {
2719
- const lang = all_langs_default[language] || "English";
2720
- const tool = {
2721
- tool_choice: {
2722
- type: "function",
2723
- function: { name: "get_feedback" }
2724
- },
2725
- tools: [
2726
- {
2727
- type: "function",
2728
- function: {
2729
- name: "get_feedback",
2730
- description: "Get feedback on a student's response",
2731
- parameters: {
2732
- type: "object",
2733
- required: [
2734
- "success",
2735
- "score",
2736
- "score_justification",
2737
- "errors",
2738
- "improvedResponse",
2739
- "compliments"
2740
- ],
2741
- properties: {
2742
- success: {
2743
- type: "boolean",
2744
- description: "Mark true if the student's response was on-topic and generally demonstrated understanding. A few grammar mistakes are acceptable. Mark false if the student's response was off-topic or did not demonstrate understanding."
2745
- },
2746
- errors: {
2747
- type: "array",
2748
- items: {
2749
- type: "object",
2750
- required: ["error", "grammar_error_type", "correction", "justification"],
2751
- properties: {
2752
- error: {
2753
- type: "string",
2754
- description: "The grammatical error in the student's response."
2755
- },
2756
- correction: {
2757
- type: "string",
2758
- description: "The suggested correction to the error"
2759
- },
2760
- justification: {
2761
- type: "string",
2762
- description: `An explanation of the rationale behind the suggested correction. WRITE THIS IN ${lang}!`
2763
- },
2764
- grammar_error_type: {
2765
- type: "string",
2766
- enum: [
2767
- "subjVerbAgree",
2768
- "tenseErrors",
2769
- "articleMisuse",
2770
- "prepositionErrors",
2771
- "adjNounAgree",
2772
- "pronounErrors",
2773
- "wordOrder",
2774
- "verbConjugation",
2775
- "pluralization",
2776
- "negationErrors",
2777
- "modalVerbMisuse",
2778
- "relativeClause",
2779
- "auxiliaryVerb",
2780
- "complexSentenceAgreement",
2781
- "idiomaticExpression",
2782
- "registerInconsistency",
2783
- "voiceMisuse"
2784
- ],
2785
- description: "The type of grammatical error found. It should be one of the following categories: subject-verb agreement, tense errors, article misuse, preposition errors, adjective-noun agreement, pronoun errors, word order, verb conjugation, pluralization errors, negation errors, modal verb misuse, relative clause errors, auxiliary verb misuse, complex sentence agreement, idiomatic expression, register inconsistency, or voice misuse"
2786
- }
2787
- }
2788
- },
2789
- description: "An array of objects, each representing a grammatical error in the student's response. Each object should have the following properties: error, grammar_error_type, correction, and justification. If there were no errors, return an empty array."
2790
- },
2791
- compliments: {
2792
- type: "array",
2793
- items: {
2794
- type: "string"
2795
- },
2796
- description: `An array of strings, each representing something the student did well. Each string should be WRITTEN IN ${lang}!`
2797
- },
2798
- improvedResponse: {
2799
- type: "string",
2800
- description: "An improved response with proper grammar and more detail, if applicable."
2801
- },
2802
- score: {
2803
- type: "number",
2804
- description: "A score between 0 and 100, reflecting the overall quality of the response"
2805
- },
2806
- score_justification: {
2807
- type: "string",
2808
- description: "An explanation of the rationale behind the assigned score, considering both accuracy and fluency"
2809
- }
2810
- }
2811
- }
2812
- }
2813
- }
2814
- ]
2815
- };
2816
- if (standard === "wida") {
2817
- const wida_level = {
2818
- type: "number",
2819
- enum: [1, 2, 3, 4, 5, 6],
2820
- description: `The student's WIDA (World-Class Instructional Design and Assessment) proficiency level. Choose one of the following options: 1, 2, 3, 4, 5, 6 which corresponds to
2821
-
2822
- 1 - Entering
2823
- 2 - Emerging
2824
- 3 - Developing
2825
- 4 - Expanding
2826
- 5 - Bridging
2827
- 6 - Reaching
2828
-
2829
- This is an estimate based on the level of the student's response. Use the descriptions of the WIDA speaking standards to guide your decision.
2830
- `
2831
- };
2832
- const wida_justification = {
2833
- type: "string",
2834
- description: `An explanation of the rationale behind the assigned WIDA level of the response, considering both accuracy and fluency. WRITE THIS IN ENGLISH!`
2835
- };
2836
- tool.tools[0].function.parameters.required.push("wida_level");
2837
- tool.tools[0].function.parameters.required.push("wida_justification");
2838
- tool.tools[0].function.parameters.properties.wida_level = wida_level;
2839
- tool.tools[0].function.parameters.properties.wida_justification = wida_justification;
2840
- } else {
2841
- const actfl_level = {
2842
- type: "string",
2843
- enum: ["NL", "NM", "NH", "IL", "IM", "IH", "AL", "AM", "AH", "S", "D"],
2844
- description: "The student's ACTFL (American Council on the Teaching of Foreign Languages) proficiency level. Choose one of the following options: NL, NM, NH, IL, IM, IH, AL, AM, AH, S, or D"
2845
- };
2846
- const actfl_justification = {
2847
- type: "string",
2848
- description: "An explanation of the rationale behind the assigned ACTFL level, considering both accuracy and fluency"
2849
- };
2850
- tool.tools[0].function.parameters.required.push("actfl_level");
2851
- tool.tools[0].function.parameters.required.push("actfl_justification");
2852
- tool.tools[0].function.parameters.properties.actfl_level = actfl_level;
2853
- tool.tools[0].function.parameters.properties.actfl_justification = actfl_justification;
2854
- }
2855
- return tool;
2856
- };
2857
-
2858
- // src/hooks/useActivity.ts
2859
- var import_react3 = require("react");
2860
-
2861
- // src/services/add-grading-standard.ts
2862
- var addGradingStandardLog = async (gradingStandard, userId) => {
2863
- logGradingStandardLog(gradingStandard);
2864
- const path = `users/${userId}/grading_standard_logs`;
2865
- await api.addDoc(path, gradingStandard);
2866
- };
2867
-
2868
- // src/hooks/useActivityTracker.ts
2869
- var import_uuid2 = require("uuid");
2870
- function useActivityTracker({ userId }) {
2871
- const trackActivity = async ({
2872
- activityName,
2873
- activityType,
2874
- id = (0, import_uuid2.v4)(),
2875
- language = ""
2876
- }) => {
2877
- if (userId) {
2878
- const { doc: doc2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = api.accessHelpers();
2879
- const activityRef = doc2(`users/${userId}/activity/${id}`);
2880
- const timestamp = serverTimestamp2();
2881
- await setDoc2(activityRef, {
2882
- name: activityName,
2883
- type: activityType,
2884
- lastSeen: timestamp,
2885
- id,
2886
- language
2887
- });
2888
- }
2889
- };
2890
- return {
2891
- trackActivity
2892
- };
2893
- }
2894
-
2895
- // src/hooks/useActivity.ts
2896
- function useActivity({
2897
- id,
2898
- isAssignment,
2899
- onAssignmentSubmitted,
2900
- ltiData
2901
- }) {
2902
- var _a, _b;
2903
- const { queryClient, user } = useSpeakableApi();
2904
- const userId = user.auth.uid;
2905
- const assignmentQuery = useAssignment({
2906
- assignmentId: id,
2907
- userId,
2908
- enabled: isAssignment
2909
- });
2910
- const activeAssignment = assignmentQuery.data;
2911
- const setId = isAssignment ? (_a = activeAssignment == null ? void 0 : activeAssignment.setId) != null ? _a : "" : id;
2912
- const querySet = useSet({ setId });
2913
- const setData = querySet.data;
2914
- const assignmentContent = activeAssignment == null ? void 0 : activeAssignment.content;
2915
- const assignmentWeights = activeAssignment == null ? void 0 : activeAssignment.weights;
2916
- const setContent = setData == null ? void 0 : setData.content;
2917
- const setWeights = setData == null ? void 0 : setData.weights;
2918
- const contentCardsToUse = isAssignment ? assignmentContent != null ? assignmentContent : setContent : setContent;
2919
- const weightsToUse = isAssignment ? assignmentWeights != null ? assignmentWeights : setWeights : setWeights;
2920
- const activityId = isAssignment ? (_b = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b : "" : setId;
2921
- const { cardsObject, cardsQueries, cards } = useCards({
2922
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2923
- enabled: querySet.isSuccess,
2924
- asObject: true
2925
- });
2926
- const scorableCardIds = (contentCardsToUse != null ? contentCardsToUse : []).filter((cardId) => {
2927
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2928
- return (card == null ? void 0 : card.type) !== "MEDIA_PAGE" /* MEDIA_PAGE */;
2929
- });
2930
- const scoreQuery = useScore({
2931
- isAssignment,
2932
- activityId: id,
2933
- userId,
2934
- courseId: activeAssignment == null ? void 0 : activeAssignment.courseId,
2935
- googleClassroomUserId: user.profile.googleClassroomUserId,
2936
- enabled: isAssignment ? assignmentQuery.isSuccess : querySet.isSuccess
2937
- });
2938
- const { mutationUpdateScore } = useUpdateScore();
2939
- const { mutationUpdateCardScore } = useUpdateCardScore({
2940
- activityId,
2941
- isAssignment,
2942
- userId,
2943
- cardIds: scorableCardIds,
2944
- weights: weightsToUse != null ? weightsToUse : {}
2945
- });
2946
- const { mutationClearScore } = useClearScore();
2947
- const { submitAssignmentScore: submitAssignmentScore2 } = useSubmitAssignmentScore({
2948
- onAssignmentSubmitted,
2949
- studentName: user.profile.displayName
2950
- });
2951
- const { submitPracticeScore: submitPracticeScore2 } = useSubmitPracticeScore();
2952
- const handleUpdateScore = (data) => {
2953
- mutationUpdateScore.mutate({
2954
- data,
2955
- isAssignment,
2956
- activityId,
2957
- userId
2958
- });
2959
- };
2960
- const handleUpdateCardScore = (cardId, cardScore) => {
2961
- mutationUpdateCardScore.mutate({ cardId, cardScore });
2962
- if (cardScore.proficiency_level) {
2963
- logGradingStandardEntry({
2964
- type: cardScore.proficiency_level.standardId,
2965
- cardId,
2966
- gradingStandard: cardScore.proficiency_level
2967
- });
2968
- } else if (cardScore.wida || cardScore.actfl) {
2969
- logGradingStandardEntry({
2970
- type: cardScore.wida ? "wida" : "actfl",
2971
- cardId,
2972
- gradingStandard: cardScore.wida || cardScore.actfl || { level: "", justification: "" }
2973
- });
2974
- }
2975
- };
2976
- const onClearScore = ({
2977
- cardId,
2978
- wasCompleted = true
2979
- }) => {
2980
- var _a2, _b2;
2981
- const currentCard = cardsObject == null ? void 0 : cardsObject[cardId];
2982
- if ((currentCard == null ? void 0 : currentCard.type) === "MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */ || (currentCard == null ? void 0 : currentCard.type) === "READ_REPEAT" /* READ_REPEAT */) {
2983
- return;
2984
- }
2985
- const queryKeys = scoreQueryKeys.byId(activityId);
2986
- const activeCardScores = (_b2 = (_a2 = queryClient.getQueryData(queryKeys)) == null ? void 0 : _a2.cards) == null ? void 0 : _b2[cardId];
2987
- if (activeCardScores === void 0) return;
2988
- mutationClearScore.mutate({
2989
- isAssignment,
2990
- activityId,
2991
- cardScores: activeCardScores,
2992
- cardId,
2993
- userId
2994
- });
2995
- };
2996
- const onSubmitScore = async () => {
2997
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2998
- try {
2999
- let results;
3000
- if (isAssignment) {
3001
- const someCardIsManualGraded = cards.some((page) => page.grading_method === "manual");
3002
- results = await submitAssignmentScore2({
3003
- assignment: {
3004
- id: (_b2 = (_a2 = assignmentQuery.data) == null ? void 0 : _a2.id) != null ? _b2 : "",
3005
- name: (_d = (_c = assignmentQuery.data) == null ? void 0 : _c.name) != null ? _d : "",
3006
- owners: (_f = (_e = assignmentQuery.data) == null ? void 0 : _e.owners) != null ? _f : [],
3007
- courseId: (_h = (_g = assignmentQuery.data) == null ? void 0 : _g.courseId) != null ? _h : "",
3008
- courseWorkId: (_j = (_i = assignmentQuery.data) == null ? void 0 : _i.courseWorkId) != null ? _j : "",
3009
- isAssessment: (_l = (_k = assignmentQuery.data) == null ? void 0 : _k.isAssessment) != null ? _l : false,
3010
- maxPoints: (_n = (_m = assignmentQuery.data) == null ? void 0 : _m.maxPoints) != null ? _n : 0
3011
- },
3012
- userId,
3013
- scores: scoreQuery.data,
3014
- status: someCardIsManualGraded ? "PENDING_REVIEW" : "SUBMITTED"
3015
- });
3016
- if ((_o = assignmentQuery.data) == null ? void 0 : _o.ltiDeeplink) {
3017
- submitLTIScore({
3018
- maxPoints: (_p = assignmentQuery.data) == null ? void 0 : _p.maxPoints,
3019
- score: (_r = (_q = scoreQuery.data) == null ? void 0 : _q.score) != null ? _r : 0,
3020
- SERVICE_KEY: (_s = ltiData == null ? void 0 : ltiData.serviceKey) != null ? _s : "",
3021
- lineItemId: (_t = ltiData == null ? void 0 : ltiData.lineItemId) != null ? _t : "",
3022
- lti_id: (_u = ltiData == null ? void 0 : ltiData.lti_id) != null ? _u : ""
3023
- });
3024
- }
3025
- } else {
3026
- results = await submitPracticeScore2({
3027
- setId: (_w = (_v = querySet.data) == null ? void 0 : _v.id) != null ? _w : "",
3028
- userId,
3029
- scores: scoreQuery.data
3030
- });
3031
- }
3032
- return results;
3033
- } catch (error) {
3034
- return {
3035
- success: false,
3036
- error
3037
- };
3038
- }
3039
- };
3040
- const logGradingStandardEntry = ({
3041
- cardId,
3042
- gradingStandard,
3043
- type
3044
- }) => {
3045
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
3046
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
3047
- const scoresObject = queryClient.getQueryData(scoreQueryKeys.byId(activityId));
3048
- const cardScore = (_a2 = scoresObject == null ? void 0 : scoresObject.cards) == null ? void 0 : _a2[cardId];
3049
- const serverTimestamp2 = api.helpers.serverTimestamp;
3050
- addGradingStandardLog(
3051
- {
3052
- assignmentId: (_b2 = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b2 : "",
3053
- courseId: (_c = activeAssignment == null ? void 0 : activeAssignment.courseId) != null ? _c : "",
3054
- teacherId: (_d = activeAssignment == null ? void 0 : activeAssignment.owners[0]) != null ? _d : "",
3055
- setId: (_e = setData == null ? void 0 : setData.id) != null ? _e : "",
3056
- cardId,
3057
- level: gradingStandard.level,
3058
- justification: gradingStandard.justification,
3059
- transcript: (_f = cardScore == null ? void 0 : cardScore.transcript) != null ? _f : "",
3060
- audioUrl: (_g = cardScore == null ? void 0 : cardScore.audio) != null ? _g : "",
3061
- prompt: (_h = card == null ? void 0 : card.prompt) != null ? _h : "",
3062
- responseType: (card == null ? void 0 : card.type) === "RESPOND_WRITE" /* RESPOND_WRITE */ ? "written" : "spoken",
3063
- type,
3064
- dateMade: serverTimestamp2(),
3065
- language: (_i = card == null ? void 0 : card.language) != null ? _i : ""
3066
- },
3067
- userId
3068
- );
3069
- };
3070
- (0, import_react3.useEffect)(() => {
3071
- if (isAssignment) {
3072
- logOpenAssignment({ assignmentId: id });
3073
- } else {
3074
- logOpenActivityPreview({ setId: id });
3075
- }
3076
- }, []);
3077
- useInitActivity({
3078
- assignment: activeAssignment != null ? activeAssignment : void 0,
3079
- set: setData != null ? setData : void 0,
3080
- enabled: !!setData,
3081
- userId
3082
- });
3083
- return {
3084
- set: {
3085
- data: setData,
3086
- query: querySet
3087
- },
3088
- cards: {
3089
- data: cardsObject,
3090
- query: cardsQueries,
3091
- cardsArray: cards
3092
- },
3093
- assignment: {
3094
- data: isAssignment ? activeAssignment : void 0,
3095
- query: assignmentQuery
3096
- },
3097
- scores: {
3098
- data: scoreQuery.data,
3099
- query: scoreQuery,
3100
- actions: {
3101
- update: handleUpdateScore,
3102
- clear: onClearScore,
3103
- submit: onSubmitScore,
3104
- updateCard: handleUpdateCardScore,
3105
- logGradingStandardEntry
3106
- }
3107
- }
3108
- };
3109
- }
3110
- var useInitActivity = ({
3111
- assignment,
3112
- set,
3113
- enabled,
3114
- userId
3115
- }) => {
3116
- const { trackActivity } = useActivityTracker({ userId });
3117
- const init = () => {
3118
- var _a, _b, _c, _d, _e, _f, _g;
3119
- if (!enabled) return;
3120
- if (!assignment) {
3121
- trackActivity({
3122
- activityName: (_a = set == null ? void 0 : set.name) != null ? _a : "",
3123
- activityType: "set",
3124
- id: set == null ? void 0 : set.id,
3125
- language: set == null ? void 0 : set.language
3126
- });
3127
- } else if (assignment.name) {
3128
- trackActivity({
3129
- activityName: assignment.name,
3130
- activityType: assignment.isAssessment ? "assessment" : "assignment",
3131
- id: assignment.id,
3132
- language: set == null ? void 0 : set.language
3133
- });
3134
- }
3135
- if (set == null ? void 0 : set.public) {
3136
- (_d = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "onSetOpened")) == null ? void 0 : _d({
3137
- setId: set.id,
3138
- language: set.language
3139
- });
3140
- }
3141
- (_g = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "updateAlgoliaIndex")) == null ? void 0 : _g({
3142
- updatePlays: true,
3143
- objectID: set == null ? void 0 : set.id
3144
- });
3145
- };
3146
- (0, import_react3.useEffect)(() => {
3147
- init();
3148
- }, [set]);
3149
- };
3150
- var submitLTIScore = async ({
3151
- maxPoints,
3152
- score,
3153
- SERVICE_KEY,
3154
- lineItemId,
3155
- lti_id
3156
- }) => {
3157
- var _a, _b, _c;
3158
- try {
3159
- if (!SERVICE_KEY || !lineItemId || !lti_id) {
3160
- throw new Error("Missing required LTI credentials");
3161
- }
3162
- const earnedPoints = score ? score / 100 * maxPoints : 0;
3163
- const { data } = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitLTIAssignmentScore")) == null ? void 0 : _c({
3164
- SERVICE_KEY,
3165
- scoreData: {
3166
- lineItemId,
3167
- userId: lti_id,
3168
- maxPoints,
3169
- earnedPoints
3170
- }
3171
- }));
3172
- return { success: true, data };
3173
- } catch (error) {
3174
- console.error("Failed to submit LTI score:", error);
3175
- return {
3176
- success: false,
3177
- error: error instanceof Error ? error : new Error("Unknown error occurred")
3178
- };
3179
- }
3180
- };
3181
-
3182
- // src/hooks/useCredits.ts
3183
- var import_react_query5 = require("@tanstack/react-query");
3184
- var creditQueryKeys = {
3185
- userCredits: (uid) => ["userCredits", uid]
3186
- };
3187
- var useUserCredits = () => {
3188
- const { user } = useSpeakableApi();
3189
- const email = user.auth.email;
3190
- const uid = user.auth.uid;
3191
- const query2 = (0, import_react_query5.useQuery)({
3192
- queryKey: creditQueryKeys.userCredits(uid),
3193
- queryFn: () => fetchUserCredits({ uid, email }),
3194
- enabled: !!uid,
3195
- refetchInterval: 1e3 * 60 * 5
3196
- });
3197
- return {
3198
- ...query2
3199
- };
3200
- };
3201
- var fetchUserCredits = async ({ uid, email }) => {
3202
- if (!uid) {
3203
- throw new Error("User ID is required");
3204
- }
3205
- const contractSnap = await api.getDoc(`creditContracts/${uid}`);
3206
- if (contractSnap.data == null) {
3207
- return {
3208
- id: uid,
3209
- userId: uid,
3210
- email,
3211
- effectivePlanId: "free_tier",
3212
- status: "inactive",
3213
- isUnlimited: false,
3214
- creditsAvailable: 100,
3215
- creditsAllocatedThisPeriod: 100,
3216
- topOffCreditsAvailable: 0,
3217
- topOffCreditsTotal: 0,
3218
- allocationSource: "free_tier",
3219
- sourceDetails: {},
3220
- periodStart: null,
3221
- periodEnd: null,
3222
- planTermEndTimestamp: null,
3223
- ownerType: "individual",
3224
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3225
- lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
3226
- };
3227
- }
3228
- const contractData = contractSnap.data;
3229
- const monthlyCredits = (contractData == null ? void 0 : contractData.creditsAvailable) || 0;
3230
- const topOffCredits = (contractData == null ? void 0 : contractData.topOffCreditsAvailable) || 0;
3231
- const totalCredits = monthlyCredits + topOffCredits;
3232
- return {
3233
- id: contractSnap.id,
3234
- ...contractData,
3235
- // Add computed total for convenience
3236
- totalCreditsAvailable: totalCredits
3237
- };
3238
- };
3239
-
3240
- // src/hooks/useOrganizationAccess.ts
3241
- var import_react_query6 = require("@tanstack/react-query");
3242
- var useOrganizationAccess = () => {
3243
- const { user } = useSpeakableApi();
3244
- const email = user.auth.email;
3245
- const query2 = (0, import_react_query6.useQuery)({
3246
- queryKey: ["organizationAccess", email],
3247
- queryFn: async () => {
3248
- if (!email) {
3249
- return {
3250
- hasUnlimitedAccess: false,
3251
- subscriptionId: null,
3252
- organizationId: null,
3253
- organizationName: null,
3254
- subscriptionEndDate: null,
3255
- accessType: "individual"
3256
- };
3257
- }
3258
- return getOrganizationAccess(email);
3259
- },
3260
- enabled: !!email,
3261
- // Only run query if we have a user email
3262
- staleTime: 5 * 60 * 1e3,
3263
- // Consider data fresh for 5 minutes
3264
- gcTime: 10 * 60 * 1e3,
3265
- // Keep in cache for 10 minutes
3266
- retry: 2
3267
- // Retry failed requests twice
3268
- });
3269
- return {
3270
- ...query2
3271
- };
3272
- };
3273
- var getOrganizationAccess = async (email) => {
3274
- const { limit: limit2, where: where2 } = api.accessQueryConstraints();
3275
- try {
3276
- const organizationSnapshot = await api.getDocs(
3277
- "organizations",
3278
- where2("members", "array-contains", email),
3279
- where2("masterSubscriptionStatus", "==", "active"),
3280
- limit2(1)
3281
- );
3282
- if (!organizationSnapshot.empty) {
3283
- const orgData = organizationSnapshot.data[0];
3284
- return {
3285
- hasUnlimitedAccess: true,
3286
- subscriptionId: orgData == null ? void 0 : orgData.masterSubscriptionId,
3287
- organizationId: orgData.id,
3288
- organizationName: orgData.name || "Unknown Organization",
3289
- subscriptionEndDate: orgData.masterSubscriptionEndDate || null,
3290
- accessType: "organization"
3291
- };
3292
- }
3293
- const institutionSnapshot = await api.getDocs(
3294
- "institution_subscriptions",
3295
- where2("users", "array-contains", email),
3296
- where2("active", "==", true),
3297
- limit2(1)
3298
- );
3299
- if (!institutionSnapshot.empty) {
3300
- const institutionData = institutionSnapshot.data[0];
3301
- const isUnlimited = (institutionData == null ? void 0 : institutionData.plan) === "organization" || (institutionData == null ? void 0 : institutionData.plan) === "school_starter";
3302
- return {
3303
- hasUnlimitedAccess: isUnlimited,
3304
- subscriptionId: institutionData.id,
3305
- organizationId: institutionData == null ? void 0 : institutionData.institutionId,
3306
- organizationName: institutionData.name || institutionData.institutionId || "Legacy Institution",
3307
- subscriptionEndDate: institutionData.endDate || null,
3308
- accessType: "institution_subscriptions"
3309
- };
3310
- }
3311
- return {
3312
- hasUnlimitedAccess: false,
3313
- subscriptionId: null,
3314
- organizationId: null,
3315
- organizationName: null,
3316
- subscriptionEndDate: null,
3317
- accessType: "individual"
3318
- };
3319
- } catch (error) {
3320
- console.error("Error checking organization access:", error);
3321
- return {
3322
- hasUnlimitedAccess: false,
3323
- subscriptionId: null,
3324
- organizationId: null,
3325
- organizationName: null,
3326
- subscriptionEndDate: null,
3327
- accessType: "individual"
3328
- };
3329
- }
3330
- };
3331
-
3332
- // src/hooks/useSpeakableTranscript.ts
3333
- var import_react_query7 = require("@tanstack/react-query");
3334
- function useSpeakableTranscript() {
3335
- const mutation = (0, import_react_query7.useMutation)({
3336
- mutationFn: async ({
3337
- model,
3338
- audioUrl,
3339
- language,
3340
- prompt
3341
- }) => {
3342
- return getTranscript(model, { audioUrl, language, prompt });
3343
- },
3344
- retry: false
3345
- });
3346
- return {
3347
- mutation
3348
- };
3349
- }
3350
- function useSpeakableTranscriptCycle() {
3351
- const mutation = (0, import_react_query7.useMutation)({
3352
- mutationFn: async (args) => {
3353
- return getTranscriptCycle(args);
3354
- },
3355
- retry: false
3356
- });
3357
- return {
3358
- mutationTranscriptCycle: mutation
3359
- };
3360
- }
3361
-
3362
- // src/hooks/useUpdateStudentVoc.ts
3363
- var useUpdateStudentVocab = (page) => {
3364
- const { user } = useSpeakableApi();
3365
- const currentUserId = user == null ? void 0 : user.auth.uid;
3366
- if (!page || !currentUserId || !page.target_text || !page.language) {
3367
- return {
3368
- studentVocabMarkVoiceSuccess: void 0,
3369
- studentVocabMarkVoiceFail: void 0
3370
- };
3371
- }
3372
- const getDataObject = () => {
3373
- var _a, _b;
3374
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3375
- const language = (_a = page.language) != null ? _a : "en";
3376
- const word = (_b = page.target_text) != null ? _b : "";
3377
- const phrase_length = getPhraseLength(word);
3378
- const wordHash = getWordHash(word, language);
3379
- const docPath = `users/${currentUserId}/vocab/${wordHash}`;
3380
- const communityPath = `checked-pronunciations/${wordHash}`;
3381
- const id = `${language}-${cleanString(word)}`;
3382
- const data = {
3383
- id,
3384
- word,
3385
- words: (word == null ? void 0 : word.split(" ")) || [],
3386
- wordHash,
3387
- language,
3388
- lastSeen: serverTimestamp2(),
3389
- phrase_length
3390
- };
3391
- return {
3392
- docPath,
3393
- communityPath,
3394
- data
3395
- };
3396
- };
3397
- const markVoiceSuccess = async () => {
3398
- const { docPath, communityPath, data } = getDataObject();
3399
- const { increment: increment2 } = api.accessQueryConstraints();
3400
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3401
- data.voiceSuccess = increment2(1);
3402
- try {
3403
- await api.updateDoc(docPath, data);
3404
- } catch (error) {
3405
- if (error instanceof Error && "code" in error) {
3406
- const firebaseError = error;
3407
- if (firebaseError.code === "not-found") {
3408
- data.firstSeen = serverTimestamp2();
3409
- await api.setDoc(docPath, data, { merge: true });
3410
- } else {
3411
- console.error("Error actualizando vocabulario:", error);
3412
- }
3413
- } else {
3414
- console.error("Error desconocido:", error);
3415
- }
3416
- }
3417
- try {
3418
- data.pronunciations = increment2(1);
3419
- await api.setDoc(communityPath, data, { merge: true });
3420
- } catch (error) {
3421
- console.log(error);
3422
- }
3423
- };
3424
- const markVoiceFail = async () => {
3425
- const { docPath, communityPath, data } = getDataObject();
3426
- const { increment: increment2 } = api.accessQueryConstraints();
3427
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3428
- data.voiceFail = increment2(1);
3429
- try {
3430
- await api.updateDoc(docPath, data);
3431
- } catch (error) {
3432
- if (error instanceof Error && error.message === "not-found") {
3433
- data.firstSeen = serverTimestamp2();
3434
- await api.setDoc(docPath, data, { merge: true });
3435
- } else {
3436
- console.log(error);
3437
- }
3438
- }
3439
- try {
3440
- data.fails = increment2(1);
3441
- await api.setDoc(communityPath, data, { merge: true });
3442
- } catch (error) {
3443
- console.log(error);
3444
- }
3445
- };
3446
- return {
3447
- studentVocabMarkVoiceSuccess: markVoiceSuccess,
3448
- studentVocabMarkVoiceFail: markVoiceFail
3449
- };
3450
- };
3451
-
3452
- // src/hooks/useActivityFeedbackAccess.ts
3453
- var import_react_query8 = require("@tanstack/react-query");
3454
- var activityFeedbackAccessQueryKeys = {
3455
- activityFeedbackAccess: (args) => ["activityFeedbackAccess", ...Object.values(args)]
3456
- };
3457
- var useActivityFeedbackAccess = ({
3458
- aiEnabled = false,
3459
- isActivityRoute = false
3460
- }) => {
3461
- var _a, _b, _c;
3462
- const { user } = useSpeakableApi();
3463
- const uid = user.auth.uid;
3464
- const isTeacher = (_a = user.profile) == null ? void 0 : _a.isTeacher;
3465
- const isStudent = (_b = user.profile) == null ? void 0 : _b.isStudent;
3466
- const userRoles = ((_c = user.profile) == null ? void 0 : _c.roles) || [];
3467
- const query2 = (0, import_react_query8.useQuery)({
3468
- queryKey: activityFeedbackAccessQueryKeys.activityFeedbackAccess({
3469
- aiEnabled,
3470
- isActivityRoute
3471
- }),
3472
- queryFn: async () => {
3473
- var _a2, _b2, _c2;
3474
- if (!uid) {
3475
- return {
3476
- canAccessFeedback: false,
3477
- reason: "Missing user ID",
3478
- isUnlimited: false,
3479
- accessType: "none"
3480
- };
3481
- }
3482
- try {
3483
- if (aiEnabled) {
3484
- return {
3485
- canAccessFeedback: true,
3486
- reason: "AI feedback enabled",
3487
- isUnlimited: true,
3488
- accessType: "ai_enabled"
3489
- };
3490
- }
3491
- if (isTeacher || userRoles.includes("ADMIN")) {
3492
- return {
3493
- canAccessFeedback: true,
3494
- reason: "Teacher preview access",
3495
- isUnlimited: true,
3496
- accessType: "teacher_preview"
3497
- };
3498
- }
3499
- if (isStudent && isActivityRoute) {
3500
- try {
3501
- const result = await ((_c2 = (_b2 = (_a2 = api).httpsCallable) == null ? void 0 : _b2.call(_a2, "checkStudentTeacherPlan")) == null ? void 0 : _c2({
3502
- studentId: uid
3503
- }));
3504
- const planCheckResult = result.data;
3505
- if (planCheckResult.canAccessFeedback) {
3506
- return {
3507
- canAccessFeedback: true,
3508
- reason: planCheckResult.reason || "Student access via teacher with active plan",
3509
- isUnlimited: planCheckResult.hasTeacherWithUnlimitedAccess,
3510
- accessType: "student_with_teacher_plan"
3511
- };
3512
- } else {
3513
- return {
3514
- canAccessFeedback: false,
3515
- reason: planCheckResult.reason || "No teacher with active plan found",
3516
- isUnlimited: false,
3517
- accessType: "none"
3518
- };
3519
- }
3520
- } catch (error) {
3521
- console.error("Error checking student teacher plan:", error);
3522
- return {
3523
- canAccessFeedback: false,
3524
- reason: "Error checking teacher plans",
3525
- isUnlimited: false,
3526
- accessType: "none"
3527
- };
3528
- }
3529
- }
3530
- return {
3531
- canAccessFeedback: false,
3532
- reason: "No access permissions found for current context",
3533
- isUnlimited: false,
3534
- accessType: "none"
3535
- };
3536
- } catch (error) {
3537
- console.error("Error checking activity feedback access:", error);
3538
- return {
3539
- canAccessFeedback: false,
3540
- reason: "Error checking access permissions",
3541
- isUnlimited: false,
3542
- accessType: "none"
3543
- };
3544
- }
3545
- },
3546
- enabled: !!uid,
3547
- staleTime: 5 * 60 * 1e3,
3548
- // 5 minutes
3549
- gcTime: 10 * 60 * 1e3
3550
- // 10 minutes
3551
- });
3552
- return {
3553
- ...query2
3554
- };
3555
- };
3556
-
3557
- // src/hooks/useOpenAI.ts
3558
- var useBaseOpenAI = ({
3559
- onTranscriptSuccess,
3560
- onTranscriptError,
3561
- onCompletionSuccess,
3562
- onCompletionError,
3563
- aiEnabled,
3564
- submitAudioResponse,
3565
- uploadAudioAndGetTranscript,
3566
- onGetAudioUrlAndTranscript
3567
- }) => {
3568
- const { user, queryClient } = useSpeakableApi();
3569
- const currentUserId = user.auth.uid;
3570
- const { data: feedbackAccess } = useActivityFeedbackAccess({
3571
- aiEnabled
3572
- });
3573
- const getTranscript2 = async (audioUrl, language, prompt) => {
3574
- var _a, _b, _c, _d, _e, _f;
3575
- const getGeminiTranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getGeminiTranscript");
3576
- const getAssemblyAITranscript = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "transcribeAssemblyAIAudio");
3577
- const getWhisperTranscript = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "transcribeAudio");
3578
- try {
3579
- const { data } = await (getWhisperTranscript == null ? void 0 : getWhisperTranscript({
3580
- audioUrl,
3581
- language
3582
- }));
3583
- const transcript = data;
3584
- if (transcript) {
3585
- return transcript;
3586
- }
3587
- } catch (error) {
3588
- console.log("Whisper transcript failed, trying Gemini fallback:", error);
3589
- }
3590
- try {
3591
- const { data } = await (getGeminiTranscript == null ? void 0 : getGeminiTranscript({
3592
- audioUrl,
3593
- targetLanguage: language,
3594
- prompt: prompt || ""
3595
- }));
3596
- const transcript = data.transcript;
3597
- if (transcript) {
3598
- return transcript;
3599
- }
3600
- } catch (error) {
3601
- console.log("Gemini transcript failed, trying AssemblyAI fallback:", error);
3602
- }
3603
- try {
3604
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
3605
- audioUrl,
3606
- language
3607
- }));
3608
- const transcript = response == null ? void 0 : response.data;
3609
- if (transcript) {
3610
- return transcript;
3611
- }
3612
- throw new Error("Both transcript services failed");
3613
- } catch (error) {
3614
- console.log("AssemblyAI transcript also failed:", error);
3615
- onTranscriptError({
3616
- type: "TRANSCRIPT",
3617
- message: (error == null ? void 0 : error.message) || "Error getting transcript from both services"
3618
- });
3619
- throw new Error(error);
3620
- }
3621
- };
3622
- const getFreeResponseCompletion = async (messages, isFreeResponse, feedbackLanguage, gradingStandard = "actfl") => {
3623
- var _a, _b, _c, _d, _e;
3624
- const responseTool = getRespondCardTool({
3625
- language: feedbackLanguage,
3626
- standard: gradingStandard
3627
- });
3628
- try {
3629
- const createChatCompletion = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createChatCompletion");
3630
- const {
3631
- data: {
3632
- response,
3633
- prompt_tokens = 0,
3634
- completion_tokens = 0,
3635
- success: aiSuccess = false
3636
- // the AI was able to generate a response
3637
- }
3638
- } = await (createChatCompletion == null ? void 0 : createChatCompletion({
3639
- chat: {
3640
- model: isFreeResponse ? "gpt-4-1106-preview" : "gpt-3.5-turbo-1106",
3641
- messages,
3642
- temperature: 0.7,
3643
- ...responseTool
3644
- },
3645
- type: isFreeResponse ? "LONG_RESPONSE" : "SHORT_RESPONSE"
3646
- }));
3647
- const functionArguments = JSON.parse(((_e = (_d = (_c = response == null ? void 0 : response.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.arguments) || "{}");
3648
- const result = {
3649
- ...functionArguments,
3650
- prompt_tokens,
3651
- completion_tokens,
3652
- aiSuccess
3653
- };
3654
- onCompletionSuccess(result);
3655
- return result;
3656
- } catch (error) {
3657
- onCompletionError({
3658
- type: "COMPLETION",
3659
- message: (error == null ? void 0 : error.message) || "Error getting completion"
3660
- });
3661
- throw new Error(error);
3662
- }
3663
- };
3664
- const getFeedback = async ({
3665
- cardId,
3666
- language = "en",
3667
- // required
3668
- writtenResponse = null,
3669
- // if the type = RESPOND_WRITE
3670
- audio = null,
3671
- autoGrade = true,
3672
- file = null,
3673
- pagePrompt = null
3674
- }) => {
3675
- try {
3676
- if (!(feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback)) {
3677
- const result = {
3678
- noFeedbackAvailable: true,
3679
- success: true,
3680
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3681
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3682
- };
3683
- onCompletionSuccess(result);
3684
- return result;
3685
- }
3686
- let transcript;
3687
- let audioUrl = void 0;
3688
- if (writtenResponse) {
3689
- transcript = writtenResponse;
3690
- onTranscriptSuccess(writtenResponse);
3691
- } else if (typeof audio === "string" && file) {
3692
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3693
- transcript = await getTranscript2(audio, language, pagePrompt != null ? pagePrompt : "");
3694
- audioUrl = audio;
3695
- onTranscriptSuccess(transcript);
3696
- } else {
3697
- console.info(
3698
- `Transcript not available: ${(feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access"}`
3699
- );
3700
- }
3701
- } else {
3702
- const response = await uploadAudioAndGetTranscript(audio || "", language, pagePrompt != null ? pagePrompt : "");
3703
- transcript = response.transcript;
3704
- audioUrl = response.audioUrl;
3705
- }
3706
- onGetAudioUrlAndTranscript == null ? void 0 : onGetAudioUrlAndTranscript({ transcript, audioUrl });
3707
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3708
- const results = await getAIResponse({
3709
- cardId,
3710
- transcript: transcript || ""
3711
- });
3712
- let output = results;
3713
- if (!autoGrade) {
3714
- output = {
3715
- ...output,
3716
- noFeedbackAvailable: true,
3717
- success: true
3718
- };
3719
- }
3720
- onCompletionSuccess(output);
3721
- return output;
3722
- } else {
3723
- const result = {
3724
- noFeedbackAvailable: true,
3725
- success: true,
3726
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3727
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3728
- };
3729
- onCompletionSuccess(result);
3730
- return result;
3731
- }
3732
- } catch (error) {
3733
- console.error("Error getting feedback:", error);
3734
- throw new Error(error);
3735
- }
3736
- };
3737
- const onGetGeminiFeedback = async ({
3738
- cardId,
3739
- studentId,
3740
- studentResponse
3741
- }) => {
3742
- var _a, _b;
3743
- try {
3744
- const getGeminiFeedback = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "callGetFeedback");
3745
- return await (getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3746
- cardId,
3747
- studentId,
3748
- studentResponse
3749
- }));
3750
- } catch (error) {
3751
- console.error("Error getting Gemini feedback:", error);
3752
- throw error;
3753
- }
3754
- };
3755
- const onGetProficiencyEstimate = async ({
3756
- cardId,
3757
- studentId,
3758
- studentResponse
3759
- }) => {
3760
- var _a, _b;
3761
- try {
3762
- const getProficiencyEstimate = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getProficiencyEstimate");
3763
- return await (getProficiencyEstimate == null ? void 0 : getProficiencyEstimate({
3764
- cardId,
3765
- studentId,
3766
- studentResponse
3767
- }));
3768
- } catch (error) {
3769
- console.error("Error getting proficiency estimate:", error);
3770
- return {};
3771
- }
3772
- };
3773
- const getAIResponse = async ({ cardId, transcript }) => {
3774
- var _a;
3775
- try {
3776
- const card = getCardFromCache({
3777
- cardId,
3778
- queryClient
3779
- });
3780
- let feedbackData;
3781
- let proficiencyData = {};
3782
- if (card && card.grading_method === "manual") {
3783
- } else if (card && card.grading_method !== "standards_based") {
3784
- const [geminiResult, proficiencyResult] = await Promise.all([
3785
- onGetGeminiFeedback == null ? void 0 : onGetGeminiFeedback({
3786
- cardId,
3787
- studentId: currentUserId,
3788
- studentResponse: transcript
3789
- }),
3790
- onGetProficiencyEstimate == null ? void 0 : onGetProficiencyEstimate({
3791
- cardId,
3792
- studentId: currentUserId,
3793
- studentResponse: transcript
3794
- })
3795
- ]);
3796
- proficiencyData = (proficiencyResult == null ? void 0 : proficiencyResult.data) || {};
3797
- feedbackData = {
3798
- ...(_a = geminiResult == null ? void 0 : geminiResult.data) != null ? _a : {},
3799
- // @ts-ignore
3800
- proficiency_level: (proficiencyData == null ? void 0 : proficiencyData.proficiency_level) || null
3801
- };
3802
- } else {
3803
- const geminiResult = await (onGetGeminiFeedback == null ? void 0 : onGetGeminiFeedback({
3804
- cardId,
3805
- studentId: currentUserId,
3806
- studentResponse: transcript
3807
- }));
3808
- feedbackData = geminiResult == null ? void 0 : geminiResult.data;
3809
- }
3810
- const results = {
3811
- ...proficiencyData,
3812
- ...feedbackData,
3813
- aiSuccess: true,
3814
- promptSuccess: (feedbackData == null ? void 0 : feedbackData.success) || false,
3815
- transcript
3816
- };
3817
- return results;
3818
- } catch (error) {
3819
- onCompletionError({
3820
- type: "AI_FEEDBACK",
3821
- message: (error == null ? void 0 : error.message) || "Error getting ai feedback"
3822
- });
3823
- throw new Error(error);
3824
- }
3825
- };
3826
- return {
3827
- submitAudioResponse,
3828
- uploadAudioAndGetTranscript,
3829
- getTranscript: getTranscript2,
3830
- getFreeResponseCompletion,
3831
- getFeedback
3832
- };
3833
- };
3834
-
3835
- // src/lib/create-firebase-client-native.ts
3836
- var import_firestore = require("@react-native-firebase/firestore");
3837
-
3838
- // src/lib/create-firebase-client.ts
3839
- function createFsClientBase({
3840
- db,
3841
- helpers,
3842
- httpsCallable,
3843
- logEvent
3844
- }) {
3845
- const dbAsFirestore = db;
3846
- api.initialize({
3847
- db: dbAsFirestore,
3848
- helpers,
3849
- httpsCallable,
3850
- logEvent
3851
- });
3852
- return {
3853
- assignmentRepo: createAssignmentRepo(),
3854
- cardRepo: createCardRepo()
3855
- };
3856
- }
3857
-
3858
- // src/lib/create-firebase-client-native.ts
3859
- var createFsClientNative = ({ db, httpsCallable, logEvent }) => {
3860
- return createFsClientBase({
3861
- db,
3862
- httpsCallable,
3863
- logEvent,
3864
- helpers: {
3865
- getDoc: import_firestore.getDoc,
3866
- getDocs: import_firestore.getDocs,
3867
- addDoc: import_firestore.addDoc,
3868
- setDoc: import_firestore.setDoc,
3869
- updateDoc: import_firestore.updateDoc,
3870
- deleteDoc: import_firestore.deleteDoc,
3871
- runTransaction: import_firestore.runTransaction,
3872
- writeBatch: import_firestore.writeBatch,
3873
- doc: import_firestore.doc,
3874
- collection: import_firestore.collection,
3875
- query: import_firestore.query,
3876
- serverTimestamp: import_firestore.serverTimestamp,
3877
- orderBy: import_firestore.orderBy,
3878
- limit: import_firestore.limit,
3879
- startAt: import_firestore.startAt,
3880
- startAfter: import_firestore.startAfter,
3881
- endAt: import_firestore.endAt,
3882
- endBefore: import_firestore.endBefore,
3883
- where: import_firestore.where,
3884
- increment: import_firestore.increment
3885
- }
3886
- });
3887
- };
3888
- //# sourceMappingURL=index.native.js.map