@vue-skuilder/standalone-ui 0.2.25 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.html CHANGED
@@ -9,13 +9,13 @@
9
9
  href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"
10
10
  rel="stylesheet"
11
11
  />
12
- <script type="module" crossorigin src="/assets/index-CaEqsGHM.js"></script>
12
+ <script type="module" crossorigin src="/assets/index-CqzX3x60.js"></script>
13
13
  <link rel="modulepreload" crossorigin href="/assets/dist-Br-kAMD_.js">
14
- <link rel="modulepreload" crossorigin href="/assets/dist-WIuWwzvM.js">
14
+ <link rel="modulepreload" crossorigin href="/assets/dist-D76mAUOD.js">
15
15
  <link rel="modulepreload" crossorigin href="/assets/MarkdownRenderer-kStoDRNE-CPe75lAF.js">
16
- <link rel="modulepreload" crossorigin href="/assets/common-ui.es-Z1FQmTU4.js">
16
+ <link rel="modulepreload" crossorigin href="/assets/common-ui.es-Cac9w3pR.js">
17
17
  <link rel="stylesheet" crossorigin href="/assets/common-ui-BY2Ut5jf.css">
18
- <link rel="stylesheet" crossorigin href="/assets/index-CAj8AHaU.css">
18
+ <link rel="stylesheet" crossorigin href="/assets/index-Ci9rmWrX.css">
19
19
  </head>
20
20
  <body>
21
21
  <div id="app"></div>
@@ -362,7 +362,7 @@ ${g.rows.map(t=>` ${t.id}-${t.key}
362
362
  `+C),S}async getCourseConfig(){let t=await getCredentialledCourseConfig(this.id);if(t)return t;throw Error(`Course config not found for course ID: ${this.id}`)}async updateCourseConfig(t){logger.debug(`Updating: ${JSON.stringify(t)}`);try{return await updateCredentialledCourseConfig(this.id,t)}catch(t){throw logger.error(`Error updating course config in course DB: ${t}`),t}}async updateCardElo(t,c){if(!c)throw Error(`Cannot update card elo with null or undefined value for card ID: ${t}`);try{return{ok:!0,id:t,rev:(await this.updateQueue.update(t,t=>(logger.debug(`Replacing ${JSON.stringify(t.elo)} with ${JSON.stringify(c)}`),t.elo=c,t)))._rev}}catch(c){throw logger.error(`Failed to update card elo for card ID: ${t}`,c),Error(`Failed to update card elo for card ID: ${t}`)}}async getAppliedTags(t){let c=await getAppliedTags(this.id,t);if(c)return c;throw Error(`Failed to find tags for card ${this.id}-${t}`)}async getAppliedTagsBatch(t){if(t.length===0)return new Map;let c=await this.db.query(`getTags`,{keys:t,include_docs:!1}),u=new Map;for(let c of t)u.set(c,[]);for(let t of c.rows){let c=t.key,d=t.value?.name;d&&u.has(c)&&u.get(c).push(d)}return u}async getAllCardIds(){let t=`${DocTypePrefixes.CARD}-`;return(await this.db.allDocs({startkey:t,endkey:`${t}\uFFF0`,include_docs:!1})).rows.map(t=>t.id)}async addTagToCard(t,c,u){return await addTagToCard(this.id,t,c,(await this._getCurrentUser()).getUsername(),u)}async removeTagFromCard(t,c){return await removeTagFromCard(this.id,t,c)}async createTag(t,c){return await createTag(this.id,t,c)}async getTag(t){return await getTag(this.id,t)}async updateTag(t){if(t.course!==this.id)throw Error(`Tag ${JSON.stringify(t)} does not belong to course ${this.id}`);return await updateTag(t)}async getCourseTagStubs(){return getCourseTagStubs(this.id)}async addNote(t,c,u,d,m,g,b=blankCourseElo()){try{let S=await addNote55(this.id,t,c,u,d,m,g,b);return S.ok?S.cardCreationFailed?(logger.warn(`[courseDB.addNote] Note added but card creation failed: ${S.cardCreationError}`),{status:Status.error,message:`Note was added but no cards were created: ${S.cardCreationError}`,id:S.id}):{status:Status.ok,message:``,id:S.id}:{status:Status.error,message:`Unexpected error adding note`}}catch(t){let c=t;return logger.error(`[addNote] error ${c.name}
363
363
  reason: ${c.reason}
364
364
  message: ${c.message}`),{status:Status.error,message:`Error adding note to course. ${t.reason||c.message}`}}}async getCourseDoc(t,c){return await this.db.get(t,c??{})}async getCourseDocs(t,c={}){return await this.db.allDocs({...c,keys:t})}getNavigationStrategy(t){if(logger.debug(`[courseDB] Getting navigation strategy: ${t}`),t==``){let t={_id:`NAVIGATION_STRATEGY-ELO`,docType:`NAVIGATION_STRATEGY`,name:`ELO`,description:`ELO-based navigation strategy for ordering content by difficulty`,implementingClass:`elo`,course:this.id,serializedData:``};return Promise.resolve(t)}else return this.db.get(t)}async getAllNavigationStrategies(){let t=DocTypePrefixes.NAVIGATION_STRATEGY;return(await this.db.allDocs({startkey:t,endkey:`${t}\uFFF0`,include_docs:!0})).rows.map(t=>t.doc)}async addNavigationStrategy(t){return logger.debug(`[courseDB] Adding navigation strategy: ${t._id}`),this.invalidateNavigatorCache(),this.remoteDB.put(t).then(()=>{})}updateNavigationStrategy(t,c){return logger.debug(`[courseDB] Updating navigation strategy: ${t}`),logger.debug(JSON.stringify(c)),Promise.resolve()}async createNavigator(t){try{let c=await this.getAllNavigationStrategies();if(c.length===0)return logger.debug(`[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])`),createDefaultPipeline(t,this);let{pipeline:u,generatorStrategies:d,filterStrategies:m,warnings:g}=await new PipelineAssembler().assemble({strategies:c,user:t,course:this});for(let t of g)logger.warn(`[PipelineAssembler] ${t}`);return u?(logger.debug(`[courseDB] Using assembled pipeline with ${d.length} generator(s) and ${m.length} filter(s)`),u):(logger.debug(`[courseDB] Pipeline assembly failed, using default pipeline`),createDefaultPipeline(t,this))}catch(t){let c=t instanceof Error?`${t.message}
365
- ${t.stack}`:JSON.stringify(t);throw logger.error(`[courseDB] Error creating navigator: ${c}`),t}}setEphemeralHints(t){this._pendingHints=t}async getWeightedCards(t){let c=await this._getCurrentUser();try{let{navigator:u}=await this._getCachedNavigator(c);return this._pendingHints&&(u.setEphemeralHints(this._pendingHints),this._pendingHints=null),await u.getWeightedCards(t)}catch(t){throw logger.error(`[courseDB] Error getting weighted cards: ${t}`),t}}async _getCachedNavigator(t){let c=t.getUsername(),u=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===c&&u-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let d=await this.createNavigator(t);return this._cachedNavigator={navigator:d,userId:c,builtAt:u},{navigator:d,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(t={limit:99,elo:`user`},c){let u;if(t.elo===`user`){let t=await this._getCurrentUser();u=-1;try{u=EloToNumber((await t.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.id).elo)}catch{u=1e3}}else if(t.elo===`random`){let t=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());u=Math.round(t.low+Math.random()*(t.high-t.low))}else u=t.elo;let d=Math.max(2e3,t.limit*4),m=Date.now(),g=`hit`;if(!this._eloPoolCache||m-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),g=`miss`}let rankAgainstCurrentElo=()=>{let t=this._eloPoolCache?.rows??[];return(c?t.filter(t=>c(t)):t).map(t=>({...t})).sort((t,c)=>Math.abs((t.elo??u)-u)-Math.abs((c.elo??u)-u))},b=rankAgainstCurrentElo();if(b.length<t.limit&&(g===`hit`||!this._eloPoolCache)){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),b=rankAgainstCurrentElo(),g=`refresh`}let S=[];for(;S.length<t.limit&&b.length>0;){let t=randIntWeightedTowardZero(b.length),c=b.splice(t,1)[0];S.push(c)}return S.map(t=>({courseID:this.id,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:t.elo,status:`new`}))}async searchCards(t){logger.log(`[CourseDB ${this.id}] Searching for: "${t}"`);let c;try{c=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${t}.*`}}}),logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(u){logger.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,u);let d=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});logger.log(`[CourseDB ${this.id}] Retrieved ${d.docs.length} documents for manual filtering`),c={docs:d.docs.filter(c=>{let u=JSON.stringify(c).toLowerCase().includes(t.toLowerCase());return u&&logger.log(`[CourseDB ${this.id}] Manual match found in document: ${c._id}`),u})}}if(logger.log(`[CourseDB ${this.id}] Found ${c.docs.length} displayable data documents`),c.docs.length===0){let t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});logger.log(`[CourseDB ${this.id}] Sample displayable data:`,t.docs.map(t=>({id:t._id,docType:t.docType,dataStructure:t.data?Object.keys(t.data):`no data field`,dataContent:t.data,fullDoc:t})))}let u=[];for(let t of c.docs){let c=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[t._id]}}});logger.log(`[CourseDB ${this.id}] Displayable data ${t._id} linked to ${c.docs.length} cards`),u.push(...c.docs)}return logger.log(`[CourseDB ${this.id}] Total cards found: ${u.length}`),u}async find(t){return this.db.find(t)}}}}),init_classroomDB2=__esm({"src/impl/couch/classroomDB.ts"(){"use strict";init_factory(),init_logger(),init_pouchdb_setup(),init_couch(),init_courseDB(),classroomLookupDBTitle=`classdb-lookup`,CLASSROOM_CONFIG=`ClassroomConfig`,ClassroomDBBase=class{constructor(){_defineProperty$2(this,`_id`,void 0),_defineProperty$2(this,`_db`,void 0),_defineProperty$2(this,`_cfg`,void 0),_defineProperty$2(this,`_initComplete`,!1),_defineProperty$2(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return logger.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(t=>t.doc)}getContentId(t){return t.type===`tag`?`${this._content_prefix}-${t.courseID}-${t.tagID}`:`${this._content_prefix}-${t.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},StudentClassroomDB=class _StudentClassroomDB extends ClassroomDBBase{constructor(t,c){super(),_defineProperty$2(this,`userMessages`,void 0),_defineProperty$2(this,`_user`,void 0),this._id=t,this._user=c}async init(){let t=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{this._cfg=await this._db.get(CLASSROOM_CONFIG),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(t){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t,c){let u=new _StudentClassroomDB(t,c);return await u.init(),u}setChangeFcn(t){this.userMessages.on(`change`,t)}async getWeightedCards(t){let c=[],u=(await this._user.getPendingReviews()).filter(t=>t.scheduledFor===`classroom`&&t.schedulingAgentId===this._id);for(let t of u)c.push({cardId:t.cardId,courseId:t.courseId,score:1,reviewID:t._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let d=await this._user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=hooks.utc(),b=(await this.getAssignedContent()).filter(t=>g.isAfter(hooks.utc(t.activeOn,REVIEW_TIME_FORMAT)));logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(b)}`);for(let u of b)if(u.type===`course`){let{cards:d}=await new CourseDB(u.courseID,async()=>this._user).getWeightedCards(t);for(let t of d)m.has(t.cardId)||c.push({...t,provenance:[...t.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:t.score,reason:`Assigned via classroom from course ${u.courseID}`}]})}else if(u.type===`tag`){let t=await getTag(u.courseID,u.tagID);for(let d of t.taggedCards)m.has(d)||c.push({cardId:d,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${u.tagID}, new card`}]})}else u.type===`card`&&(m.has(u.cardID)||c.push({cardId:u.cardID,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return logger.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${c.length} total (reviews + new)`),{cards:c.sort((t,c)=>c.score-t.score).slice(0,t)}}},TeacherClassroomDB=class _TeacherClassroomDB extends ClassroomDBBase{constructor(t){super(),_defineProperty$2(this,`_stuDb`,void 0),this._id=t}async init(){let t=`classdb-teacher-${this._id}`,c=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig()),this._stuDb=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+c,createPouchDBConfig());try{return this._db.get(CLASSROOM_CONFIG).then(t=>{this._cfg=t,this._initComplete=!0}).then(()=>{})}catch(t){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t){let c=new _TeacherClassroomDB(t);return await c.init(),c}async removeContent(t){let c=this.getContentId(t);try{let t=await this._db.get(c);await this._db.remove(t),this._db.replicate.to(this._stuDb,{doc_ids:[c]})}catch(t){logger.error(`Failed to remove content:`,c,t)}}async assignContent(t){let c,u=this.getContentId(t);return c=t.type===`tag`?await this._db.put({courseID:t.courseID,tagID:t.tagID,type:`tag`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}):await this._db.put({courseID:t.courseID,type:`course`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}),c.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[u]}),!0):!1}},ClassroomLookupDB=()=>new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+classroomLookupDBTitle,{skip_setup:!0})}}),init_adminDB2=__esm({"src/impl/couch/adminDB.ts"(){"use strict";init_pouchdb_setup(),init_factory(),init_couch(),init_classroomDB2(),init_courseLookupDB(),init_logger(),AdminDB=class{constructor(){_defineProperty$2(this,`usersDB`,void 0),this.usersDB=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(t=>t.doc)}async getCourses(){let t=await CourseLookup.allCourseWare();return await Promise.all(t.map(t=>getCredentialledCourseConfig(t._id)))}async removeCourse(t){let c=await CourseLookup.delete(t),u=await getCredentialledCourseConfig(t);u.deleted=!0;let d=await updateCredentialledCourseConfig(t,u);return{ok:c.ok&&d.ok,id:c.id,rev:c.rev}}async getClassrooms(){let t=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(t=>t.doc.uuid);logger.debug(t.join(`, `));let c=[];for(let u=0;u<t.length;u++)try{let d=await TeacherClassroomDB.factory(t[u]);c.push(d)}catch(c){let d=c;d.error&&d.error===`not_found`&&logger.warn(`db ${t[u]} not found`)}return c.map(t=>({...t.getConfig(),_id:t._id}))}}}}),CourseSyncService_exports={},__export(CourseSyncService_exports,{CourseSyncService:()=>CourseSyncService}),init_CourseSyncService=__esm({"src/impl/couch/CourseSyncService.ts"(){"use strict";var t;init_pouchdb_setup(),init_couch(),init_logger(),DEFAULT_REPLICATION={batchSize:1e3,batchesLimit:5},CourseSyncService=(t=class _CourseSyncService{constructor(){_defineProperty$2(this,`entries`,new Map),_defineProperty$2(this,`replicationOptions`,DEFAULT_REPLICATION)}static getInstance(){return _CourseSyncService.instance||(_CourseSyncService.instance=new _CourseSyncService),_CourseSyncService.instance}configure(t){t.replication&&(this.replicationOptions={...DEFAULT_REPLICATION,...t.replication},logger.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(_CourseSyncService.instance){for(let[,t]of _CourseSyncService.instance.entries)t.localDB&&t.localDB.close().catch(()=>{});_CourseSyncService.instance.entries.clear()}_CourseSyncService.instance=null}async ensureSynced(t,c){let u=this.entries.get(t);if(u?.status.state===`ready`&&u.localDB){if(!await this.isLocalEpochStale(t,u.localDB))return;logger.info(`[CourseSyncService] Remote DB epoch changed for course ${t} \u2014 destroying stale local replica`);try{await u.localDB.destroy()}catch{}u.localDB=null,u.readyPromise=null}if(u?.status.state===`disabled`)return;if(u?.readyPromise)return u.readyPromise;let d={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(t,d),d.readyPromise=this.performSync(t,d,c),d.readyPromise}getLocalDB(t){let c=this.entries.get(t);return c?.status.state===`ready`&&c.localDB?c.localDB:null}isReady(t){return this.entries.get(t)?.status.state===`ready`}getStatus(t){return this.entries.get(t)?.status??{state:`not-started`}}async performSync(t,c,u){try{if(!u&&(c.status={state:`checking-config`},!await this.checkLocalSyncEnabled(t))){c.status={state:`disabled`},c.readyPromise=null,logger.debug(`[CourseSyncService] Local sync disabled for course ${t}`);return}c.status={state:`syncing`};let d=this.localDBName(t),m=new pouchdb_setup_default(d);await this.isLocalEpochStale(t,m)&&(logger.info(`[CourseSyncService] Stale local DB detected for course ${t} \u2014 destroying before sync`),await m.destroy(),m=new pouchdb_setup_default(d)),c.localDB=m;let g=this.getRemoteDB(t),b=Date.now();logger.info(`[CourseSyncService] Starting one-shot replication for course ${t} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let S=await this.replicate(g,m),C=Date.now()-b;logger.info(`[CourseSyncService] Replication complete for course ${t}: ${S.docs_written} docs in ${C}ms`),c.status={state:`warming-views`};let w=Date.now();await this.warmViewIndices(m);let T=Date.now()-w;logger.info(`[CourseSyncService] View indices warmed for course ${t} in ${T}ms`),c.status={state:`ready`,docsReplicated:S.docs_written,syncTimeMs:C,viewWarmTimeMs:T}}catch(u){let d=u instanceof Error?u.message:String(u);if(logger.error(`[CourseSyncService] Sync failed for course ${t}: ${d}`),c.status={state:`error`,error:d},c.readyPromise=null,c.localDB){try{await c.localDB.destroy()}catch{}c.localDB=null}}}async checkLocalSyncEnabled(t){try{return(await this.getRemoteDB(t).get(`CourseConfig`)).localSync?.enabled===!0}catch(c){return logger.warn(`[CourseSyncService] Could not read CourseConfig for ${t}, assuming local sync disabled: ${c}`),!1}}replicate(t,c){return new Promise((u,d)=>{pouchdb_setup_default.replicate(t,c,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,t=>{u(t)}).on(`error`,t=>{d(t)})})}async warmViewIndices(t){for(let c of[`elo`,`getTags`])try{await t.query(c,{limit:1}),logger.debug(`[CourseSyncService] Warmed view index: ${c}`)}catch(t){logger.debug(`[CourseSyncService] Could not warm view ${c}: ${t}`)}}async isLocalEpochStale(t,c){try{let u=await this.getRemoteDB(t).get(`db-epoch`),d=null;try{d=await c.get(`db-epoch`)}catch{return!0}return u.epoch!==d.epoch}catch{return!1}}getRemoteDB(t){return getCourseDB2(t)}localDBName(t){return`coursedb-local-${t}`}},_defineProperty$2(t,`instance`,null),t)}}),init_auth=__esm({"src/impl/couch/auth.ts"(){"use strict";init_factory(),init_logger()}}),CouchDBSyncStrategy_exports={},__export(CouchDBSyncStrategy_exports,{CouchDBSyncStrategy:()=>CouchDBSyncStrategy}),init_CouchDBSyncStrategy=__esm({"src/impl/couch/CouchDBSyncStrategy.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_common(),init_pouchdb_setup(),init_couch(),init_auth(),log2=t=>{logger.info(t)},CouchDBSyncStrategy=class{constructor(){_defineProperty$2(this,`syncHandle`,void 0),_defineProperty$2(this,`hydrationHandle`,void 0)}setupRemoteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}getWriteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}async hydrate(t,c){let u=(await t.info()).doc_count===0,d=pouchdb_setup_default.replicate(c,t,u?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=d;try{let t=await d;return{docsWritten:t.docs_written,lastSeq:u?t.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(t,c,u){t.name!==c.name&&(this.syncHandle=pouchdb_setup_default.sync(t,c,{live:!0,retry:!0,...u===void 0?{}:{pull:{since:u}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(t){logger.warn(`Failed to cancel hydration pull (continuing anyway): ${t}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(t){logger.warn(`Failed to cancel user sync (continuing anyway): ${t}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(t,c){let u=await this.getCurrentUsername(),d=u.startsWith(GuestUsername);d&&logger.info(`Creating account for funnel user ${u} -> ${t}`);try{let m=await this.getRemoteCouchRootDB().signUp(t,c);if(m.ok){log2(`CREATEACCOUNT: Successfully created account for ${t}`);try{let t=await this.getRemoteCouchRootDB().logOut();log2(`CREATEACCOUNT: logged out: ${t.ok}`)}catch{}let m=await this.getRemoteCouchRootDB().logIn(t,c);if(log2(`CREATEACCOUNT: logged in as new user: ${m.ok}`),m.ok){if(d){logger.info(`Migrating data from funnel account ${u} to ${t}`);let c=await this.migrateFunnelData(u,t);c.success||logger.warn(`Migration failed: ${c.error}`)}return{status:Status.ok,error:void 0}}else return{status:Status.error,error:`Failed to log in after account creation`}}else return logger.warn(`Signup not OK: ${JSON.stringify(m)}`),{status:Status.error,error:`Account creation failed`}}catch(t){return t.reason===`Document update conflict.`?{status:Status.error,error:`This username is taken!`}:(logger.error(`Error on signup: ${JSON.stringify(t)}`),{status:Status.error,error:t.message||`Unknown error during account creation`})}}async authenticate(t,c){try{return(await this.getRemoteCouchRootDB().logIn(t,c)).ok?(log2(`Successfully logged in as ${t}`),{ok:!0}):(log2(`Login failed for ${t}`),{ok:!1,error:`Invalid username or password`})}catch(c){return logger.error(`Authentication error for ${t}:`,c),{ok:!1,error:c.message||`Authentication failed`}}}async logout(){try{let t=await this.getRemoteCouchRootDB().logOut();return{ok:t.ok,error:t.ok?void 0:`Logout failed`}}catch(t){return logger.error(`Logout error:`,t),{ok:!1,error:t.message||`Logout failed`}}}async getCurrentUsername(){logger.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let t=await getLoggedInUsername();return logger.log(`[funnel] getLoggedInUsername() returned:`,t),t}catch(t){logger.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),logger.log(`[funnel] Error was:`,t);let c=accomodateGuest();return logger.log(`[funnel] accomodateGuest() returned:`,c),c.username}}async migrateFunnelData(t,c){try{logger.info(`Starting data migration from ${t} to ${c}`);let u=getLocalUserDB(t),d=getLocalUserDB(c),m=await u.allDocs({include_docs:!0});logger.info(`Found ${m.rows.length} documents in funnel account`);let g=m.rows.filter(t=>!t.id.startsWith(`_design/`)).map(t=>({...t.doc,_rev:void 0}));g.length>0?(await d.bulkDocs(g),logger.info(`Successfully migrated ${g.length} documents from ${t} to ${c}`)):logger.info(`No documents to migrate from funnel account`);try{await u.destroy(),logger.info(`Destroyed consumed guest DB for ${t}`)}catch(c){logger.warn(`Failed to destroy consumed guest DB for ${t} (non-fatal): ${c instanceof Error?c.message:String(c)}`)}return{success:!0}}catch(t){return logger.error(`Migration failed:`,t),{success:!1,error:t instanceof Error?t.message:`Unknown error`}}}getRemoteCouchRootDB(){let t=ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`skuilder`;try{return new pouchdb_setup_default(t,{skip_setup:!0})}catch(t){throw logger.error(`Failed to initialize remote CouchDB connection:`,t),Error(`Failed to initialize CouchDB: ${JSON.stringify(t)}`)}}getUserDB(t){let c=!1,u=`userdb-${hexEncode(t)}`;return log2(`Fetching user database: ${u} (${t})`),new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+u,createPouchDBConfig())}}}}),init_couch=__esm({"src/impl/couch/index.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_pouchdb_setup(),init_contentSource(),init_adminDB2(),init_classroomDB2(),init_courseAPI(),init_courseDB(),init_CourseSyncService(),init_CouchDBSyncStrategy(),isBrowser=typeof window<`u`,isBrowser&&(window.process=import_browser.default),GUEST_LOCAL_DB=`userdb-${GuestUsername}`,new pouchdb_setup_default(GUEST_LOCAL_DB),pouchDBincludeCredentialsConfig={fetch(t,c){return c.credentials=`include`,pouchdb_setup_default.fetch(t,c)}},REVIEW_TIME_FORMAT=`YYYY-MM-DD--kk:mm:ss-SSS`}}),init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){"use strict";init_util(),init_logger(),duration=hooks.duration}}),init_SrsService=__esm({"src/study/services/SrsService.ts"(){"use strict";init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(t){_defineProperty$2(this,`user`,void 0),this.user=t}removeReview(t){logger.info(`[SrsService] Removing orphaned scheduled review: ${t}`),this.user.removeScheduledCardReview(t)}async scheduleReview(t,c){let u=newInterval(this.user,t),d=hooks.utc().add(u,`seconds`);isReview(c)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${c.cardID}`),this.user.removeScheduledCardReview(c.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:t.courseID,card_id:t.cardID,time:d,scheduledFor:c.contentSourceType,schedulingAgentId:c.contentSourceID})}}}}),init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){"use strict";}}),init_EloService=__esm({"src/study/services/EloService.ts"(){"use strict";init_logger(),init_tagRecent(),EloService=class{constructor(t,c){_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`user`,void 0),this.dataLayer=t,this.user=c}async updateUserAndCardElo(t,c,u,d,m,g){g&&logger.warn(`k value interpretation not currently implemented`);let b=this.dataLayer.getCourseDB(m.card.course_id),S=d.courses.find(t=>t.courseID===c);if(!S)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping ELO update for card ${u}. (Is the user registered for this course?)`),null;let C=toCourseElo(S.elo),w=(await b.getCardEloData([m.card.card_id]))[0];if(w&&C){let d=C.global.score,m=w.global.score,g=Object.keys(w.tags),T={};for(let t of g)T[t]=C.tags[t]?.score??C.global.score;let E=adjustCourseScores(C,w,t);S.elo=E.userElo;let D={};for(let c of g)D[c]={before:T[c],after:E.userElo.tags[c].score,score:t};let O={cardId:u,at:new Date().toISOString(),userScore:t,global:{before:d,after:E.userElo.global.score},card:{before:m,after:E.cardElo.global.score},...g.length?{tags:D}:{}},xr=await Promise.allSettled([this.user.updateUserElo(c,E.userElo),b.updateCardElo(u,E.cardElo)]),Sr=xr[0].status===`fulfilled`,Cr=xr[1].status===`fulfilled`;if(Sr&&Cr){let t=xr[0].value,c=xr[1].value;t.ok&&c&&c.ok&&logger.info(`[EloService] Updated ELOS:
365
+ ${t.stack}`:JSON.stringify(t);throw logger.error(`[courseDB] Error creating navigator: ${c}`),t}}setEphemeralHints(t){this._pendingHints=t}async getWeightedCards(t){let c=await this._getCurrentUser();try{let{navigator:u}=await this._getCachedNavigator(c);return this._pendingHints&&(u.setEphemeralHints(this._pendingHints),this._pendingHints=null),await u.getWeightedCards(t)}catch(t){throw logger.error(`[courseDB] Error getting weighted cards: ${t}`),t}}async _getCachedNavigator(t){let c=t.getUsername(),u=Date.now();if(this._cachedNavigator&&this._cachedNavigator.userId===c&&u-this._cachedNavigator.builtAt<this._navigatorTtlMs)return{navigator:this._cachedNavigator.navigator,cacheStatus:`hit`};let d=await this.createNavigator(t);return this._cachedNavigator={navigator:d,userId:c,builtAt:u},{navigator:d,cacheStatus:`miss`}}invalidateNavigatorCache(){this._cachedNavigator=null}async getCardsCenteredAtELO(t={limit:99,elo:`user`},c){let u;if(t.elo===`user`){let t=await this._getCurrentUser();u=-1;try{u=EloToNumber((await t.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this.id).elo)}catch{u=1e3}}else if(t.elo===`random`){let t=await GET_CACHED(`elo-bounds-${this.id}`,()=>this.getELOBounds());u=Math.round(t.low+Math.random()*(t.high-t.low))}else u=t.elo;let d=Math.max(2e3,t.limit*4),m=Date.now(),g=`hit`;if(!this._eloPoolCache||m-this._eloPoolCache.fetchedAt>this._eloPoolTtlMs){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),g=`miss`}let rankAgainstCurrentElo=()=>{let t=this._eloPoolCache?.rows??[];return(c?t.filter(t=>c(t)):t).map(t=>({...t})).sort((t,c)=>Math.abs((t.elo??u)-u)-Math.abs((c.elo??u)-u))},b=rankAgainstCurrentElo();if(b.length<t.limit&&(g===`hit`||!this._eloPoolCache)){let t=await this.getCardsByELO(u,d);t.length>0&&(this._eloPoolCache={rows:t,fetchedAt:m}),b=rankAgainstCurrentElo(),g=`refresh`}let S=[];for(;S.length<t.limit&&b.length>0;){let t=randIntWeightedTowardZero(b.length),c=b.splice(t,1)[0];S.push(c)}return S.map(t=>({courseID:this.id,cardID:t.cardID,contentSourceType:`course`,contentSourceID:this.id,elo:t.elo,status:`new`}))}async searchCards(t){logger.log(`[CourseDB ${this.id}] Searching for: "${t}"`);let c;try{c=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`,"data.0.data":{$regex:`.*${t}.*`}}}),logger.log(`[CourseDB ${this.id}] Regex search on data[0].data successful`)}catch(u){logger.log(`[CourseDB ${this.id}] Regex search failed, falling back to manual search:`,u);let d=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`}});logger.log(`[CourseDB ${this.id}] Retrieved ${d.docs.length} documents for manual filtering`),c={docs:d.docs.filter(c=>{let u=JSON.stringify(c).toLowerCase().includes(t.toLowerCase());return u&&logger.log(`[CourseDB ${this.id}] Manual match found in document: ${c._id}`),u})}}if(logger.log(`[CourseDB ${this.id}] Found ${c.docs.length} displayable data documents`),c.docs.length===0){let t=await this.db.find({selector:{docType:`DISPLAYABLE_DATA`},limit:5});logger.log(`[CourseDB ${this.id}] Sample displayable data:`,t.docs.map(t=>({id:t._id,docType:t.docType,dataStructure:t.data?Object.keys(t.data):`no data field`,dataContent:t.data,fullDoc:t})))}let u=[];for(let t of c.docs){let c=await this.db.find({selector:{docType:`CARD`,id_displayable_data:{$in:[t._id]}}});logger.log(`[CourseDB ${this.id}] Displayable data ${t._id} linked to ${c.docs.length} cards`),u.push(...c.docs)}return logger.log(`[CourseDB ${this.id}] Total cards found: ${u.length}`),u}async find(t){return this.db.find(t)}}}}),init_classroomDB2=__esm({"src/impl/couch/classroomDB.ts"(){"use strict";init_factory(),init_logger(),init_pouchdb_setup(),init_couch(),init_courseDB(),classroomLookupDBTitle=`classdb-lookup`,CLASSROOM_CONFIG=`ClassroomConfig`,ClassroomDBBase=class{constructor(){_defineProperty$2(this,`_id`,void 0),_defineProperty$2(this,`_db`,void 0),_defineProperty$2(this,`_cfg`,void 0),_defineProperty$2(this,`_initComplete`,!1),_defineProperty$2(this,`_content_prefix`,`content`)}get _content_searchkeys(){return getStartAndEndKeys(this._content_prefix)}async getAssignedContent(){return logger.info(`Getting assigned content...`),(await this._db.allDocs({startkey:this._content_prefix,endkey:this._content_prefix+`￰`,include_docs:!0})).rows.map(t=>t.doc)}getContentId(t){return t.type===`tag`?`${this._content_prefix}-${t.courseID}-${t.tagID}`:`${this._content_prefix}-${t.courseID}`}get ready(){return this._initComplete}getConfig(){return this._cfg}},StudentClassroomDB=class _StudentClassroomDB extends ClassroomDBBase{constructor(t,c){super(),_defineProperty$2(this,`userMessages`,void 0),_defineProperty$2(this,`_user`,void 0),this._id=t,this._user=c}async init(){let t=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig());try{this._cfg=await this._db.get(CLASSROOM_CONFIG),this.userMessages=this._db.changes({since:`now`,live:!0,include_docs:!0}),this._initComplete=!0;return}catch(t){throw Error(`Error in StudentClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t,c){let u=new _StudentClassroomDB(t,c);return await u.init(),u}setChangeFcn(t){this.userMessages.on(`change`,t)}async getWeightedCards(t){let c=[],u=(await this._user.getPendingReviews()).filter(t=>t.scheduledFor===`classroom`&&t.schedulingAgentId===this._id);for(let t of u)c.push({cardId:t.cardId,courseId:t.courseId,score:1,reviewID:t._id,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom scheduled review`}]});let d=await this._user.getActiveCards(),m=new Set(d.map(t=>t.cardID)),g=hooks.utc(),b=(await this.getAssignedContent()).filter(t=>g.isAfter(hooks.utc(t.activeOn,REVIEW_TIME_FORMAT)));logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(b)}`);for(let u of b)if(u.type===`course`){let{cards:d}=await new CourseDB(u.courseID,async()=>this._user).getWeightedCards(t);for(let t of d)m.has(t.cardId)||c.push({...t,provenance:[...t.provenance,{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`passed`,score:t.score,reason:`Assigned via classroom from course ${u.courseID}`}]})}else if(u.type===`tag`){let t=await getTag(u.courseID,u.tagID);for(let d of t.taggedCards)m.has(d)||c.push({cardId:d,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned tag: ${u.tagID}, new card`}]})}else u.type===`card`&&(m.has(u.cardID)||c.push({cardId:u.cardID,courseId:u.courseID,score:1,provenance:[{strategy:`classroom`,strategyName:`Classroom`,strategyId:`CLASSROOM`,action:`generated`,score:1,reason:`Classroom assigned card, new card`}]}));return logger.info(`[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${c.length} total (reviews + new)`),{cards:c.sort((t,c)=>c.score-t.score).slice(0,t)}}},TeacherClassroomDB=class _TeacherClassroomDB extends ClassroomDBBase{constructor(t){super(),_defineProperty$2(this,`_stuDb`,void 0),this._id=t}async init(){let t=`classdb-teacher-${this._id}`,c=`classdb-student-${this._id}`;this._db=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+t,createPouchDBConfig()),this._stuDb=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+c,createPouchDBConfig());try{return this._db.get(CLASSROOM_CONFIG).then(t=>{this._cfg=t,this._initComplete=!0}).then(()=>{})}catch(t){throw Error(`Error in TeacherClassroomDB constructor: ${JSON.stringify(t)}`)}}static async factory(t){let c=new _TeacherClassroomDB(t);return await c.init(),c}async removeContent(t){let c=this.getContentId(t);try{let t=await this._db.get(c);await this._db.remove(t),this._db.replicate.to(this._stuDb,{doc_ids:[c]})}catch(t){logger.error(`Failed to remove content:`,c,t)}}async assignContent(t){let c,u=this.getContentId(t);return c=t.type===`tag`?await this._db.put({courseID:t.courseID,tagID:t.tagID,type:`tag`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}):await this._db.put({courseID:t.courseID,type:`course`,_id:u,assignedBy:t.assignedBy,assignedOn:hooks.utc(),activeOn:t.activeOn||hooks.utc()}),c.ok?(this._db.replicate.to(this._stuDb,{doc_ids:[u]}),!0):!1}},ClassroomLookupDB=()=>new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+classroomLookupDBTitle,{skip_setup:!0})}}),init_adminDB2=__esm({"src/impl/couch/adminDB.ts"(){"use strict";init_pouchdb_setup(),init_factory(),init_couch(),init_classroomDB2(),init_courseLookupDB(),init_logger(),AdminDB=class{constructor(){_defineProperty$2(this,`usersDB`,void 0),this.usersDB=new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`_users`,createPouchDBConfig())}async getUsers(){return(await this.usersDB.allDocs({include_docs:!0,...getStartAndEndKeys(`org.couchdb.user:`)})).rows.map(t=>t.doc)}async getCourses(){let t=await CourseLookup.allCourseWare();return await Promise.all(t.map(t=>getCredentialledCourseConfig(t._id)))}async removeCourse(t){let c=await CourseLookup.delete(t),u=await getCredentialledCourseConfig(t);u.deleted=!0;let d=await updateCredentialledCourseConfig(t,u);return{ok:c.ok&&d.ok,id:c.id,rev:c.rev}}async getClassrooms(){let t=(await ClassroomLookupDB().allDocs({include_docs:!0})).rows.map(t=>t.doc.uuid);logger.debug(t.join(`, `));let c=[];for(let u=0;u<t.length;u++)try{let d=await TeacherClassroomDB.factory(t[u]);c.push(d)}catch(c){let d=c;d.error&&d.error===`not_found`&&logger.warn(`db ${t[u]} not found`)}return c.map(t=>({...t.getConfig(),_id:t._id}))}}}}),CourseSyncService_exports={},__export(CourseSyncService_exports,{CourseSyncService:()=>CourseSyncService}),init_CourseSyncService=__esm({"src/impl/couch/CourseSyncService.ts"(){"use strict";var t;init_pouchdb_setup(),init_couch(),init_logger(),DEFAULT_REPLICATION={batchSize:1e3,batchesLimit:5},CourseSyncService=(t=class _CourseSyncService{constructor(){_defineProperty$2(this,`entries`,new Map),_defineProperty$2(this,`replicationOptions`,DEFAULT_REPLICATION)}static getInstance(){return _CourseSyncService.instance||(_CourseSyncService.instance=new _CourseSyncService),_CourseSyncService.instance}configure(t){t.replication&&(this.replicationOptions={...DEFAULT_REPLICATION,...t.replication},logger.info(`[CourseSyncService] Replication configured: batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit}`))}static resetInstance(){if(_CourseSyncService.instance){for(let[,t]of _CourseSyncService.instance.entries)t.localDB&&t.localDB.close().catch(()=>{});_CourseSyncService.instance.entries.clear()}_CourseSyncService.instance=null}async ensureSynced(t,c){let u=this.entries.get(t);if(u?.status.state===`ready`&&u.localDB){if(!await this.isLocalEpochStale(t,u.localDB))return;logger.info(`[CourseSyncService] Remote DB epoch changed for course ${t} \u2014 destroying stale local replica`);try{await u.localDB.destroy()}catch{}u.localDB=null,u.readyPromise=null}if(u?.status.state===`disabled`)return;if(u?.readyPromise)return u.readyPromise;let d={localDB:null,status:{state:`not-started`},readyPromise:null};return this.entries.set(t,d),d.readyPromise=this.performSync(t,d,c),d.readyPromise}getLocalDB(t){let c=this.entries.get(t);return c?.status.state===`ready`&&c.localDB?c.localDB:null}isReady(t){return this.entries.get(t)?.status.state===`ready`}getStatus(t){return this.entries.get(t)?.status??{state:`not-started`}}async performSync(t,c,u){try{if(!u&&(c.status={state:`checking-config`},!await this.checkLocalSyncEnabled(t))){c.status={state:`disabled`},c.readyPromise=null,logger.debug(`[CourseSyncService] Local sync disabled for course ${t}`);return}c.status={state:`syncing`};let d=this.localDBName(t),m=new pouchdb_setup_default(d);await this.isLocalEpochStale(t,m)&&(logger.info(`[CourseSyncService] Stale local DB detected for course ${t} \u2014 destroying before sync`),await m.destroy(),m=new pouchdb_setup_default(d)),c.localDB=m;let g=this.getRemoteDB(t),b=Date.now();logger.info(`[CourseSyncService] Starting one-shot replication for course ${t} (batch_size=${this.replicationOptions.batchSize}, batches_limit=${this.replicationOptions.batchesLimit})`);let S=await this.replicate(g,m),C=Date.now()-b;logger.info(`[CourseSyncService] Replication complete for course ${t}: ${S.docs_written} docs in ${C}ms`),c.status={state:`warming-views`};let w=Date.now();await this.warmViewIndices(m);let T=Date.now()-w;logger.info(`[CourseSyncService] View indices warmed for course ${t} in ${T}ms`),c.status={state:`ready`,docsReplicated:S.docs_written,syncTimeMs:C,viewWarmTimeMs:T}}catch(u){let d=u instanceof Error?u.message:String(u);if(logger.error(`[CourseSyncService] Sync failed for course ${t}: ${d}`),c.status={state:`error`,error:d},c.readyPromise=null,c.localDB){try{await c.localDB.destroy()}catch{}c.localDB=null}}}async checkLocalSyncEnabled(t){try{return(await this.getRemoteDB(t).get(`CourseConfig`)).localSync?.enabled===!0}catch(c){return logger.warn(`[CourseSyncService] Could not read CourseConfig for ${t}, assuming local sync disabled: ${c}`),!1}}replicate(t,c){return new Promise((u,d)=>{pouchdb_setup_default.replicate(t,c,{batch_size:this.replicationOptions.batchSize,batches_limit:this.replicationOptions.batchesLimit}).on(`complete`,t=>{u(t)}).on(`error`,t=>{d(t)})})}async warmViewIndices(t){for(let c of[`elo`,`getTags`])try{await t.query(c,{limit:1}),logger.debug(`[CourseSyncService] Warmed view index: ${c}`)}catch(t){logger.debug(`[CourseSyncService] Could not warm view ${c}: ${t}`)}}async isLocalEpochStale(t,c){try{let u=await this.getRemoteDB(t).get(`db-epoch`),d=null;try{d=await c.get(`db-epoch`)}catch{return!0}return u.epoch!==d.epoch}catch{return!1}}getRemoteDB(t){return getCourseDB2(t)}localDBName(t){return`coursedb-local-${t}`}},_defineProperty$2(t,`instance`,null),t)}}),init_auth=__esm({"src/impl/couch/auth.ts"(){"use strict";init_factory(),init_logger()}}),CouchDBSyncStrategy_exports={},__export(CouchDBSyncStrategy_exports,{CouchDBSyncStrategy:()=>CouchDBSyncStrategy}),init_CouchDBSyncStrategy=__esm({"src/impl/couch/CouchDBSyncStrategy.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_common(),init_pouchdb_setup(),init_couch(),init_auth(),log2=t=>{logger.info(t)},CouchDBSyncStrategy=class{constructor(){_defineProperty$2(this,`syncHandle`,void 0),_defineProperty$2(this,`hydrationHandle`,void 0)}setupRemoteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}getWriteDB(t){return t===GuestUsername||t.startsWith(GuestUsername)?getLocalUserDB(t):this.getUserDB(t)}async hydrate(t,c){let u=(await t.info()).doc_count===0,d=pouchdb_setup_default.replicate(c,t,u?{selector:{_deleted:{$exists:!1}}}:{});this.hydrationHandle=d;try{let t=await d;return{docsWritten:t.docs_written,lastSeq:u?t.last_seq:void 0}}finally{this.hydrationHandle=void 0}}startSync(t,c,u){t.name!==c.name&&(this.syncHandle=pouchdb_setup_default.sync(t,c,{live:!0,retry:!0,...u===void 0?{}:{pull:{since:u}}}))}stopSync(){if(this.hydrationHandle){try{this.hydrationHandle.cancel()}catch(t){logger.warn(`Failed to cancel hydration pull (continuing anyway): ${t}`)}this.hydrationHandle=void 0}if(this.syncHandle){try{this.syncHandle.cancel()}catch(t){logger.warn(`Failed to cancel user sync (continuing anyway): ${t}`)}this.syncHandle=void 0}}canCreateAccount(){return!0}canAuthenticate(){return!0}async createAccount(t,c){let u=await this.getCurrentUsername(),d=u.startsWith(GuestUsername);d&&logger.info(`Creating account for funnel user ${u} -> ${t}`);try{let m=await this.getRemoteCouchRootDB().signUp(t,c);if(m.ok){log2(`CREATEACCOUNT: Successfully created account for ${t}`);try{let t=await this.getRemoteCouchRootDB().logOut();log2(`CREATEACCOUNT: logged out: ${t.ok}`)}catch{}let m=await this.getRemoteCouchRootDB().logIn(t,c);if(log2(`CREATEACCOUNT: logged in as new user: ${m.ok}`),m.ok){if(d){logger.info(`Migrating data from funnel account ${u} to ${t}`);let c=await this.migrateFunnelData(u,t);c.success||logger.warn(`Migration failed: ${c.error}`)}return{status:Status.ok,error:void 0}}else return{status:Status.error,error:`Failed to log in after account creation`}}else return logger.warn(`Signup not OK: ${JSON.stringify(m)}`),{status:Status.error,error:`Account creation failed`}}catch(t){return t.reason===`Document update conflict.`?{status:Status.error,error:`This username is taken!`}:(logger.error(`Error on signup: ${JSON.stringify(t)}`),{status:Status.error,error:t.message||`Unknown error during account creation`})}}async authenticate(t,c){try{return(await this.getRemoteCouchRootDB().logIn(t,c)).ok?(log2(`Successfully logged in as ${t}`),{ok:!0}):(log2(`Login failed for ${t}`),{ok:!1,error:`Invalid username or password`})}catch(c){return logger.error(`Authentication error for ${t}:`,c),{ok:!1,error:c.message||`Authentication failed`}}}async adoptSession(t){let c;try{c=await getLoggedInUsername()}catch{return{ok:!1,error:`No session to adopt`}}if(t?.startsWith(GuestUsername)){logger.info(`Migrating data from funnel account ${t} to ${c}`);let u=await this.migrateFunnelData(t,c);u.success||logger.warn(`Migration failed: ${u.error}`)}return{ok:!0,username:c}}async logout(){try{let t=await this.getRemoteCouchRootDB().logOut();return{ok:t.ok,error:t.ok?void 0:`Logout failed`}}catch(t){return logger.error(`Logout error:`,t),{ok:!1,error:t.message||`Logout failed`}}}async getCurrentUsername(){logger.log(`[funnel] CouchDBSyncStrategy.getCurrentUsername() called`);try{let t=await getLoggedInUsername();return logger.log(`[funnel] getLoggedInUsername() returned:`,t),t}catch(t){logger.log(`[funnel] getLoggedInUsername() failed, calling accomodateGuest()`),logger.log(`[funnel] Error was:`,t);let c=accomodateGuest();return logger.log(`[funnel] accomodateGuest() returned:`,c),c.username}}async migrateFunnelData(t,c){try{logger.info(`Starting data migration from ${t} to ${c}`);let u=getLocalUserDB(t),d=getLocalUserDB(c),m=await u.allDocs({include_docs:!0});logger.info(`Found ${m.rows.length} documents in funnel account`);let g=m.rows.filter(t=>!t.id.startsWith(`_design/`)).map(t=>({...t.doc,_rev:void 0}));g.length>0?(await d.bulkDocs(g),logger.info(`Successfully migrated ${g.length} documents from ${t} to ${c}`)):logger.info(`No documents to migrate from funnel account`);try{await u.destroy(),logger.info(`Destroyed consumed guest DB for ${t}`)}catch(c){logger.warn(`Failed to destroy consumed guest DB for ${t} (non-fatal): ${c instanceof Error?c.message:String(c)}`)}return{success:!0}}catch(t){return logger.error(`Migration failed:`,t),{success:!1,error:t instanceof Error?t.message:`Unknown error`}}}getRemoteCouchRootDB(){let t=ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+`skuilder`;try{return new pouchdb_setup_default(t,{skip_setup:!0})}catch(t){throw logger.error(`Failed to initialize remote CouchDB connection:`,t),Error(`Failed to initialize CouchDB: ${JSON.stringify(t)}`)}}getUserDB(t){let c=!1,u=`userdb-${hexEncode(t)}`;return log2(`Fetching user database: ${u} (${t})`),new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL+`://`+ENV.COUCHDB_SERVER_URL+u,createPouchDBConfig())}}}}),init_couch=__esm({"src/impl/couch/index.ts"(){"use strict";init_factory(),init_types_legacy(),init_logger(),init_pouchdb_setup(),init_contentSource(),init_adminDB2(),init_classroomDB2(),init_courseAPI(),init_courseDB(),init_CourseSyncService(),init_CouchDBSyncStrategy(),isBrowser=typeof window<`u`,isBrowser&&(window.process=import_browser.default),GUEST_LOCAL_DB=`userdb-${GuestUsername}`,new pouchdb_setup_default(GUEST_LOCAL_DB),pouchDBincludeCredentialsConfig={fetch(t,c){return c.credentials=`include`,pouchdb_setup_default.fetch(t,c)}},REVIEW_TIME_FORMAT=`YYYY-MM-DD--kk:mm:ss-SSS`}}),init_SpacedRepetition=__esm({"src/study/SpacedRepetition.ts"(){"use strict";init_util(),init_logger(),duration=hooks.duration}}),init_SrsService=__esm({"src/study/services/SrsService.ts"(){"use strict";init_couch(),init_SpacedRepetition(),init_logger(),SrsService=class{constructor(t){_defineProperty$2(this,`user`,void 0),this.user=t}removeReview(t){logger.info(`[SrsService] Removing orphaned scheduled review: ${t}`),this.user.removeScheduledCardReview(t)}async scheduleReview(t,c){let u=newInterval(this.user,t),d=hooks.utc().add(u,`seconds`);isReview(c)&&(logger.info(`[SrsService] Removing previously scheduled review for: ${c.cardID}`),this.user.removeScheduledCardReview(c.reviewID)),this.user.scheduleCardReview({user:this.user.getUsername(),course_id:t.courseID,card_id:t.cardID,time:d,scheduledFor:c.contentSourceType,schedulingAgentId:c.contentSourceID})}}}}),init_tagRecent=__esm({"src/study/services/tagRecent.ts"(){"use strict";}}),init_EloService=__esm({"src/study/services/EloService.ts"(){"use strict";init_logger(),init_tagRecent(),EloService=class{constructor(t,c){_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`user`,void 0),this.dataLayer=t,this.user=c}async updateUserAndCardElo(t,c,u,d,m,g){g&&logger.warn(`k value interpretation not currently implemented`);let b=this.dataLayer.getCourseDB(m.card.course_id),S=d.courses.find(t=>t.courseID===c);if(!S)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping ELO update for card ${u}. (Is the user registered for this course?)`),null;let C=toCourseElo(S.elo),w=(await b.getCardEloData([m.card.card_id]))[0];if(w&&C){let d=C.global.score,m=w.global.score,g=Object.keys(w.tags),T={};for(let t of g)T[t]=C.tags[t]?.score??C.global.score;let E=adjustCourseScores(C,w,t);S.elo=E.userElo;let D={};for(let c of g)D[c]={before:T[c],after:E.userElo.tags[c].score,score:t};let O={cardId:u,at:new Date().toISOString(),userScore:t,global:{before:d,after:E.userElo.global.score},card:{before:m,after:E.cardElo.global.score},...g.length?{tags:D}:{}},xr=await Promise.allSettled([this.user.updateUserElo(c,E.userElo),b.updateCardElo(u,E.cardElo)]),Sr=xr[0].status===`fulfilled`,Cr=xr[1].status===`fulfilled`;if(Sr&&Cr){let t=xr[0].value,c=xr[1].value;t.ok&&c&&c.ok&&logger.info(`[EloService] Updated ELOS:
366
366
  User: ${JSON.stringify(E.userElo)})
367
367
  Card: ${JSON.stringify(E.cardElo)})
368
368
  `)}else logger.warn(`[EloService] Partial ELO update:
@@ -420,13 +420,14 @@ Example:
420
420
  sessionId: ${this.sessionId}
421
421
  startTime: ${this.startTime}
422
422
  endTime: ${this.endTime}
423
- defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let t=0;for(let c=0;c<this.failedQ.length;c++){let u=this.failedQ.peek(c),d=this._sessionRecord.find(t=>t.item.cardID===u.cardID),m=0;if(d){for(let t=0;t<d.records.length;t++)m+=d.records[t].timeSpent;m/=d.records.length,t+=m}}let c=t/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(c)}`),c}async prepareSession(){if(this.sources.some(t=>typeof t.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let t=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=t,t>=0&&t<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${t}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(t,c){for(let u of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:u.runId,at:u.timestamp.toISOString(),label:t,...c?{mode:c}:{},generatedCount:u.generatedCount,finalCount:u.finalCount,reviewsSelected:u.reviewsSelected,newSelected:u.newSelected,...typeof u.userElo==`number`?{userElo:u.userElo}:{},...u.generators?{generators:u.generators}:{},...u.filters?{filters:u.filters}:{},...u.hints?{hints:u.hints}:{},...u.discardedTail?{discardedTail:u.discardedTail}:{}})}}async _captureState(t){if(!this._stateSnapshotProvider)return;let c=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(t)),new Promise(t=>setTimeout(()=>t(void 0),3e3))])}catch(c){this.log(`[Session] state snapshot (${t}) failed: ${c}`);return}}async _openSessionDoc(){if(this._courseId)try{let t=this.dataLayer.getUserDB(),c={_id:makeStudySessionId(this._courseId,t.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:t.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=c,await t.putStudySession(c),this.log(`[Session] Opened session record ${c._id}`)}catch(t){logger.warn(`[SessionController] Failed to open session record: ${t}`)}}async requestReplan(t){let c=this.normalizeReplanOptions(t),u=this._replanHasIntent(c);if(this._replanPromise){if(!u)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let t=c.label?` [${c.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${t} behind in-flight run`);let d=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(c)),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=m,d}let d=this._runReplan(c),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=m,await d}_replanHasIntent(t){return!!(t.limit!==void 0||t.minFollowUpCards!==void 0||t.mode&&t.mode!==`replace`||t.hints&&Object.keys(t.hints).length>0||t.sessionHints!==void 0||t.mergeSessionHints!==void 0)}async _runReplan(t){this._activeReplanLabel=t.label??`(auto)`,t.hints||(t.hints={});let c=t.hints,u=new Set(c.excludeCards??[]);this._currentCard?.item.cardID&&u.add(this._currentCard.item.cardID);for(let t of this._sessionRecord)u.add(t.card.card_id);this.supplyQ.length>0&&u.add(this.supplyQ.peek(0).cardID),c.excludeCards=[...u],t.sessionHints!==void 0&&(this._sessionHints=t.sessionHints,this.log(`[Replan] Session hints ${t.sessionHints?`set`:`cleared`}: ${JSON.stringify(t.sessionHints)}`)),t.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,t.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(t.hints,t.label);let d=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${d} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(t)}setSessionHints(t){this._sessionHints=t,this.log(`Session hints ${t?`set`:`cleared`}: ${JSON.stringify(t)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=t=>{let c=[];for(let u=0;u<t.length;u++){let d=t.peek(u);c.push({cardID:d.cardID,status:d.status,origin:isReview(d)?`review`:`new`,score:d.score})}return{length:t.length,dequeueCount:t.dequeueCount,cards:c}},t=this._sessionRecord.map(t=>{let c=t.records[t.records.length-1];return{cardID:t.item.cardID,status:t.item.status,attempts:t.records.length,correct:c&&isQuestionRecord(c)?c.isCorrect:null,timeSpentMs:t.records.reduce((t,c)=>t+c.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:t}}mergeSessionHints(t){this._sessionHints=mergeHints2([this._sessionHints,t])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(t,c){let u=t&&c?{...t,_label:c}:t,d=mergeHints2([this._sessionHints,u]);if(d)for(let t of this.sources)t.setEphemeralHints?.(d)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:t=>this.setSessionHints(t),mergeSessionHints:t=>this.mergeSessionHints(t),requestReplan:t=>this.requestReplan(t)}),this._sessionControls}_recordEloEvent(t){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(t)}async _notifyOutcomeObservers(t,c,u){if(this._outcomeObservers.length===0||!isQuestionRecord(t))return;let d={record:t,card:c.card,result:u},m=this._getSessionControls();for(let t of this._outcomeObservers)try{await t(d,m)}catch(t){this.error(`[OutcomeObserver] observer threw; ignoring`,t)}}async _replanUncoalesced(t){let c=this._runReplan(t),u=c.finally(()=>{this._replanPromise===u&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=u,await c}normalizeReplanOptions(t){if(!t)return{};let c=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(t).some(t=>c.includes(t))?t:{hints:t}}async _executeReplan(t={}){let c=t.limit,u=t.mode??`replace`,d=await this.getWeightedContent({replan:!0,additive:u===`merge`,limit:c});this._recordRuns(t.label??`(auto)`,u),this._wellIndicatedRemaining=d,c!==void 0&&c<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${c}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,d>=0&&d<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${d}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let m=t.label?` [${t.label}]`:``;this.log(`Replan complete${m}: supplyQ now has ${this.supplyQ.length} cards (mode=${u})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(t){this.endTime=new Date(this.endTime.valueOf()+1e3*t)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let t=this.sources.some(t=>typeof t.getWeightedCards==`function`),extractQueueItems=(t,c=10)=>{let u=[];for(let d=0;d<Math.min(t.length,c);d++){let c=t.peek(d);u.push({courseID:c.courseID||`unknown`,cardID:c.cardID||`unknown`,status:c.status||`unknown`,score:c.score})}return u};return{api:{mode:t?`weighted`:`legacy`,description:t?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(t){let c=t?.replan??!1,u=t?.additive??!1,d=t?.limit??this._defaultBatchLimit,m=d;c||this._applyHintsToSources();let g=[];for(let t=0;t<this.sources.length;t++){let c=this.sources[t];try{let u=(await c.getWeightedCards(m)).cards;g.push({sourceIndex:t,weighted:u})}catch(c){if(this.error(`Failed to get content from source ${t}:`,c),this.sources.length===1)throw Error(`Cannot start session: failed to load content from source ${t}`)}}if(g.length===0){if(c)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let b=this.mixer.mix(g,m*this.sources.length),S=g.map(t=>t.weighted[0]?.courseId||`source-${t.sourceIndex}`);await Promise.all(S.map(async t=>{if(!this.courseNameCache.has(t))try{let c=await this.dataLayer.getCoursesDB().getCourseConfig(t);this.courseNameCache.set(t,c.name)}catch{}}));let C=S.map(t=>this.courseNameCache.get(t)),w=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(m*this.sources.length/g.length):void 0;captureMixerRun(this.mixer.constructor.name,g,S,C,m*this.sources.length,w,b);let T=b.filter(t=>!this._servedCardIds.has(t.cardId)),E=T.filter(t=>t.score===1/0),D=T.filter(t=>t.score!==1/0),O=[...E,...D.slice(0,Math.max(0,d-E.length))],xr=new Set(E.map(t=>t.cardId)),Sr=O.filter(t=>t.score>=_SessionController.WELL_INDICATED_SCORE).length,Cr=c?`Replan content:
423
+ defaultBatchLimit: ${this._defaultBatchLimit}`),registerActiveController(this)}tick(){this._secondsRemaining=Math.floor((this.endTime.valueOf()-Date.now())/1e3),this._secondsRemaining<=0&&clearInterval(this._intervalHandle)}estimateCleanupTime(){let t=0;for(let c=0;c<this.failedQ.length;c++){let u=this.failedQ.peek(c),d=this._sessionRecord.find(t=>t.item.cardID===u.cardID),m=0;if(d){for(let t=0;t<d.records.length;t++)m+=d.records[t].timeSpent;m/=d.records.length,t+=m}}let c=t/1e3;return this.log(`Failed card cleanup estimate: ${Math.round(c)}`),c}async prepareSession(){if(this.sources.some(t=>typeof t.getWeightedCards!=`function`))throw Error(`[SessionController] All content sources must implement getWeightedCards().`);clearStaleSessionDebugState();let t=await this.getWeightedContent();this._recordRuns(`bootstrap`),this._wellIndicatedRemaining=t,t>=0&&t<_SessionController.MIN_WELL_INDICATED&&this.log(`[Init] Only ${t}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`),await this.hydrationService.ensureHydratedCards(),startSessionTracking(this.sessionId,this.supplyQ.length,this.failedQ.length),this._openDocPromise=this._openSessionDoc(),this._intervalHandle=setInterval(()=>{this.tick()},1e3)}_recordRuns(t,c){for(let u of drainCapturedRuns()){if(this._runLog.length>=_SessionController.MAX_LOGGED_RUNS)break;this._runLog.push({runId:u.runId,at:u.timestamp.toISOString(),label:t,...c?{mode:c}:{},generatedCount:u.generatedCount,finalCount:u.finalCount,reviewsSelected:u.reviewsSelected,newSelected:u.newSelected,...typeof u.userElo==`number`?{userElo:u.userElo}:{},...u.generators?{generators:u.generators}:{},...u.filters?{filters:u.filters}:{},...u.hints?{hints:u.hints}:{},...u.discardedTail?{discardedTail:u.discardedTail}:{}})}}async _captureState(t){if(!this._stateSnapshotProvider)return;let c=3e3;try{return await Promise.race([Promise.resolve(this._stateSnapshotProvider(t)),new Promise(t=>setTimeout(()=>t(void 0),3e3))])}catch(c){this.log(`[Session] state snapshot (${t}) failed: ${c}`);return}}async _openSessionDoc(){if(this._courseId)try{let t=this.dataLayer.getUserDB(),c={_id:makeStudySessionId(this._courseId,t.getUsername(),this.sessionId),docType:`STUDY_SESSION`,sessionId:this.sessionId,courseId:this._courseId,userId:t.getUsername(),startTime:this.startTime.toISOString(),status:`open`,plannedSeconds:Math.round((this.endTime.valueOf()-this.startTime.valueOf())/1e3),config:{defaultBatchLimit:this._defaultBatchLimit,sourceCount:this.sources.length,initHints:this._sessionHints},initialQueues:{supplyQ:this.supplyQ.length,failedQ:this.failedQ.length},runs:[...this._runLog],stateAtStart:await this._captureState(`start`)};this._sessionDoc=c,await t.putStudySession(c),this.log(`[Session] Opened session record ${c._id}`)}catch(t){logger.warn(`[SessionController] Failed to open session record: ${t}`)}}async requestReplan(t){let c=this.normalizeReplanOptions(t),u=this._replanHasIntent(c);if(this._replanPromise){if(!u)return this.log(`Replan already in progress, coalescing unhinted auto-replan`),this._replanPromise;let t=c.label?` [${c.label}]`:``;this.log(`Replan in progress; queueing hint-bearing replan${t} behind in-flight run`);let d=this._replanPromise.catch(()=>void 0).then(()=>this._runReplan(c)),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});return this._replanPromise=m,d}let d=this._runReplan(c),m=d.finally(()=>{this._replanPromise===m&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=m,await d}_replanHasIntent(t){return!!(t.limit!==void 0||t.minFollowUpCards!==void 0||t.mode&&t.mode!==`replace`||t.hints&&Object.keys(t.hints).length>0||t.sessionHints!==void 0||t.mergeSessionHints!==void 0)}async _runReplan(t){this._activeReplanLabel=t.label??`(auto)`,t.hints||(t.hints={});let c=t.hints,u=new Set(c.excludeCards??[]);this._currentCard?.item.cardID&&u.add(this._currentCard.item.cardID);for(let t of this._sessionRecord)u.add(t.card.card_id);this.supplyQ.length>0&&u.add(this.supplyQ.peek(0).cardID),c.excludeCards=[...u],t.sessionHints!==void 0&&(this._sessionHints=t.sessionHints,this.log(`[Replan] Session hints ${t.sessionHints?`set`:`cleared`}: ${JSON.stringify(t.sessionHints)}`)),t.mergeSessionHints!==void 0&&(this._sessionHints=mergeHints2([this._sessionHints,t.mergeSessionHints])??null,this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`)),this._applyHintsToSources(t.hints,t.label);let d=t.label?` [${t.label}]`:``;this.log(`Mid-session replan requested${d} (limit: ${t.limit??`default`}, mode: ${t.mode??`replace`}${t.hints?`, with hints`:``})`),t.minFollowUpCards!==void 0&&t.minFollowUpCards>0&&(this._minCardsGuarantee=Math.max(this._minCardsGuarantee,t.minFollowUpCards),this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`)),await this._executeReplan(t)}setSessionHints(t){this._sessionHints=t,this.log(`Session hints ${t?`set`:`cleared`}: ${JSON.stringify(t)}`)}getSessionHints(){return this._sessionHints}getDebugSnapshot(){let describe=t=>{let c=[];for(let u=0;u<t.length;u++){let d=t.peek(u);c.push({cardID:d.cardID,status:d.status,origin:isReview(d)?`review`:`new`,score:d.score})}return{length:t.length,dequeueCount:t.dequeueCount,cards:c}},t=this._sessionRecord.map(t=>{let c=t.records[t.records.length-1];return{cardID:t.item.cardID,status:t.item.status,attempts:t.records.length,correct:c&&isQuestionRecord(c)?c.isCorrect:null,timeSpentMs:t.records.reduce((t,c)=>t+c.timeSpent,0)}});return{sessionId:this.sessionId,secondsRemaining:this.secondsRemaining,hasCardGuarantee:this.hasCardGuarantee,minCardsGuarantee:this._minCardsGuarantee,wellIndicatedRemaining:this._wellIndicatedRemaining,currentCard:this._currentCard?.item.cardID??null,sessionHints:this._sessionHints,replanActive:this._replanPromise!==null,replanLabel:this._activeReplanLabel,supplyQ:describe(this.supplyQ),failedQ:describe(this.failedQ),reviewBacklog:getSrsBacklogDebug(),strategyPressure:getStrategyPressureDebug(),drawnCards:t}}mergeSessionHints(t){this._sessionHints=mergeHints2([this._sessionHints,t])??null,this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`)}_applyHintsToSources(t,c){let u=t&&c?{...t,_label:c}:t,d=mergeHints2([this._sessionHints,u]);if(d)for(let t of this.sources)t.setEphemeralHints?.(d)}_getSessionControls(){return this._sessionControls||(this._sessionControls={getSessionHints:()=>this.getSessionHints(),setSessionHints:t=>this.setSessionHints(t),mergeSessionHints:t=>this.mergeSessionHints(t),requestReplan:t=>this.requestReplan(t)}),this._sessionControls}_recordEloEvent(t){this._eloLog.length>=_SessionController.MAX_LOGGED_ELO_EVENTS||this._eloLog.push(t)}async _notifyOutcomeObservers(t,c,u){if(this._outcomeObservers.length===0||!isQuestionRecord(t))return;let d={record:t,card:c.card,result:u},m=this._getSessionControls();for(let t of this._outcomeObservers)try{await t(d,m)}catch(t){this.error(`[OutcomeObserver] observer threw; ignoring`,t)}}async _replanUncoalesced(t){let c=this._runReplan(t),u=c.finally(()=>{this._replanPromise===u&&(this._replanPromise=null,this._activeReplanLabel=null)});this._replanPromise=u,await c}normalizeReplanOptions(t){if(!t)return{};let c=[`hints`,`sessionHints`,`limit`,`mode`,`label`,`minFollowUpCards`];return Object.keys(t).some(t=>c.includes(t))?t:{hints:t}}async _executeReplan(t={}){let c=t.limit,u=t.mode??`replace`,d=await this.getWeightedContent({replan:!0,additive:u===`merge`,limit:c});this._recordRuns(t.label??`(auto)`,u),this._wellIndicatedRemaining=d,c!==void 0&&c<this._defaultBatchLimit?(this._suppressQualityReplan=!0,this.log(`[Replan] Burst mode (limit=${c}): suppressing quality-based auto-replan`)):this._suppressQualityReplan=!1,d>=0&&d<_SessionController.MIN_WELL_INDICATED&&this.log(`[Replan] Only ${d}/${_SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`),await this.hydrationService.ensureHydratedCards();let m=t.label?` [${t.label}]`:``;this.log(`Replan complete${m}: supplyQ now has ${this.supplyQ.length} cards (mode=${u})`),snapshotQueues(this.supplyQ.length,this.failedQ.length)}addTime(t){this.endTime=new Date(this.endTime.valueOf()+1e3*t)}get failedCount(){return this.failedQ.length}toString(){return`Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`}reportString(){return`${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`}getDebugInfo(){let t=this.sources.some(t=>typeof t.getWeightedCards==`function`),extractQueueItems=(t,c=10)=>{let u=[];for(let d=0;d<Math.min(t.length,c);d++){let c=t.peek(d);u.push({courseID:c.courseID||`unknown`,cardID:c.cardID||`unknown`,status:c.status||`unknown`,score:c.score})}return u};return{api:{mode:t?`weighted`:`legacy`,description:t?`Using getWeightedCards() API with scored candidates`:`ERROR: getWeightedCards() not a function.`},supplyQueue:{length:this.supplyQ.length,dequeueCount:this.supplyQ.dequeueCount,items:extractQueueItems(this.supplyQ)},failedQueue:{length:this.failedQ.length,dequeueCount:this.failedQ.dequeueCount,items:extractQueueItems(this.failedQ)},hydratedCache:{count:this.hydrationService.hydratedCount,cardIds:this.hydrationService.getHydratedCardIds()},replan:{inProgress:this._replanPromise!==null,suppressQualityReplan:this._suppressQualityReplan,defaultBatchLimit:this._defaultBatchLimit,minCardsGuarantee:this._minCardsGuarantee}}}async getWeightedContent(t){let c=t?.replan??!1,u=t?.additive??!1,d=t?.limit??this._defaultBatchLimit,m=d;c||this._applyHintsToSources();let g=[];for(let t=0;t<this.sources.length;t++){let u=this.sources[t];try{let c=(await u.getWeightedCards(m)).cards;g.push({sourceIndex:t,weighted:c})}catch(u){if(this.error(`Failed to get content from source ${t}:`,u),this.sources.length===1&&!c)throw Error(`Cannot start session: failed to load content from source ${t}`)}}if(g.length===0){if(c)return this.log(`Replan: no content from any source, keeping existing supplyQ`),-1;throw Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`)}let b=this.mixer.mix(g,m*this.sources.length),S=g.map(t=>t.weighted[0]?.courseId||`source-${t.sourceIndex}`);await Promise.all(S.map(async t=>{if(!this.courseNameCache.has(t))try{let c=await this.dataLayer.getCoursesDB().getCourseConfig(t);this.courseNameCache.set(t,c.name)}catch{}}));let C=S.map(t=>this.courseNameCache.get(t)),w=this.mixer instanceof QuotaRoundRobinMixer?Math.ceil(m*this.sources.length/g.length):void 0;captureMixerRun(this.mixer.constructor.name,g,S,C,m*this.sources.length,w,b);let T=b.filter(t=>!this._servedCardIds.has(t.cardId)),E=T.filter(t=>t.score===1/0),D=T.filter(t=>t.score!==1/0),O=[...E,...D.slice(0,Math.max(0,d-E.length))],xr=new Set(E.map(t=>t.cardId)),Sr=O.filter(t=>t.score>=_SessionController.WELL_INDICATED_SCORE).length,Cr=c?`Replan content:
424
424
  `:`Mixed content session created with:
425
425
  `,wr=O.map(t=>{let c=getCardOrigin(t),u=Number.isFinite(t.score)?t.score.toFixed(2):`+INF`;return Cr+=`${c===`review`?`Review`:`New`}: ${t.courseId}::${t.cardId} (score: ${u})
426
426
  `,this._buildSupplyItem(t,c)});if(u){let t=this.supplyQ.mergeToFront(wr,t=>t.cardID,xr);Cr+=`Additive merge: ${t} cards added to front of supplyQ
427
427
  `}else if(c)this.supplyQ.replaceAll(wr,t=>t.cardID);else for(let t of wr)this.supplyQ.add(t,t.cardID);return this.log(Cr),Sr}_buildSupplyItem(t,c=getCardOrigin(t)){let u={cardID:t.cardId,courseID:t.courseId,contentSourceType:`course`,contentSourceID:t.courseId,score:t.score};return c===`review`?{...u,status:`review`,reviewID:t.reviewID}:{...u,status:`new`}}_getItemsToHydrate(){let t=[],c=3,u=2;for(let c=0;c<Math.min(3,this.supplyQ.length);c++)t.push(this.supplyQ.peek(c));for(let c=0;c<Math.min(2,this.failedQ.length);c++)t.push(this.failedQ.peek(c));return t}_selectNextItemToHydrate(){if(this.supplyQ.length===0&&this.failedQ.length===0||this._secondsRemaining<2&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return null;if(this._secondsRemaining<=0&&this._minCardsGuarantee<=0)return this.failedQ.length>0?this.failedQ.peek(0):null;let t=this.supplyQ.length>0?this.supplyQ.peek(0):null;return this._minCardsGuarantee>0&&t?t:this.failedQ.length>0&&this._shouldInterleaveFailed(t!==null)?this.failedQ.peek(0):t||(this.failedQ.length>0?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null))}_shouldInterleaveFailed(t){return this.failedQ.length===0?!1:!t||this._secondsRemaining-this.estimateCleanupTime()<=_SessionController.FAILED_ENDGAME_SLACK_SECONDS?!0:this._supplyDrawsSinceFailed>=_SessionController.FAILED_INTERLEAVE_EVERY}async nextCard(t=`dismiss-success`){if(this.dismissCurrentCard(t),this._minCardsGuarantee>0&&(this._minCardsGuarantee--,this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`)),this._replanPromise&&this.supplyQ.length===0&&this.failedQ.length===0&&(this.log(`nextCard: queues empty, awaiting in-flight replan before drawing`),await this._replanPromise),this.supplyQ.length<=_SessionController.DEPLETION_PREFETCH_THRESHOLD&&this._secondsRemaining>0&&!this._replanPromise&&(this._suppressQualityReplan=!1,this.log(`[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) (${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. Triggering background replan.`),this.requestReplan({label:`auto:depletion`,mode:`merge`})),!this._suppressQualityReplan&&this._wellIndicatedRemaining<=3&&this.supplyQ.length>0&&!this._replanPromise&&(this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (supplyQ: ${this.supplyQ.length}). Triggering background replan.`),this.requestReplan({label:`auto:quality`})),this._secondsRemaining<=0&&this.failedQ.length===0&&this._minCardsGuarantee<=0)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let c=3,u=250,d=0;for(;this._secondsRemaining>0&&this.supplyQ.length===0&&this.failedQ.length===0;)if(this.log(`[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. Running pipeline (attempt ${d+1}/3).`),await this._replanUncoalesced({label:`wedge-breaker`}),this.supplyQ.length===0&&this.failedQ.length===0){if(d++,d>=3){this.log(`[WedgeBreaker] Pipeline returned no content 3 consecutive times. Giving up; session will end.`);break}await new Promise(t=>setTimeout(t,250))}else d=0;let m=20;for(let t=0;t<20;t++){let t=this._selectNextItemToHydrate();if(!t)return this._currentCard=null,endSessionTracking(),this._terminate(),null;let c=this.hydrationService.getHydratedCard(t.cardID);if(c||(c=await this.hydrationService.waitForCard(t.cardID)),this.removeItemFromQueue(t),c){await this.hydrationService.ensureHydratedCards(),this._currentCard=c;let u=t.status===`review`||t.status===`failed-review`?`review`:t.status===`new`||t.status===`failed-new`?`new`:`failed`,d=t.status.startsWith(`failed`)?`failedQ`:`supplyQ`;return recordCardPresentation(t.cardID,t.courseID,this.courseNameCache.get(t.courseID),u,d,t.score),snapshotQueues(this.supplyQ.length,this.failedQ.length),c}this.log(`Skipping card ${t.cardID}: hydration failed, trying next`),isReview(t)&&this.srsService.removeReview(t.reviewID)}return this.log(`Exhausted 20 skip attempts finding a hydratable card`),this._currentCard=null,endSessionTracking(),this._terminate(),null}_terminate(){this.endSession().catch(t=>{logger.warn(`[SessionController] endSession failed: ${t}`)})}async submitResponse(t,c,u,d,m,g,b,S,C){let w={...d.item},T=await this.services.response.processResponse(t,c,w,u,d,m,g,b,S,C);return await this._notifyOutcomeObservers(t,d,T),T}dismissCurrentCard(t=`dismiss-success`){if(this._currentCard)if(t===`dismiss-success`)this.hydrationService.removeCard(this._currentCard.item.cardID);else if(t===`marked-failed`){let t;t=isReview(this._currentCard.item)?{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-review`,reviewID:this._currentCard.item.reviewID}:{cardID:this._currentCard.item.cardID,courseID:this._currentCard.item.courseID,contentSourceID:this._currentCard.item.contentSourceID,contentSourceType:this._currentCard.item.contentSourceType,status:`failed-new`},this.failedQ.add(t,t.cardID),this._supplyDrawsSinceFailed=0}else (t===`dismiss-error`||t===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(t){this._clearDurableRequirement(t.cardID),this._servedCardIds.add(t.cardID),this.failedQ.peek(0)?.cardID===t.cardID?(this.failedQ.dequeue(t=>t.cardID),this._supplyDrawsSinceFailed=0):this.supplyQ.peek(0)?.cardID===t.cardID&&(this.supplyQ.dequeue(t=>t.cardID),this._supplyDrawsSinceFailed++,this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--)}_clearDurableRequirement(t){let c=this._sessionHints?.requireCards;if(!c||c.length===0)return;let u=c.filter(c=>c!==t);u.length!==c.length&&(this._sessionHints={...this._sessionHints,requireCards:u.length>0?u:void 0},this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${t}`))}async endSession(t=`closed`){if(this._sessionClosed||(this._sessionClosed=!0,clearInterval(this._intervalHandle),setDebugSessionId(void 0),await this._closeSessionDoc(t),!this._sessionRecord||this._sessionRecord.length===0))return;let c=this._sessionRecord.flatMap(t=>t.records).filter(t=>t.userAnswer!==void 0);if(c.length===0)return;let u=null,d=[];for(let t of this.sources)if(t.getOrchestrationContext){try{u=await t.getOrchestrationContext(),t.getStrategyIds&&d.push(...t.getStrategyIds())}catch(t){logger.warn(`[SessionController] Failed to get orchestration context: ${t}`)}if(u)break}if(!u){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let m=new Date().toISOString(),g=new Date(this.startTime).toISOString();await recordUserOutcome(u,g,m,c,d)}async _closeSessionDoc(t){this._openDocPromise&&await this._openDocPromise;let c=this._sessionDoc;if(!c)return;let u=this._sessionRecord.flatMap(t=>t.records),d=u.filter(isQuestionRecord);try{let m={...c,status:t,endTime:new Date().toISOString(),tally:{cardsPresented:this._sessionRecord.length,responses:u.length,correct:d.filter(t=>t.isCorrect).length,incorrect:d.filter(t=>!t.isCorrect).length,failedQRemaining:this.failedQ.length,secondsRemaining:Math.max(0,this._secondsRemaining)},runs:[...this._runLog],eloEvents:[...this._eloLog],finalHints:this._sessionHints,stateAtEnd:await this._captureState(`end`)};this._sessionDoc=m,await this.dataLayer.getUserDB().putStudySession(m),this.log(`[Session] Session record ${m._id} -> ${t} (${m.tally.cardsPresented} cards, ${m.tally.responses} responses, ${this._runLog.length} pipeline runs)`)}catch(t){logger.warn(`[SessionController] Failed to close session record: ${t}`)}}},_defineProperty$2(t,`MAX_LOGGED_RUNS`,100),_defineProperty$2(t,`MAX_LOGGED_ELO_EVENTS`,2e3),_defineProperty$2(t,`MIN_WELL_INDICATED`,5),_defineProperty$2(t,`WELL_INDICATED_SCORE`,.1),_defineProperty$2(t,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty$2(t,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty$2(t,`FAILED_ENDGAME_SLACK_SECONDS`,20),t)}}),init_TagFilteredContentSource=__esm({"src/study/TagFilteredContentSource.ts"(){"use strict";init_courseDB(),init_logger(),TagFilteredContentSource=class{constructor(t,c,u){_defineProperty$2(this,`courseId`,void 0),_defineProperty$2(this,`filter`,void 0),_defineProperty$2(this,`user`,void 0),_defineProperty$2(this,`resolvedCardIds`,null),this.courseId=t,this.filter=c,this.user=u,logger.info(`[TagFilteredContentSource] Created for course "${t}" with filter:`,JSON.stringify(c))}async resolveFilteredCardIds(){if(this.resolvedCardIds!==null)return this.resolvedCardIds;let t=new Set;if(this.filter.include.length>0)for(let c of this.filter.include)try{(await getTag(this.courseId,c)).taggedCards.forEach(c=>t.add(c))}catch(t){logger.warn(`[TagFilteredContentSource] Could not resolve tag "${c}" for inclusion:`,t)}if(t.size===0&&this.filter.include.length>0)return logger.warn(`[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(`, `)}`),this.resolvedCardIds=new Set,this.resolvedCardIds;let c=new Set;if(this.filter.exclude.length>0)for(let t of this.filter.exclude)try{(await getTag(this.courseId,t)).taggedCards.forEach(t=>c.add(t))}catch(c){logger.warn(`[TagFilteredContentSource] Could not resolve tag "${t}" for exclusion:`,c)}let u=new Set;for(let d of t)c.has(d)||u.add(d);return logger.info(`[TagFilteredContentSource] Resolved ${u.size} cards (included: ${t.size}, excluded: ${c.size})`),this.resolvedCardIds=u,u}async getWeightedCards(t){if(!hasActiveFilter(this.filter))return logger.warn(`[TagFilteredContentSource] getWeightedCards called with no active filter`),{cards:[]};let c=await this.resolveFilteredCardIds(),u=await this.user.getActiveCards(),d=new Set(u.map(t=>t.cardID)),m=[];for(let u of c)if(d.has(u)||m.push({cardId:u,courseId:this.courseId,score:1,provenance:[{strategy:`tagFilter`,strategyName:`Tag Filter`,strategyId:`TAG_FILTER`,action:`generated`,score:1,reason:`Tag-filtered new card (tags: ${this.filter.include.join(`, `)})`}]}),m.length>=t)break;logger.info(`[TagFilteredContentSource] Found ${m.length} new cards matching filter`);let g=await this.user.getPendingReviews(this.courseId),b=g.filter(t=>c.has(t.cardId));return logger.info(`[TagFilteredContentSource] Found ${b.length} pending reviews matching filter (of ${g.length} total)`),{cards:[...b.map(t=>({cardId:t.cardId,courseId:t.courseId,score:1,reviewID:t._id,provenance:[{strategy:`tagFilter`,strategyName:`Tag Filter`,strategyId:`TAG_FILTER`,action:`generated`,score:1,reason:`Tag-filtered review (tags: ${this.filter.include.join(`, `)})`}]})),...m].slice(0,t)}}clearCache(){this.resolvedCardIds=null}getCourseId(){return this.courseId}getFilter(){return this.filter}}}}),init_study=__esm({"src/study/index.ts"(){"use strict";init_SessionController(),init_SourceMixer(),init_SpacedRepetition(),init_TagFilteredContentSource(),init_MixerDebugger(),init_SessionDebugger(),init_SessionOverlay()}}),init_userDBHelpers=__esm({"src/impl/common/userDBHelpers.ts"(){"use strict";init_core(),init_logger(),init_pouchdb_setup(),init_dataDirectory(),REVIEW_TIME_FORMAT2=`YYYY-MM-DD--kk:mm:ss-SSS`,log3=t=>{logger.info(t)}}}),init_user_course_relDB=__esm({"src/impl/couch/user-course-relDB.ts"(){"use strict";init_logger(),UsrCrsData=class{constructor(t,c){_defineProperty$2(this,`user`,void 0),_defineProperty$2(this,`_courseId`,void 0),this.user=t,this._courseId=c}async getReviewsForcast(t){let c=hooks.utc().add(t,`days`);return this.getReviewstoDate(c)}async getPendingReviews(){let t=hooks.utc();return this.getReviewstoDate(t)}async getScheduledReviewCount(){return(await this.getPendingReviews()).length}async getCourseSettings(){let t=(await this.user.getCourseRegistrationsDoc()).courses.find(t=>t.courseID===this._courseId);return t&&t.settings?t.settings:(logger.warn(`no settings found during lookup on course ${this._courseId}`),{})}updateCourseSettings(t){`updateCourseSettings`in this.user&&this.user.updateCourseSettings(this._courseId,t)}async getStrategyState(t){return this.user.getStrategyState(this._courseId,t)}async putStrategyState(t,c){return this.user.putStrategyState(this._courseId,t,c)}async deleteStrategyState(t){return this.user.deleteStrategyState(this._courseId,t)}async getReviewstoDate(t){let c=await this.user.getPendingReviews(this._courseId);return logger.debug(`Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`),c.filter(c=>{let u=hooks.utc(c.reviewTime);return t.isAfter(u)})}}}}),init_BaseUserDB=__esm({"src/impl/common/BaseUserDB.ts"(){"use strict";var t;init_core(),init_util(),init_types_legacy(),init_logger(),init_study(),init_userDBHelpers(),init_updateQueue(),init_user_course_relDB(),init_couch(),log4=t=>{logger.info(t)},HYDRATION_TIMEOUT_MS=15e3,BaseUser=(t=class _BaseUser{static Dummy(t){return new _BaseUser(`Me`,t)}getUsername(){return this._username}isLoggedIn(){return!this._username.startsWith(GuestUsername)}remote(){return this.remoteDB}hydrationStatus(){return{...this._hydration}}async awaitHydration(){try{await this._hydrationPromise}catch{}return this.hydrationStatus()}canMaterializeDefaults(){return this._hydration.state!==`failed`&&this._hydration.state!==`hydrating`}async createAccount(t,c){if(!this.syncStrategy.canCreateAccount())throw Error(`Account creation not supported by current sync strategy`);if(!this._username.startsWith(GuestUsername))throw Error(`Cannot create a new account while logged in:
428
428
  Currently logged-in as ${this._username}.`);let u=await this.syncStrategy.createAccount(t,c);if(u.status===Status.ok){log4(`Account created successfully, updating username to ${t}`),this._username=t;try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}await this.init()}return{status:u.status,error:u.error||``}}async login(t,c){if(!this.syncStrategy.canAuthenticate())throw Error(`Authentication not supported by current sync strategy`);if(!this._username.startsWith(GuestUsername)&&this._username!=t){if(this._username!=t)throw Error(`Cannot change accounts while logged in.
429
- Log out of account ${this.getUsername()} before logging in as ${t}.`);logger.warn(`User ${this._username} is already logged in, but executing login again.`)}let u=await this.syncStrategy.authenticate(t,c);if(u.ok){log4(`Logged in as ${t}`),this._username=t;try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}await this.init()}return u}async resetUserData(){if(this.syncStrategy.canAuthenticate())return{status:Status.error,error:`Reset user data is only available for local-only mode. Use logout instead for remote sync.`};try{let t=getLocalUserDB(this._username),c=(await t.allDocs({include_docs:!1})).rows.filter(t=>{let c=t.id;return c.startsWith(DocTypePrefixes.CARDRECORD)||c.startsWith(DocTypePrefixes.SCHEDULED_CARD)||c.startsWith(DocTypePrefixes.STRATEGY_STATE)||c.startsWith(DocTypePrefixes.USER_OUTCOME)||c.startsWith(DocTypePrefixes.STRATEGY_LEARNING_STATE)||c===_BaseUser.DOC_IDS.COURSE_REGISTRATIONS||c===_BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS||c===_BaseUser.DOC_IDS.CONFIG}).map(t=>({_id:t.id,_rev:t.value.rev,_deleted:!0}));return c.length>0&&await t.bulkDocs(c),await this.init(),{status:Status.ok}}catch(t){return logger.error(`Failed to reset user data:`,t),{status:Status.error,error:t instanceof Error?t.message:`Unknown error during reset`}}}async logout(){if(!this.syncStrategy.canAuthenticate())return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),{ok:!0};let t=await this.syncStrategy.logout();try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),t}async get(t){return this.localDB.get(t)}update(t,c){return this.updateQueue.update(t,c)}async getCourseRegistrationsDoc(){logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);let t;try{return await this.localDB.get(_BaseUser.DOC_IDS.COURSE_REGISTRATIONS)}catch(c){if(c.status===404){if(!this.canMaterializeDefaults())throw Error(`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc \u2014 that would report an existing user as unregistered, and then lose to their real document once sync resumes.`);await this.localDB.put({_id:_BaseUser.DOC_IDS.COURSE_REGISTRATIONS,courses:[],studyWeight:{}}),t=await this.getCourseRegistrationsDoc()}else throw Error(`Unexpected error ${JSON.stringify(c)} in getOrCreateCourseRegistrationDoc...`)}return t}async getActiveCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(t=>t.status===void 0||t.status===`active`)}async getActiveCards(){let t=getStartAndEndKeys2(DocTypePrefixes.SCHEDULED_CARD);return(await this.remoteDB.allDocs({startkey:t.startkey,endkey:t.endkey,include_docs:!0})).rows.map(t=>({courseID:t.doc.courseId,cardID:t.doc.cardId}))}async getActivityRecords(){try{let t=await this.getHistory(),c=[];if(!Array.isArray(t))return logger.error(`getHistory did not return an array:`,t),c;let u=0;for(let d=0;d<t.length;d++)try{t[d]&&Array.isArray(t[d].records)&&t[d].records.forEach(t=>{try{if(!t.timeStamp)return;let d;if(typeof t.timeStamp==`object`)if(typeof t.timeStamp.toDate==`function`)d=t.timeStamp.toISOString();else if(t.timeStamp instanceof Date)d=t.timeStamp.toISOString();else{u<3&&(logger.warn(`Unknown timestamp object type:`,t.timeStamp),u++);return}else if(typeof t.timeStamp==`string`){let c=new Date(t.timeStamp);if(isNaN(c.getTime()))return;d=t.timeStamp}else if(typeof t.timeStamp==`number`)d=new Date(t.timeStamp).toISOString();else return;c.push({timeStamp:d,courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,timeSpent:t.timeSpent||0,type:`card_view`})}catch{}})}catch(t){logger.error(`Error processing history item:`,t)}return logger.debug(`Found ${c.length} activity records`),c}catch(t){return logger.error(`Error in getActivityRecords:`,t),[]}}async getReviewstoDate(t,c){let u=getStartAndEndKeys2(DocTypePrefixes.SCHEDULED_CARD),d=await this.remoteDB.allDocs({startkey:u.startkey,endkey:u.endkey,include_docs:!0});return log4(`Fetching ${this._username}'s scheduled reviews${c?` for course ${c}`:``}.`),d.rows.filter(u=>{if(u.id.startsWith(DocTypePrefixes.SCHEDULED_CARD)){let d=hooks.utc(u.id.substr(DocTypePrefixes.SCHEDULED_CARD.length),REVIEW_TIME_FORMAT2);if(t.isAfter(d)&&(c===void 0||u.doc.courseId===c))return!0}}).map(t=>t.doc)}async getReviewsForcast(t,c){let u=hooks.utc().add(t,`days`);return this.getReviewstoDate(u,c)}async getPendingReviews(t){let c=hooks.utc();return this.getReviewstoDate(c,t)}async getScheduledReviewCount(t){return(await this.getPendingReviews(t)).length}async getRegisteredCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(t=>!t.status||t.status===`active`||t.status===`maintenance-mode`)}async getCourseRegDoc(t){let c=(await this.getCourseRegistrationsDoc()).courses.find(c=>c.courseID===t);if(c)return c;throw Error(`Course registration not found for course ID: ${t}`)}async registerForCourse(t,c=!1){return this.getCourseRegistrationsDoc().then(u=>{let d=c?`preview`:`active`;logger.debug(`Registering for ${t} with status: ${d}`);let m={status:d,courseID:t,user:!0,admin:!1,moderator:!1,elo:{global:{score:1e3,count:0},tags:{},misc:{}}};return u.courses.filter(t=>t.courseID===m.courseID).length===0?(log4(`It's a new course registration!`),u.courses.push(m),u.studyWeight[t]=1):u.courses.forEach(c=>{log4(`Found the previously registered course!`),c.courseID===t&&(c.status=d)}),this.localDB.put(u)}).catch(t=>{throw log4(`Registration failed because of: ${JSON.stringify(t)}`),t})}async dropCourse(t,c=`dropped`){return this.getCourseRegistrationsDoc().then(u=>{let d=-1;for(let c=0;c<u.courses.length;c++)u.courses[c].courseID===t&&(d=c);if(d!==-1)delete u.studyWeight[t],u.courses[d].status=c;else throw Error(`User ${this.getUsername()} is not currently registered for course ${t}`);return this.localDB.put(u)})}async getCourseInterface(t){return new UsrCrsData(this,t)}async getUserEditableCourses(){let t=[],c=await this.getCourseRegistrationsDoc();return t=t.concat(c.courses.map(t=>t.courseID)),await Promise.all(t.map(async t=>await getCredentialledCourseConfig(t)))}async getConfig(){let t={_id:_BaseUser.DOC_IDS.CONFIG,darkMode:!1,likesConfetti:!1,sessionTimeLimit:5};try{let t=await this.localDB.get(_BaseUser.DOC_IDS.CONFIG);return logger.debug(`Raw config from DB:`,t),t}catch(c){let u=c;if(u.name&&u.name===`not_found`){if(!this.canMaterializeDefaults())throw Error(`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`);return await this.localDB.put(t),this.getConfig()}else throw logger.error(`Error setting user default config:`,c),Error(`Error returning the user's configuration: ${JSON.stringify(c)}`)}}async setConfig(t){logger.debug(`Setting Config items ${JSON.stringify(t)}`);let c=await this.getConfig(),u=await this.localDB.put({...c,...t});u.ok?logger.debug(`Config items set: ${JSON.stringify(t)}`):logger.error(`Error setting config items: ${JSON.stringify(u)}`)}static async instance(t,c){return c?(_BaseUser._instance=new _BaseUser(c,t),await _BaseUser._instance.init(),_BaseUser._instance):_BaseUser._instance&&_BaseUser._initialized?_BaseUser._instance:_BaseUser._instance?new Promise(t=>{(function waitForUser(){if(_BaseUser._initialized)return t(_BaseUser._instance);setTimeout(waitForUser,50)})()}):(_BaseUser._instance=new _BaseUser(await t.getCurrentUsername(),t),await _BaseUser._instance.init(),_BaseUser._instance)}constructor(t,c){_defineProperty$2(this,`_username`,void 0),_defineProperty$2(this,`syncStrategy`,void 0),_defineProperty$2(this,`localDB`,void 0),_defineProperty$2(this,`remoteDB`,void 0),_defineProperty$2(this,`writeDB`,void 0),_defineProperty$2(this,`updateQueue`,void 0),_defineProperty$2(this,`_hydration`,{state:`not-required`}),_defineProperty$2(this,`_hydrationPromise`,null),_defineProperty$2(this,`_hydratedSeq`,void 0),_BaseUser._initialized=!1,this._username=t,this.syncStrategy=c,this.setDBandQ()}setDBandQ(){this.localDB=getLocalUserDB(this._username),this.remoteDB=this.syncStrategy.setupRemoteDB(this._username),this.writeDB=this.syncStrategy.getWriteDB?this.syncStrategy.getWriteDB(this._username):this.localDB,this.updateQueue=new UpdateQueue(this.localDB,this.writeDB)}async init(){if(_BaseUser._initialized=!1,this._username===`admin`){_BaseUser._initialized=!0;return}this.syncStrategy.stopSync?.(),this.setDBandQ(),this._hydrationPromise=this.hydrateLocalMirror(),await this._hydrationPromise,this.syncStrategy.startSync(this.localDB,this.remoteDB,this._hydratedSeq),this.applyDesignDocs().catch(t=>{log4(`Error in applyDesignDocs background task: ${t}`),t&&typeof t==`object`&&log4(`Full error details in applyDesignDocs: ${JSON.stringify(t)}`)}),this.deduplicateReviews().catch(t=>{log4(`Error in deduplicateReviews background task: ${t}`),t&&typeof t==`object`&&log4(`Full error details in background task: ${JSON.stringify(t)}`)}),_BaseUser._initialized=!0}async hydrateLocalMirror(){if(this._hydratedSeq=void 0,this.localDB.name===this.remoteDB.name||!this.syncStrategy.hydrate){this._hydration={state:`not-required`};return}if(await this.hasHydrationMarker()){this._hydration={state:`stale`};return}this._hydration={state:`hydrating`};let t=Date.now();try{let{docsWritten:c,lastSeq:u}=await withTimeout(this.syncStrategy.hydrate(this.localDB,this.remoteDB),HYDRATION_TIMEOUT_MS,`Hydration of local mirror for ${this._username}`);this._hydratedSeq=u,await this.writeHydrationMarker(),this._hydration={state:`hydrated`,docsWritten:c,durationMs:Date.now()-t},log4(`Hydrated local mirror for ${this._username}: ${c} docs in ${this._hydration.durationMs}ms`)}catch(c){this.syncStrategy.stopSync?.(),this._hydration={state:`failed`,durationMs:Date.now()-t,error:c instanceof Error?c.message:String(c)},logger.error(`Failed to hydrate local mirror for ${this._username}:`,c)}}async hasHydrationMarker(){try{return(await this.localDB.get(HYDRATION_MARKER_ID)).username===this._username}catch{return!1}}async writeHydrationMarker(){try{let t;try{t=(await this.localDB.get(HYDRATION_MARKER_ID))._rev}catch{}await this.localDB.put({_id:HYDRATION_MARKER_ID,_rev:t,username:this._username,hydratedAt:new Date().toISOString()})}catch(t){logger.warn(`Could not write hydration marker for ${this._username}: ${t}`)}}async applyDesignDocs(){if(log4(`Starting applyDesignDocs for user: ${this._username}`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),this._username===`admin`){log4(`Skipping design docs for admin user`);return}log4(`Applying ${_BaseUser.designDocs.length} design docs`);for(let t of _BaseUser.designDocs){log4(`Applying design doc: ${t._id}`);try{try{let c=await this.remoteDB.get(t._id);await this.remoteDB.put({...t,_rev:c._rev})}catch(c){if(c?.name===`not_found`)await this.remoteDB.put(t);else throw c}}catch(c){if(c.name&&c.name===`conflict`)logger.warn(`Design doc ${t._id} update conflict - will retry`),await new Promise(t=>setTimeout(t,1e3)),await this.applyDesignDoc(t);else throw logger.error(`Failed to apply design doc ${t._id}:`,c),c}}}async applyDesignDoc(t,c=3){try{let c=await this.remoteDB.get(t._id);await this.remoteDB.put({...t,_rev:c._rev})}catch(u){if(u?.name===`conflict`&&c>0)return await new Promise(t=>setTimeout(t,1e3)),this.applyDesignDoc(t,c-1);throw u}}async putCardRecord(t){let c=getCardHistoryID(t.courseID,t.cardID);t.timeStamp=hooks.utc(t.timeStamp).toString();try{let u=await this.update(c,function(c){return c.records.push(t),c.bestInterval=c.bestInterval||0,areQuestionRecords(c)?(c.lapses=getLapses(c.records),c.streak=getStreak(c.records)):(c.lapses=c.lapses||0,c.streak=c.streak||0),c});return u.records=u.records.map(t=>{let c={...t};return c.timeStamp=hooks.utc(t.timeStamp),c}),u}catch(u){let d=u;if(d.status===404)try{let u={_id:c,cardID:t.cardID,courseID:t.courseID,records:[t],lapses:0,streak:0,bestInterval:0},d=await this.writeDB.put(u);return{...u,_rev:d.rev}}catch(t){throw Error(`Failed to create CardHistory for ${c}. Reason: ${t}`)}else throw Error(`putCardRecord failed because of:
429
+ Log out of account ${this.getUsername()} before logging in as ${t}.`);logger.warn(`User ${this._username} is already logged in, but executing login again.`)}let u=await this.syncStrategy.authenticate(t,c);if(u.ok){log4(`Logged in as ${t}`),this._username=t;try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}await this.init()}return u}async adoptSession(t){if(!this.syncStrategy.canAuthenticate()||!this.syncStrategy.adoptSession)throw Error(`Session adoption not supported by current sync strategy`);let c=this._username.startsWith(GuestUsername)?this._username:void 0;if(!c)throw Error(`Cannot adopt a session while logged in.
430
+ Log out of account ${this.getUsername()} first.`);let u=await this.syncStrategy.adoptSession(t.migrateGuestData?c:void 0);if(u.ok&&u.username){log4(`Adopted session for ${u.username}`),this._username=u.username;try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}await this.init()}return u}async resetUserData(){if(this.syncStrategy.canAuthenticate())return{status:Status.error,error:`Reset user data is only available for local-only mode. Use logout instead for remote sync.`};try{let t=getLocalUserDB(this._username),c=(await t.allDocs({include_docs:!1})).rows.filter(t=>{let c=t.id;return c.startsWith(DocTypePrefixes.CARDRECORD)||c.startsWith(DocTypePrefixes.SCHEDULED_CARD)||c.startsWith(DocTypePrefixes.STRATEGY_STATE)||c.startsWith(DocTypePrefixes.USER_OUTCOME)||c.startsWith(DocTypePrefixes.STRATEGY_LEARNING_STATE)||c===_BaseUser.DOC_IDS.COURSE_REGISTRATIONS||c===_BaseUser.DOC_IDS.CLASSROOM_REGISTRATIONS||c===_BaseUser.DOC_IDS.CONFIG}).map(t=>({_id:t.id,_rev:t.value.rev,_deleted:!0}));return c.length>0&&await t.bulkDocs(c),await this.init(),{status:Status.ok}}catch(t){return logger.error(`Failed to reset user data:`,t),{status:Status.error,error:t instanceof Error?t.message:`Unknown error during reset`}}}async logout(){if(!this.syncStrategy.canAuthenticate())return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),{ok:!0};let t=await this.syncStrategy.logout();try{localStorage.removeItem(`sk-guest-uuid`)}catch(t){logger.warn(`localStorage not available (Node.js environment):`,t)}return this._username=await this.syncStrategy.getCurrentUsername(),await this.init(),t}async get(t){return this.localDB.get(t)}update(t,c){return this.updateQueue.update(t,c)}async getCourseRegistrationsDoc(){logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);let t;try{return await this.localDB.get(_BaseUser.DOC_IDS.COURSE_REGISTRATIONS)}catch(c){if(c.status===404){if(!this.canMaterializeDefaults())throw Error(`Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc \u2014 that would report an existing user as unregistered, and then lose to their real document once sync resumes.`);await this.localDB.put({_id:_BaseUser.DOC_IDS.COURSE_REGISTRATIONS,courses:[],studyWeight:{}}),t=await this.getCourseRegistrationsDoc()}else throw Error(`Unexpected error ${JSON.stringify(c)} in getOrCreateCourseRegistrationDoc...`)}return t}async getActiveCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(t=>t.status===void 0||t.status===`active`)}async getActiveCards(){let t=getStartAndEndKeys2(DocTypePrefixes.SCHEDULED_CARD);return(await this.remoteDB.allDocs({startkey:t.startkey,endkey:t.endkey,include_docs:!0})).rows.map(t=>({courseID:t.doc.courseId,cardID:t.doc.cardId}))}async getActivityRecords(){try{let t=await this.getHistory(),c=[];if(!Array.isArray(t))return logger.error(`getHistory did not return an array:`,t),c;let u=0;for(let d=0;d<t.length;d++)try{t[d]&&Array.isArray(t[d].records)&&t[d].records.forEach(t=>{try{if(!t.timeStamp)return;let d;if(typeof t.timeStamp==`object`)if(typeof t.timeStamp.toDate==`function`)d=t.timeStamp.toISOString();else if(t.timeStamp instanceof Date)d=t.timeStamp.toISOString();else{u<3&&(logger.warn(`Unknown timestamp object type:`,t.timeStamp),u++);return}else if(typeof t.timeStamp==`string`){let c=new Date(t.timeStamp);if(isNaN(c.getTime()))return;d=t.timeStamp}else if(typeof t.timeStamp==`number`)d=new Date(t.timeStamp).toISOString();else return;c.push({timeStamp:d,courseID:t.courseID||`unknown`,cardID:t.cardID||`unknown`,timeSpent:t.timeSpent||0,type:`card_view`})}catch{}})}catch(t){logger.error(`Error processing history item:`,t)}return logger.debug(`Found ${c.length} activity records`),c}catch(t){return logger.error(`Error in getActivityRecords:`,t),[]}}async getReviewstoDate(t,c){let u=getStartAndEndKeys2(DocTypePrefixes.SCHEDULED_CARD),d=await this.remoteDB.allDocs({startkey:u.startkey,endkey:u.endkey,include_docs:!0});return log4(`Fetching ${this._username}'s scheduled reviews${c?` for course ${c}`:``}.`),d.rows.filter(u=>{if(u.id.startsWith(DocTypePrefixes.SCHEDULED_CARD)){let d=hooks.utc(u.id.substr(DocTypePrefixes.SCHEDULED_CARD.length),REVIEW_TIME_FORMAT2);if(t.isAfter(d)&&(c===void 0||u.doc.courseId===c))return!0}}).map(t=>t.doc)}async getReviewsForcast(t,c){let u=hooks.utc().add(t,`days`);return this.getReviewstoDate(u,c)}async getPendingReviews(t){let c=hooks.utc();return this.getReviewstoDate(c,t)}async getScheduledReviewCount(t){return(await this.getPendingReviews(t)).length}async getRegisteredCourses(){return(await this.getCourseRegistrationsDoc()).courses.filter(t=>!t.status||t.status===`active`||t.status===`maintenance-mode`)}async getCourseRegDoc(t){let c=(await this.getCourseRegistrationsDoc()).courses.find(c=>c.courseID===t);if(c)return c;throw Error(`Course registration not found for course ID: ${t}`)}async registerForCourse(t,c=!1){return this.getCourseRegistrationsDoc().then(u=>{let d=c?`preview`:`active`;logger.debug(`Registering for ${t} with status: ${d}`);let m={status:d,courseID:t,user:!0,admin:!1,moderator:!1,elo:{global:{score:1e3,count:0},tags:{},misc:{}}};return u.courses.filter(t=>t.courseID===m.courseID).length===0?(log4(`It's a new course registration!`),u.courses.push(m),u.studyWeight[t]=1):u.courses.forEach(c=>{log4(`Found the previously registered course!`),c.courseID===t&&(c.status=d)}),this.localDB.put(u)}).catch(t=>{throw log4(`Registration failed because of: ${JSON.stringify(t)}`),t})}async dropCourse(t,c=`dropped`){return this.getCourseRegistrationsDoc().then(u=>{let d=-1;for(let c=0;c<u.courses.length;c++)u.courses[c].courseID===t&&(d=c);if(d!==-1)delete u.studyWeight[t],u.courses[d].status=c;else throw Error(`User ${this.getUsername()} is not currently registered for course ${t}`);return this.localDB.put(u)})}async getCourseInterface(t){return new UsrCrsData(this,t)}async getUserEditableCourses(){let t=[],c=await this.getCourseRegistrationsDoc();return t=t.concat(c.courses.map(t=>t.courseID)),await Promise.all(t.map(async t=>await getCredentialledCourseConfig(t)))}async getConfig(){let t={_id:_BaseUser.DOC_IDS.CONFIG,darkMode:!1,likesConfetti:!1,sessionTimeLimit:5};try{let t=await this.localDB.get(_BaseUser.DOC_IDS.CONFIG);return logger.debug(`Raw config from DB:`,t),t}catch(c){let u=c;if(u.name&&u.name===`not_found`){if(!this.canMaterializeDefaults())throw Error(`Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`);return await this.localDB.put(t),this.getConfig()}else throw logger.error(`Error setting user default config:`,c),Error(`Error returning the user's configuration: ${JSON.stringify(c)}`)}}async setConfig(t){logger.debug(`Setting Config items ${JSON.stringify(t)}`);let c=await this.getConfig(),u=await this.localDB.put({...c,...t});u.ok?logger.debug(`Config items set: ${JSON.stringify(t)}`):logger.error(`Error setting config items: ${JSON.stringify(u)}`)}static async instance(t,c){return c?(_BaseUser._instance=new _BaseUser(c,t),await _BaseUser._instance.init(),_BaseUser._instance):_BaseUser._instance&&_BaseUser._initialized?_BaseUser._instance:_BaseUser._instance?new Promise(t=>{(function waitForUser(){if(_BaseUser._initialized)return t(_BaseUser._instance);setTimeout(waitForUser,50)})()}):(_BaseUser._instance=new _BaseUser(await t.getCurrentUsername(),t),await _BaseUser._instance.init(),_BaseUser._instance)}constructor(t,c){_defineProperty$2(this,`_username`,void 0),_defineProperty$2(this,`syncStrategy`,void 0),_defineProperty$2(this,`localDB`,void 0),_defineProperty$2(this,`remoteDB`,void 0),_defineProperty$2(this,`writeDB`,void 0),_defineProperty$2(this,`updateQueue`,void 0),_defineProperty$2(this,`_hydration`,{state:`not-required`}),_defineProperty$2(this,`_hydrationPromise`,null),_defineProperty$2(this,`_hydratedSeq`,void 0),_BaseUser._initialized=!1,this._username=t,this.syncStrategy=c,this.setDBandQ()}setDBandQ(){this.localDB=getLocalUserDB(this._username),this.remoteDB=this.syncStrategy.setupRemoteDB(this._username),this.writeDB=this.syncStrategy.getWriteDB?this.syncStrategy.getWriteDB(this._username):this.localDB,this.updateQueue=new UpdateQueue(this.localDB,this.writeDB)}async init(){if(_BaseUser._initialized=!1,this._username===`admin`){_BaseUser._initialized=!0;return}this.syncStrategy.stopSync?.(),this.setDBandQ(),this._hydrationPromise=this.hydrateLocalMirror(),await this._hydrationPromise,this.syncStrategy.startSync(this.localDB,this.remoteDB,this._hydratedSeq),this.applyDesignDocs().catch(t=>{log4(`Error in applyDesignDocs background task: ${t}`),t&&typeof t==`object`&&log4(`Full error details in applyDesignDocs: ${JSON.stringify(t)}`)}),this.deduplicateReviews().catch(t=>{log4(`Error in deduplicateReviews background task: ${t}`),t&&typeof t==`object`&&log4(`Full error details in background task: ${JSON.stringify(t)}`)}),_BaseUser._initialized=!0}async hydrateLocalMirror(){if(this._hydratedSeq=void 0,this.localDB.name===this.remoteDB.name||!this.syncStrategy.hydrate){this._hydration={state:`not-required`};return}if(await this.hasHydrationMarker()){this._hydration={state:`stale`};return}this._hydration={state:`hydrating`};let t=Date.now();try{let{docsWritten:c,lastSeq:u}=await withTimeout(this.syncStrategy.hydrate(this.localDB,this.remoteDB),HYDRATION_TIMEOUT_MS,`Hydration of local mirror for ${this._username}`);this._hydratedSeq=u,await this.writeHydrationMarker(),this._hydration={state:`hydrated`,docsWritten:c,durationMs:Date.now()-t},log4(`Hydrated local mirror for ${this._username}: ${c} docs in ${this._hydration.durationMs}ms`)}catch(c){this.syncStrategy.stopSync?.(),this._hydration={state:`failed`,durationMs:Date.now()-t,error:c instanceof Error?c.message:String(c)},logger.error(`Failed to hydrate local mirror for ${this._username}:`,c)}}async hasHydrationMarker(){try{return(await this.localDB.get(HYDRATION_MARKER_ID)).username===this._username}catch{return!1}}async writeHydrationMarker(){try{let t;try{t=(await this.localDB.get(HYDRATION_MARKER_ID))._rev}catch{}await this.localDB.put({_id:HYDRATION_MARKER_ID,_rev:t,username:this._username,hydratedAt:new Date().toISOString()})}catch(t){logger.warn(`Could not write hydration marker for ${this._username}: ${t}`)}}async applyDesignDocs(){if(log4(`Starting applyDesignDocs for user: ${this._username}`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),this._username===`admin`){log4(`Skipping design docs for admin user`);return}log4(`Applying ${_BaseUser.designDocs.length} design docs`);for(let t of _BaseUser.designDocs){log4(`Applying design doc: ${t._id}`);try{try{let c=await this.remoteDB.get(t._id);await this.remoteDB.put({...t,_rev:c._rev})}catch(c){if(c?.name===`not_found`)await this.remoteDB.put(t);else throw c}}catch(c){if(c.name&&c.name===`conflict`)logger.warn(`Design doc ${t._id} update conflict - will retry`),await new Promise(t=>setTimeout(t,1e3)),await this.applyDesignDoc(t);else throw logger.error(`Failed to apply design doc ${t._id}:`,c),c}}}async applyDesignDoc(t,c=3){try{let c=await this.remoteDB.get(t._id);await this.remoteDB.put({...t,_rev:c._rev})}catch(u){if(u?.name===`conflict`&&c>0)return await new Promise(t=>setTimeout(t,1e3)),this.applyDesignDoc(t,c-1);throw u}}async putCardRecord(t){let c=getCardHistoryID(t.courseID,t.cardID);t.timeStamp=hooks.utc(t.timeStamp).toString();try{let u=await this.update(c,function(c){return c.records.push(t),c.bestInterval=c.bestInterval||0,areQuestionRecords(c)?(c.lapses=getLapses(c.records),c.streak=getStreak(c.records)):(c.lapses=c.lapses||0,c.streak=c.streak||0),c});return u.records=u.records.map(t=>{let c={...t};return c.timeStamp=hooks.utc(t.timeStamp),c}),u}catch(u){let d=u;if(d.status===404)try{let u={_id:c,cardID:t.cardID,courseID:t.courseID,records:[t],lapses:0,streak:0,bestInterval:0},d=await this.writeDB.put(u);return{...u,_rev:d.rev}}catch(t){throw Error(`Failed to create CardHistory for ${c}. Reason: ${t}`)}else throw Error(`putCardRecord failed because of:
430
431
  name:${d.name}
431
432
  error: ${d.error}
432
433
  message: ${d.message}`)}}async deduplicateReviews(){try{log4(`Starting deduplication of scheduled reviews...`),log4(`Remote DB name: ${this.remoteDB.name||`unknown`}`),log4(`Write DB name: ${this.writeDB.name||`unknown`}`);let t={},c=[];log4(`Attempting to query remoteDB for reviewCards/reviewCards. Database: ${this.remoteDB.name||`unknown`}`);let u=await this.remoteDB.query(`reviewCards/reviewCards`);if(log4(`Found ${u.rows.length} scheduled reviews to process`),u.rows.forEach(u=>{let d=u.value,m=u.key;t[d]?(log4(`Found duplicate scheduled review for card: ${d}`),log4(`Marking earlier review ${t[d]} for deletion, keeping ${m}`),c.push(t[d]),t[d]=m):t[d]=m}),c.length>0){log4(`Removing ${c.length} duplicate reviews...`);let t=c.map(async t=>{try{let c=await this.remoteDB.get(t);await this.writeDB.remove(c),log4(`Successfully removed duplicate review: ${t}`)}catch(c){log4(`Failed to remove duplicate review ${t}: ${c}`)}});await Promise.all(t),log4(`Deduplication complete. Processed ${c.length} duplicates`)}else log4(`No duplicate reviews found`)}catch(t){log4(`Error during review deduplication: ${t}`),t&&typeof t==`object`&&`status`in t&&t.status===404&&(log4(`Database not found (404) during review deduplication. Database: ${this.remoteDB.name||`unknown`}`),log4(`This might indicate the user database doesn't exist or the reviewCards view isn't available`)),t&&typeof t==`object`&&log4(`Full error details: ${JSON.stringify(t)}`)}}async getSeenCards(t){let c=DocTypePrefixes.CARDRECORD;t&&(c+=`-${t}-`);let u=await filterAllDocsByPrefix2(this.localDB,c,{include_docs:!1}),d=[];return u.rows.forEach(t=>{t.id.startsWith(c)&&d.push(t.id.substr(c.length))}),d}async getHistory(){return(await filterAllDocsByPrefix2(this.remoteDB,DocTypePrefixes.CARDRECORD,{include_docs:!0,attachments:!1})).rows.map(t=>t.doc)}async updateCourseSettings(t,c){this.getCourseRegistrationsDoc().then(u=>{let d=u.courses.find(c=>c.courseID===t);return d&&((d.settings===null||d.settings===void 0)&&(d.settings={}),c.forEach(t=>{d.settings[t.key]=t.value})),this.localDB.put(u)})}async getCourseSettings(t){let c=(await this.getCourseRegistrationsDoc()).courses.find(c=>c.courseID===t);if(c)return c.settings;throw Error(`getCourseSettings Failed:
@@ -477,11 +478,11 @@ Displayable Constructor was called with no view Data.
477
478
  Card was displayed at ${t.timeStamp}
478
479
  User spent ${t.timeSpent} milliseconds with the card.
479
480
  `),this.$emit(`emitResponse`,t)}}}),__name(_sfc_render$17,`_sfc_render`),Q$1=F$3(ct$1,[[`render`,_sfc_render$17],[`__scopeId`,`data-v-2d892b82`]]),lt$1=defineComponent({name:`SessionControllerDebug`,props:{sessionController:{type:Object,required:!0}},setup(t){let c=ref(0),u=null;onMounted(()=>{u=setInterval(()=>{c.value++},500)}),onUnmounted(()=>{u&&clearInterval(u)});let d=computed(()=>(c.value,t.sessionController?t.sessionController.getDebugInfo():{supplyQueue:{length:0,dequeueCount:0,items:[]},failedQueue:{length:0,dequeueCount:0,items:[]},hydratedCache:{count:0,failedCacheSize:0,items:[]}})),fmtScore=t=>t===void 0?``:Number.isFinite(t)?t.toFixed(2):`REQ`;return{debugInfo:d,fmtScore}}}),ut$1={class:`debug-section`},dt$1={class:`debug-header`},ft$1={class:`debug-stats`},pt$1={class:`text-caption`},mt$1={class:`text-caption ml-2`},ht$1={key:0,class:`debug-items`},gt$1={class:`text-caption`},_t={class:`text-caption text-grey ml-1`},vt$1={class:`text-caption ml-1`,style:{color:`#90caf9`}},yt={key:0,class:`text-caption text-grey`},bt={key:1,class:`text-caption text-grey`},xt={class:`debug-section`},St={class:`debug-header`},Ct={class:`debug-stats`},wt={class:`text-caption`},Tt={class:`text-caption ml-2`},Et={key:0,class:`debug-items`},Dt={class:`text-caption`},Ot={class:`text-caption text-grey ml-1`},kt={key:0,class:`text-caption text-grey`},At={key:1,class:`text-caption text-grey`},jt={class:`debug-section`},Mt={class:`debug-header`},Nt={class:`debug-stats`},Pt={class:`text-caption`},Ft={class:`text-caption ml-2`},It={key:0,class:`debug-items`},Lt={class:`text-caption`},Rt={key:0,class:`text-caption text-grey`},zt={key:1,class:`text-caption text-grey`},__name(_sfc_render$16,`_sfc_render`),Bt=F$3(lt$1,[[`render`,_sfc_render$16],[`__scopeId`,`data-v-641ac170`]]),Vt={},(function main(t,c,u,d){var m=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),g=typeof Path2D==`function`&&typeof DOMMatrix==`function`,b=(function(){if(!t.OffscreenCanvas)return!1;var c=new OffscreenCanvas(1,1),u=c.getContext(`2d`);u.fillRect(0,0,1,1);var d=c.transferToImageBitmap();try{u.createPattern(d,`no-repeat`)}catch{return!1}return!0})();function noop(){}function promise(u){var d=c.exports.Promise,m=d===void 0?t.Promise:d;return typeof m==`function`?new m(u):(u(noop,noop),null)}var S=(function(t,c){return{transform:function(u){if(t)return u;if(c.has(u))return c.get(u);var d=new OffscreenCanvas(u.width,u.height);return d.getContext(`2d`).drawImage(u,0,0),c.set(u,d),d},clear:function(){c.clear()}}})(b,new Map),C=function(){var t=16,frame,cancel,c={},u=0;return typeof requestAnimationFrame==`function`&&typeof cancelAnimationFrame==`function`?(frame=function(d){var m=Math.random();return c[m]=requestAnimationFrame(function onFrame(g){u===g||u+t-1<g?(u=g,delete c[m],d()):c[m]=requestAnimationFrame(onFrame)}),m},cancel=function(t){c[t]&&cancelAnimationFrame(c[t])}):(frame=function(c){return setTimeout(c,t)},cancel=function(t){return clearTimeout(t)}),{frame,cancel}}(),w=(function(){var t,c,d={};function decorate(t){function execute(c,u){t.postMessage({options:c||{},callback:u})}t.init=function initWorker(c){var u=c.transferControlToOffscreen();t.postMessage({canvas:u},[u])},t.fire=function fireWorker(u,m,g){if(c)return execute(u,null),c;var b=Math.random().toString(36).slice(2);return c=promise(function(m){function workerDone(u){u.data.callback===b&&(delete d[b],t.removeEventListener(`message`,workerDone),c=null,S.clear(),g(),m())}t.addEventListener(`message`,workerDone),execute(u,b),d[b]=workerDone.bind(null,{data:{callback:b}})}),c},t.reset=function resetWorker(){for(var c in t.postMessage({reset:!0}),d)d[c](),delete d[c]}}return function(){if(t)return t;if(!u&&m){var c=[`var CONFETTI, SIZE = {}, module = {};`,`(`+main.toString()+`)(this, module, true, SIZE);`,`onmessage = function(msg) {`,` if (msg.data.options) {`,` CONFETTI(msg.data.options).then(function () {`,` if (msg.data.callback) {`,` postMessage({ callback: msg.data.callback });`,` }`,` });`,` } else if (msg.data.reset) {`,` CONFETTI && CONFETTI.reset();`,` } else if (msg.data.resize) {`,` SIZE.width = msg.data.resize.width;`,` SIZE.height = msg.data.resize.height;`,` } else if (msg.data.canvas) {`,` SIZE.width = msg.data.canvas.width;`,` SIZE.height = msg.data.canvas.height;`,` CONFETTI = module.exports.create(msg.data.canvas);`,` }`,`}`].join(`
480
- `);try{t=new Worker(URL.createObjectURL(new Blob([c])))}catch(t){return typeof console.warn==`function`&&console.warn(`🎊 Could not load worker`,t),null}decorate(t)}return t}})(),T={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:[`square`,`circle`],zIndex:100,colors:[`#26ccff`,`#a25afd`,`#ff5e7e`,`#88ff5a`,`#fcff42`,`#ffa62d`,`#ff36ff`],disableForReducedMotion:!1,scalar:1};function convert(t,c){return c?c(t):t}function isOk(t){return t!=null}function prop(t,c,u){return convert(t&&isOk(t[c])?t[c]:T[c],u)}function onlyPositiveInt(t){return t<0?0:Math.floor(t)}function randomInt(t,c){return Math.floor(Math.random()*(c-t))+t}function toDecimal(t){return parseInt(t,16)}function colorsToRgb(t){return t.map(hexToRgb)}function hexToRgb(t){var c=String(t).replace(/[^0-9a-f]/gi,``);return c.length<6&&(c=c[0]+c[0]+c[1]+c[1]+c[2]+c[2]),{r:toDecimal(c.substring(0,2)),g:toDecimal(c.substring(2,4)),b:toDecimal(c.substring(4,6))}}function getOrigin(t){var c=prop(t,`origin`,Object);return c.x=prop(c,`x`,Number),c.y=prop(c,`y`,Number),c}function setCanvasWindowSize(t){t.width=document.documentElement.clientWidth,t.height=document.documentElement.clientHeight}function setCanvasRectSize(t){var c=t.getBoundingClientRect();t.width=c.width,t.height=c.height}function getCanvas(t){var c=document.createElement(`canvas`);return c.style.position=`fixed`,c.style.top=`0px`,c.style.left=`0px`,c.style.pointerEvents=`none`,c.style.zIndex=t,c}function ellipse(t,c,u,d,m,g,b,S,C){t.save(),t.translate(c,u),t.rotate(g),t.scale(d,m),t.arc(0,0,1,b,S,C),t.restore()}function randomPhysics(t){var c=t.angle*(Math.PI/180),u=t.spread*(Math.PI/180);return{x:t.x,y:t.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:t.startVelocity*.5+Math.random()*t.startVelocity,angle2D:-c+(.5*u-Math.random()*u),tiltAngle:(Math.random()*.5+.25)*Math.PI,color:t.color,shape:t.shape,tick:0,totalTicks:t.ticks,decay:t.decay,drift:t.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:t.gravity*3,ovalScalar:.6,scalar:t.scalar,flat:t.flat}}function updateFetti(t,c){c.x+=Math.cos(c.angle2D)*c.velocity+c.drift,c.y+=Math.sin(c.angle2D)*c.velocity+c.gravity,c.velocity*=c.decay,c.flat?(c.wobble=0,c.wobbleX=c.x+10*c.scalar,c.wobbleY=c.y+10*c.scalar,c.tiltSin=0,c.tiltCos=0,c.random=1):(c.wobble+=c.wobbleSpeed,c.wobbleX=c.x+10*c.scalar*Math.cos(c.wobble),c.wobbleY=c.y+10*c.scalar*Math.sin(c.wobble),c.tiltAngle+=.1,c.tiltSin=Math.sin(c.tiltAngle),c.tiltCos=Math.cos(c.tiltAngle),c.random=Math.random()+2);var u=c.tick++/c.totalTicks,d=c.x+c.random*c.tiltCos,m=c.y+c.random*c.tiltSin,b=c.wobbleX+c.random*c.tiltCos,C=c.wobbleY+c.random*c.tiltSin;if(t.fillStyle=`rgba(`+c.color.r+`, `+c.color.g+`, `+c.color.b+`, `+(1-u)+`)`,t.beginPath(),g&&c.shape.type===`path`&&typeof c.shape.path==`string`&&Array.isArray(c.shape.matrix))t.fill(transformPath2D(c.shape.path,c.shape.matrix,c.x,c.y,Math.abs(b-d)*.1,Math.abs(C-m)*.1,Math.PI/10*c.wobble));else if(c.shape.type===`bitmap`){var w=Math.PI/10*c.wobble,T=Math.abs(b-d)*.1,E=Math.abs(C-m)*.1,D=c.shape.bitmap.width*c.scalar,O=c.shape.bitmap.height*c.scalar,xr=new DOMMatrix([Math.cos(w)*T,Math.sin(w)*T,-Math.sin(w)*E,Math.cos(w)*E,c.x,c.y]);xr.multiplySelf(new DOMMatrix(c.shape.matrix));var Sr=t.createPattern(S.transform(c.shape.bitmap),`no-repeat`);Sr.setTransform(xr),t.globalAlpha=1-u,t.fillStyle=Sr,t.fillRect(c.x-D/2,c.y-O/2,D,O),t.globalAlpha=1}else if(c.shape===`circle`)t.ellipse?t.ellipse(c.x,c.y,Math.abs(b-d)*c.ovalScalar,Math.abs(C-m)*c.ovalScalar,Math.PI/10*c.wobble,0,2*Math.PI):ellipse(t,c.x,c.y,Math.abs(b-d)*c.ovalScalar,Math.abs(C-m)*c.ovalScalar,Math.PI/10*c.wobble,0,2*Math.PI);else if(c.shape===`star`)for(var Cr=Math.PI/2*3,wr=4*c.scalar,Tr=8*c.scalar,Er=c.x,Dr=c.y,Or=5,kr=Math.PI/Or;Or--;)Er=c.x+Math.cos(Cr)*Tr,Dr=c.y+Math.sin(Cr)*Tr,t.lineTo(Er,Dr),Cr+=kr,Er=c.x+Math.cos(Cr)*wr,Dr=c.y+Math.sin(Cr)*wr,t.lineTo(Er,Dr),Cr+=kr;else t.moveTo(Math.floor(c.x),Math.floor(c.y)),t.lineTo(Math.floor(c.wobbleX),Math.floor(m)),t.lineTo(Math.floor(b),Math.floor(C)),t.lineTo(Math.floor(d),Math.floor(c.wobbleY));return t.closePath(),t.fill(),c.tick<c.totalTicks}function animate(t,c,m,g,b){var w=c.slice(),T=t.getContext(`2d`),E,D,O=promise(function(c){function onDone(){E=D=null,T.clearRect(0,0,g.width,g.height),S.clear(),b(),c()}function update(){u&&!(g.width===d.width&&g.height===d.height)&&(g.width=t.width=d.width,g.height=t.height=d.height),!g.width&&!g.height&&(m(t),g.width=t.width,g.height=t.height),T.clearRect(0,0,g.width,g.height),w=w.filter(function(t){return updateFetti(T,t)}),w.length?E=C.frame(update):onDone()}E=C.frame(update),D=onDone});return{addFettis:function(t){return w=w.concat(t),O},canvas:t,promise:O,reset:function(){E&&C.cancel(E),D&&D()}}}function confettiCannon(c,u){var d=!c,g=!!prop(u||{},`resize`),b=!1,S=prop(u,`disableForReducedMotion`,Boolean),C=m&&prop(u||{},`useWorker`)?w():null,T=d?setCanvasWindowSize:setCanvasRectSize,E=c&&C?!!c.__confetti_initialized:!1,D=typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion)`).matches,O;function fireLocal(t,u,d){for(var m=prop(t,`particleCount`,onlyPositiveInt),g=prop(t,`angle`,Number),b=prop(t,`spread`,Number),S=prop(t,`startVelocity`,Number),C=prop(t,`decay`,Number),w=prop(t,`gravity`,Number),E=prop(t,`drift`,Number),D=prop(t,`colors`,colorsToRgb),xr=prop(t,`ticks`,Number),Sr=prop(t,`shapes`),Cr=prop(t,`scalar`),wr=!!prop(t,`flat`),Tr=getOrigin(t),Er=m,Dr=[],Or=c.width*Tr.x,kr=c.height*Tr.y;Er--;)Dr.push(randomPhysics({x:Or,y:kr,angle:g,spread:b,startVelocity:S,color:D[Er%D.length],shape:Sr[randomInt(0,Sr.length)],ticks:xr,decay:C,gravity:w,drift:E,scalar:Cr,flat:wr}));return O?O.addFettis(Dr):(O=animate(c,Dr,T,u,d),O.promise)}function fire(u){var m=S||prop(u,`disableForReducedMotion`,Boolean),w=prop(u,`zIndex`,Number);if(m&&D)return promise(function(t){t()});d&&O?c=O.canvas:d&&!c&&(c=getCanvas(w),document.body.appendChild(c)),g&&!E&&T(c);var xr={width:c.width,height:c.height};C&&!E&&C.init(c),E=!0,C&&(c.__confetti_initialized=!0);function onResize(){if(C){var t={getBoundingClientRect:function(){if(!d)return c.getBoundingClientRect()}};T(t),C.postMessage({resize:{width:t.width,height:t.height}});return}xr.width=xr.height=null}function done(){O=null,g&&(b=!1,t.removeEventListener(`resize`,onResize)),d&&c&&(document.body.contains(c)&&document.body.removeChild(c),c=null,E=!1)}return g&&!b&&(b=!0,t.addEventListener(`resize`,onResize,!1)),C?C.fire(u,xr,done):fireLocal(u,xr,done)}return fire.reset=function(){C&&C.reset(),O&&O.reset()},fire}var E;function getDefaultFire(){return E||(E=confettiCannon(null,{useWorker:!0,resize:!0})),E}function transformPath2D(t,c,u,d,m,g,b){var S=new Path2D(t),C=new Path2D;C.addPath(S,new DOMMatrix(c));var w=new Path2D;return w.addPath(C,new DOMMatrix([Math.cos(b)*m,Math.sin(b)*m,-Math.sin(b)*g,Math.cos(b)*g,u,d])),w}function shapeFromPath(t){if(!g)throw Error(`path confetti are not supported in this browser`);var c,u;typeof t==`string`?c=t:(c=t.path,u=t.matrix);var d=new Path2D(c),m=document.createElement(`canvas`).getContext(`2d`);if(!u){for(var b=1e3,S=b,C=b,w=0,T=0,E,D,O=0;O<b;O+=2)for(var xr=0;xr<b;xr+=2)m.isPointInPath(d,O,xr,`nonzero`)&&(S=Math.min(S,O),C=Math.min(C,xr),w=Math.max(w,O),T=Math.max(T,xr));E=w-S,D=T-C;var Sr=10,Cr=Math.min(Sr/E,Sr/D);u=[Cr,0,0,Cr,-Math.round(E/2+S)*Cr,-Math.round(D/2+C)*Cr]}return{type:`path`,path:c,matrix:u}}function shapeFromText(t){var c,u=1,d=`#000000`,m=`"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif`;typeof t==`string`?c=t:(c=t.text,u=`scalar`in t?t.scalar:u,m=`fontFamily`in t?t.fontFamily:m,d=`color`in t?t.color:d);var g=10*u,b=``+g+`px `+m,S=new OffscreenCanvas(g,g),C=S.getContext(`2d`);C.font=b;var w=C.measureText(c),T=Math.ceil(w.actualBoundingBoxRight+w.actualBoundingBoxLeft),E=Math.ceil(w.actualBoundingBoxAscent+w.actualBoundingBoxDescent),D=2,O=w.actualBoundingBoxLeft+D,xr=w.actualBoundingBoxAscent+D;T+=D+D,E+=D+D,S=new OffscreenCanvas(T,E),C=S.getContext(`2d`),C.font=b,C.fillStyle=d,C.fillText(c,O,xr);var Sr=1/u;return{type:`bitmap`,bitmap:S.transferToImageBitmap(),matrix:[Sr,0,0,Sr,-T*Sr/2,-E*Sr/2]}}c.exports=function(){return getDefaultFire().apply(this,arguments)},c.exports.reset=function(){getDefaultFire().reset()},c.exports.create=confettiCannon,c.exports.shapeFromPath=shapeFromPath,c.exports.shapeFromText=shapeFromText})((function(){return typeof window<`u`?window:typeof self<`u`?self:this||{}})(),Vt,!1),Ht=Vt.exports,Vt.exports.create,Ut=defineComponent({name:`StudySession`,ref:{},components:{CardViewer:Q$1,StudySessionTimer:st$1,SkMouseTrap:Ne$1,HeatMap:Ae$1,SessionControllerDebug:Bt},props:{sessionTimeLimit:{type:Number,required:!0},contentSources:{type:Array,required:!0},user:{type:Object,required:!0},dataLayer:{type:Object,required:!0},sessionConfig:{type:Object,default:()=>({likesConfetti:!1})},getViewComponent:{type:Function,required:!0},frameless:{type:Boolean,default:!1},hideFooter:{type:Boolean,default:!1},transitionName:{type:String,default:`component-fade`},transitionMode:{type:String,default:`out-in`}},emits:[`session-finished`,`session-started`,`card-loaded`,`card-response`,`time-changed`,`session-prepared`,`session-error`,`replan-requested`],data(){return{cardID:``,view:null,data:[],courseID:``,card_elo:1e3,courseNames:{},cardCount:1,sessionController:null,sessionPrepared:!1,sessionFinished:!1,sessionRecord:[],percentageRemaining:100,timerIsActive:!0,loading:!1,userCourseRegDoc:null,sessionContentSources:[],timeRemaining:300,replanPending:!1,replanOptions:null,deferredNextCardAction:null,intervalHandler:null,cardType:``,debugMode:window.debugMode===!0}},computed:{currentCard(){return this.sessionRecord[this.sessionRecord.length-1]},resolvedTransitionMode(){return this.transitionMode===`default`?void 0:this.transitionMode}},async created(){this.userCourseRegDoc=await this.user.getCourseRegistrationsDoc(),console.log(`[StudySession] Created lifecycle hook - starting initSession`),await this.initSession(),console.log(`[StudySession] InitSession completed in created hook`)},beforeUnmount(){this.sessionController&&!this.sessionFinished&&this.sessionController.endSession(`abandoned`),this.intervalHandler&&clearInterval(this.intervalHandler)},errorCaptured(t,c,u){return console.error(`[StudySession] Card render error (${u}), skipping card "${this.cardID}":`,t),this.sessionController&&this.sessionController.nextCard().then(t=>this.loadCard(t)),!1},methods:{async handleReadyToAdvance(){let t=this.deferredNextCardAction;if(!t){console.warn(`[StudySession] ready-to-advance received but no deferred action stashed — ignoring`);return}console.log(`[StudySession] ready-to-advance received — advancing with stashed action: ${t}`),this.deferredNextCardAction=null,this.loadCard(await this.sessionController.nextCard(t))},handleReplanRequest(t){if(this.sessionController){let c=t?.label,u=c?` [${c}]`:``;console.log(`[StudySession] Replan requested by card view${u}, deferring until after response processing`),this.replanPending=!0,this.replanOptions=t??null}},user_elo(t){let c=this.userCourseRegDoc.courses.find(c=>c.courseID===t);return toCourseElo(c?c.elo:void 0)},handleClassroomMessage(){return t=>(Z$2({text:this.user?.getUsername()||`[Unknown user]`,status:Status.ok}),console.log(`[StudySession] There was a change in the classroom DB:`),console.log(`[StudySession] change: ${t}`),console.log(`[StudySession] Stringified change: ${JSON.stringify(t)}`),{})},incrementSessionClock(){let t=60*this.sessionTimeLimit-this.timeRemaining;this.sessionController.addTime(Math.min(t,60)),this.tick()},tick(){this.timeRemaining=this.sessionController.secondsRemaining,this.percentageRemaining=this.timeRemaining>60?100*(this.timeRemaining/(60*this.sessionTimeLimit)):100*(this.timeRemaining/60),this.$emit(`time-changed`,this.timeRemaining),this.timeRemaining===0&&clearInterval(this.intervalHandler)},async initSession(){let t=[];try{console.log(`[StudySession] starting study session w/ sources: ${JSON.stringify(this.contentSources)}`),console.log(`[StudySession] Beginning preparation process`),this.sessionContentSources=markRaw((await Promise.all(this.contentSources.map(async t=>{try{return await getStudySource(t,this.user)}catch(c){return console.error(`Failed to load study source: ${t.type}/${t.id}`,c),null}}))).filter(t=>t!==null)),this.timeRemaining=this.sessionTimeLimit*60,t=await Promise.all(this.contentSources.filter(t=>t.type===`classroom`).map(async t=>await this.dataLayer.getClassroomDB(t.id,`student`))),t.forEach(t=>{});let c={};this.sessionConfig?.defaultBatchLimit!==void 0&&(c.defaultBatchLimit=this.sessionConfig.defaultBatchLimit),this.sessionConfig?.outcomeObservers?.length&&(c.outcomeObservers=this.sessionConfig.outcomeObservers);let u=this.contentSources.find(t=>t.type===`course`)?.id;u&&(c.courseId=u),this.sessionConfig?.sessionStateSnapshot&&(c.stateSnapshotProvider=this.sessionConfig.sessionStateSnapshot),this.sessionController=markRaw(new SessionController(this.sessionContentSources,60*this.sessionTimeLimit,this.dataLayer,this.getViewComponent,void 0,c)),this.sessionController.sessionRecord=this.sessionRecord,this.sessionConfig?.initHints&&(this.sessionController.setSessionHints(this.sessionConfig.initHints),console.log(`[StudySession] Applied init hints as session-durable hints`)),await this.sessionController.prepareSession(),this.intervalHandler=setInterval(this.tick,1e3),this.sessionPrepared=!0,console.log(`[StudySession] Session preparation complete, emitting session-prepared event`),this.$emit(`session-prepared`),console.log(`[StudySession] Event emission completed`)}catch(t){console.error(`[StudySession] Error during session preparation:`,t),this.$emit(`session-error`,{message:`Failed to prepare study session`,error:t})}try{this.contentSources.filter(t=>t.type===`course`).forEach(async t=>this.courseNames[t.id]=(await this.dataLayer.getCoursesDB().getCourseConfig(t.id)).name),console.log(`[StudySession] Session created:
481
+ `);try{t=new Worker(URL.createObjectURL(new Blob([c])))}catch(t){return typeof console.warn==`function`&&console.warn(`🎊 Could not load worker`,t),null}decorate(t)}return t}})(),T={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:[`square`,`circle`],zIndex:100,colors:[`#26ccff`,`#a25afd`,`#ff5e7e`,`#88ff5a`,`#fcff42`,`#ffa62d`,`#ff36ff`],disableForReducedMotion:!1,scalar:1};function convert(t,c){return c?c(t):t}function isOk(t){return t!=null}function prop(t,c,u){return convert(t&&isOk(t[c])?t[c]:T[c],u)}function onlyPositiveInt(t){return t<0?0:Math.floor(t)}function randomInt(t,c){return Math.floor(Math.random()*(c-t))+t}function toDecimal(t){return parseInt(t,16)}function colorsToRgb(t){return t.map(hexToRgb)}function hexToRgb(t){var c=String(t).replace(/[^0-9a-f]/gi,``);return c.length<6&&(c=c[0]+c[0]+c[1]+c[1]+c[2]+c[2]),{r:toDecimal(c.substring(0,2)),g:toDecimal(c.substring(2,4)),b:toDecimal(c.substring(4,6))}}function getOrigin(t){var c=prop(t,`origin`,Object);return c.x=prop(c,`x`,Number),c.y=prop(c,`y`,Number),c}function setCanvasWindowSize(t){t.width=document.documentElement.clientWidth,t.height=document.documentElement.clientHeight}function setCanvasRectSize(t){var c=t.getBoundingClientRect();t.width=c.width,t.height=c.height}function getCanvas(t){var c=document.createElement(`canvas`);return c.style.position=`fixed`,c.style.top=`0px`,c.style.left=`0px`,c.style.pointerEvents=`none`,c.style.zIndex=t,c}function ellipse(t,c,u,d,m,g,b,S,C){t.save(),t.translate(c,u),t.rotate(g),t.scale(d,m),t.arc(0,0,1,b,S,C),t.restore()}function randomPhysics(t){var c=t.angle*(Math.PI/180),u=t.spread*(Math.PI/180);return{x:t.x,y:t.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:t.startVelocity*.5+Math.random()*t.startVelocity,angle2D:-c+(.5*u-Math.random()*u),tiltAngle:(Math.random()*.5+.25)*Math.PI,color:t.color,shape:t.shape,tick:0,totalTicks:t.ticks,decay:t.decay,drift:t.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:t.gravity*3,ovalScalar:.6,scalar:t.scalar,flat:t.flat}}function updateFetti(t,c){c.x+=Math.cos(c.angle2D)*c.velocity+c.drift,c.y+=Math.sin(c.angle2D)*c.velocity+c.gravity,c.velocity*=c.decay,c.flat?(c.wobble=0,c.wobbleX=c.x+10*c.scalar,c.wobbleY=c.y+10*c.scalar,c.tiltSin=0,c.tiltCos=0,c.random=1):(c.wobble+=c.wobbleSpeed,c.wobbleX=c.x+10*c.scalar*Math.cos(c.wobble),c.wobbleY=c.y+10*c.scalar*Math.sin(c.wobble),c.tiltAngle+=.1,c.tiltSin=Math.sin(c.tiltAngle),c.tiltCos=Math.cos(c.tiltAngle),c.random=Math.random()+2);var u=c.tick++/c.totalTicks,d=c.x+c.random*c.tiltCos,m=c.y+c.random*c.tiltSin,b=c.wobbleX+c.random*c.tiltCos,C=c.wobbleY+c.random*c.tiltSin;if(t.fillStyle=`rgba(`+c.color.r+`, `+c.color.g+`, `+c.color.b+`, `+(1-u)+`)`,t.beginPath(),g&&c.shape.type===`path`&&typeof c.shape.path==`string`&&Array.isArray(c.shape.matrix))t.fill(transformPath2D(c.shape.path,c.shape.matrix,c.x,c.y,Math.abs(b-d)*.1,Math.abs(C-m)*.1,Math.PI/10*c.wobble));else if(c.shape.type===`bitmap`){var w=Math.PI/10*c.wobble,T=Math.abs(b-d)*.1,E=Math.abs(C-m)*.1,D=c.shape.bitmap.width*c.scalar,O=c.shape.bitmap.height*c.scalar,xr=new DOMMatrix([Math.cos(w)*T,Math.sin(w)*T,-Math.sin(w)*E,Math.cos(w)*E,c.x,c.y]);xr.multiplySelf(new DOMMatrix(c.shape.matrix));var Sr=t.createPattern(S.transform(c.shape.bitmap),`no-repeat`);Sr.setTransform(xr),t.globalAlpha=1-u,t.fillStyle=Sr,t.fillRect(c.x-D/2,c.y-O/2,D,O),t.globalAlpha=1}else if(c.shape===`circle`)t.ellipse?t.ellipse(c.x,c.y,Math.abs(b-d)*c.ovalScalar,Math.abs(C-m)*c.ovalScalar,Math.PI/10*c.wobble,0,2*Math.PI):ellipse(t,c.x,c.y,Math.abs(b-d)*c.ovalScalar,Math.abs(C-m)*c.ovalScalar,Math.PI/10*c.wobble,0,2*Math.PI);else if(c.shape===`star`)for(var Cr=Math.PI/2*3,wr=4*c.scalar,Tr=8*c.scalar,Er=c.x,Dr=c.y,Or=5,kr=Math.PI/Or;Or--;)Er=c.x+Math.cos(Cr)*Tr,Dr=c.y+Math.sin(Cr)*Tr,t.lineTo(Er,Dr),Cr+=kr,Er=c.x+Math.cos(Cr)*wr,Dr=c.y+Math.sin(Cr)*wr,t.lineTo(Er,Dr),Cr+=kr;else t.moveTo(Math.floor(c.x),Math.floor(c.y)),t.lineTo(Math.floor(c.wobbleX),Math.floor(m)),t.lineTo(Math.floor(b),Math.floor(C)),t.lineTo(Math.floor(d),Math.floor(c.wobbleY));return t.closePath(),t.fill(),c.tick<c.totalTicks}function animate(t,c,m,g,b){var w=c.slice(),T=t.getContext(`2d`),E,D,O=promise(function(c){function onDone(){E=D=null,T.clearRect(0,0,g.width,g.height),S.clear(),b(),c()}function update(){u&&!(g.width===d.width&&g.height===d.height)&&(g.width=t.width=d.width,g.height=t.height=d.height),!g.width&&!g.height&&(m(t),g.width=t.width,g.height=t.height),T.clearRect(0,0,g.width,g.height),w=w.filter(function(t){return updateFetti(T,t)}),w.length?E=C.frame(update):onDone()}E=C.frame(update),D=onDone});return{addFettis:function(t){return w=w.concat(t),O},canvas:t,promise:O,reset:function(){E&&C.cancel(E),D&&D()}}}function confettiCannon(c,u){var d=!c,g=!!prop(u||{},`resize`),b=!1,S=prop(u,`disableForReducedMotion`,Boolean),C=m&&prop(u||{},`useWorker`)?w():null,T=d?setCanvasWindowSize:setCanvasRectSize,E=c&&C?!!c.__confetti_initialized:!1,D=typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion)`).matches,O;function fireLocal(t,u,d){for(var m=prop(t,`particleCount`,onlyPositiveInt),g=prop(t,`angle`,Number),b=prop(t,`spread`,Number),S=prop(t,`startVelocity`,Number),C=prop(t,`decay`,Number),w=prop(t,`gravity`,Number),E=prop(t,`drift`,Number),D=prop(t,`colors`,colorsToRgb),xr=prop(t,`ticks`,Number),Sr=prop(t,`shapes`),Cr=prop(t,`scalar`),wr=!!prop(t,`flat`),Tr=getOrigin(t),Er=m,Dr=[],Or=c.width*Tr.x,kr=c.height*Tr.y;Er--;)Dr.push(randomPhysics({x:Or,y:kr,angle:g,spread:b,startVelocity:S,color:D[Er%D.length],shape:Sr[randomInt(0,Sr.length)],ticks:xr,decay:C,gravity:w,drift:E,scalar:Cr,flat:wr}));return O?O.addFettis(Dr):(O=animate(c,Dr,T,u,d),O.promise)}function fire(u){var m=S||prop(u,`disableForReducedMotion`,Boolean),w=prop(u,`zIndex`,Number);if(m&&D)return promise(function(t){t()});d&&O?c=O.canvas:d&&!c&&(c=getCanvas(w),document.body.appendChild(c)),g&&!E&&T(c);var xr={width:c.width,height:c.height};C&&!E&&C.init(c),E=!0,C&&(c.__confetti_initialized=!0);function onResize(){if(C){var t={getBoundingClientRect:function(){if(!d)return c.getBoundingClientRect()}};T(t),C.postMessage({resize:{width:t.width,height:t.height}});return}xr.width=xr.height=null}function done(){O=null,g&&(b=!1,t.removeEventListener(`resize`,onResize)),d&&c&&(document.body.contains(c)&&document.body.removeChild(c),c=null,E=!1)}return g&&!b&&(b=!0,t.addEventListener(`resize`,onResize,!1)),C?C.fire(u,xr,done):fireLocal(u,xr,done)}return fire.reset=function(){C&&C.reset(),O&&O.reset()},fire}var E;function getDefaultFire(){return E||(E=confettiCannon(null,{useWorker:!0,resize:!0})),E}function transformPath2D(t,c,u,d,m,g,b){var S=new Path2D(t),C=new Path2D;C.addPath(S,new DOMMatrix(c));var w=new Path2D;return w.addPath(C,new DOMMatrix([Math.cos(b)*m,Math.sin(b)*m,-Math.sin(b)*g,Math.cos(b)*g,u,d])),w}function shapeFromPath(t){if(!g)throw Error(`path confetti are not supported in this browser`);var c,u;typeof t==`string`?c=t:(c=t.path,u=t.matrix);var d=new Path2D(c),m=document.createElement(`canvas`).getContext(`2d`);if(!u){for(var b=1e3,S=b,C=b,w=0,T=0,E,D,O=0;O<b;O+=2)for(var xr=0;xr<b;xr+=2)m.isPointInPath(d,O,xr,`nonzero`)&&(S=Math.min(S,O),C=Math.min(C,xr),w=Math.max(w,O),T=Math.max(T,xr));E=w-S,D=T-C;var Sr=10,Cr=Math.min(Sr/E,Sr/D);u=[Cr,0,0,Cr,-Math.round(E/2+S)*Cr,-Math.round(D/2+C)*Cr]}return{type:`path`,path:c,matrix:u}}function shapeFromText(t){var c,u=1,d=`#000000`,m=`"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif`;typeof t==`string`?c=t:(c=t.text,u=`scalar`in t?t.scalar:u,m=`fontFamily`in t?t.fontFamily:m,d=`color`in t?t.color:d);var g=10*u,b=``+g+`px `+m,S=new OffscreenCanvas(g,g),C=S.getContext(`2d`);C.font=b;var w=C.measureText(c),T=Math.ceil(w.actualBoundingBoxRight+w.actualBoundingBoxLeft),E=Math.ceil(w.actualBoundingBoxAscent+w.actualBoundingBoxDescent),D=2,O=w.actualBoundingBoxLeft+D,xr=w.actualBoundingBoxAscent+D;T+=D+D,E+=D+D,S=new OffscreenCanvas(T,E),C=S.getContext(`2d`),C.font=b,C.fillStyle=d,C.fillText(c,O,xr);var Sr=1/u;return{type:`bitmap`,bitmap:S.transferToImageBitmap(),matrix:[Sr,0,0,Sr,-T*Sr/2,-E*Sr/2]}}c.exports=function(){return getDefaultFire().apply(this,arguments)},c.exports.reset=function(){getDefaultFire().reset()},c.exports.create=confettiCannon,c.exports.shapeFromPath=shapeFromPath,c.exports.shapeFromText=shapeFromText})((function(){return typeof window<`u`?window:typeof self<`u`?self:this||{}})(),Vt,!1),Ht=Vt.exports,Vt.exports.create,Ut=defineComponent({name:`StudySession`,ref:{},components:{CardViewer:Q$1,StudySessionTimer:st$1,SkMouseTrap:Ne$1,HeatMap:Ae$1,SessionControllerDebug:Bt},props:{sessionTimeLimit:{type:Number,required:!0},contentSources:{type:Array,required:!0},user:{type:Object,required:!0},dataLayer:{type:Object,required:!0},sessionConfig:{type:Object,default:()=>({likesConfetti:!1})},getViewComponent:{type:Function,required:!0},frameless:{type:Boolean,default:!1},hideFooter:{type:Boolean,default:!1},transitionName:{type:String,default:`component-fade`},transitionMode:{type:String,default:`out-in`}},emits:[`session-finished`,`session-started`,`card-loaded`,`card-response`,`time-changed`,`session-prepared`,`session-error`,`replan-requested`],data(){return{cardID:``,view:null,data:[],courseID:``,card_elo:1e3,courseNames:{},cardCount:1,sessionController:null,sessionPrepared:!1,sessionFinished:!1,sessionRecord:[],percentageRemaining:100,timerIsActive:!0,loading:!1,userCourseRegDoc:null,sessionContentSources:[],timeRemaining:300,replanPending:!1,replanOptions:null,deferredNextCardAction:null,intervalHandler:null,cardType:``,debugMode:window.debugMode===!0}},computed:{currentCard(){return this.sessionRecord[this.sessionRecord.length-1]},resolvedTransitionMode(){return this.transitionMode===`default`?void 0:this.transitionMode}},async created(){this.userCourseRegDoc=await this.user.getCourseRegistrationsDoc(),console.log(`[StudySession] Created lifecycle hook - starting initSession`),await this.initSession(),console.log(`[StudySession] InitSession completed in created hook`)},beforeUnmount(){this.sessionController&&!this.sessionFinished&&this.sessionController.endSession(`abandoned`),this.intervalHandler&&clearInterval(this.intervalHandler)},errorCaptured(t,c,u){return console.error(`[StudySession] Card render error (${u}), skipping card "${this.cardID}":`,t),this.sessionController&&this.sessionController.nextCard().then(t=>this.loadCard(t)),!1},methods:{async handleReadyToAdvance(){let t=this.deferredNextCardAction;if(!t){console.warn(`[StudySession] ready-to-advance received but no deferred action stashed — ignoring`);return}console.log(`[StudySession] ready-to-advance received — advancing with stashed action: ${t}`),this.deferredNextCardAction=null,this.loadCard(await this.sessionController.nextCard(t))},handleReplanRequest(t){if(this.sessionController){let c=t?.label,u=c?` [${c}]`:``;console.log(`[StudySession] Replan requested by card view${u}, deferring until after response processing`),this.replanPending=!0,this.replanOptions=t??null}},user_elo(t){let c=this.userCourseRegDoc.courses.find(c=>c.courseID===t);return toCourseElo(c?c.elo:void 0)},handleClassroomMessage(){return t=>(Z$2({text:this.user?.getUsername()||`[Unknown user]`,status:Status.ok}),console.log(`[StudySession] There was a change in the classroom DB:`),console.log(`[StudySession] change: ${t}`),console.log(`[StudySession] Stringified change: ${JSON.stringify(t)}`),{})},incrementSessionClock(){let t=60*this.sessionTimeLimit-this.timeRemaining;this.sessionController.addTime(Math.min(t,60)),this.tick()},tick(){this.timeRemaining=this.sessionController.secondsRemaining,this.percentageRemaining=this.timeRemaining>60?100*(this.timeRemaining/(60*this.sessionTimeLimit)):100*(this.timeRemaining/60),this.$emit(`time-changed`,this.timeRemaining),this.timeRemaining===0&&clearInterval(this.intervalHandler)},async initSession(){let t=[];try{console.log(`[StudySession] starting study session w/ sources: ${JSON.stringify(this.contentSources)}`),console.log(`[StudySession] Beginning preparation process`),this.sessionContentSources=markRaw((await Promise.all(this.contentSources.map(async t=>{try{return await getStudySource(t,this.user)}catch(c){return console.error(`Failed to load study source: ${t.type}/${t.id}`,c),null}}))).filter(t=>t!==null)),this.timeRemaining=this.sessionTimeLimit*60,t=await Promise.all(this.contentSources.filter(t=>t.type===`classroom`).map(async t=>await this.dataLayer.getClassroomDB(t.id,`student`))),t.forEach(t=>{});let c={};this.sessionConfig?.defaultBatchLimit!==void 0&&(c.defaultBatchLimit=this.sessionConfig.defaultBatchLimit),this.sessionConfig?.outcomeObservers?.length&&(c.outcomeObservers=this.sessionConfig.outcomeObservers);let u=this.contentSources.find(t=>t.type===`course`)?.id;u&&(c.courseId=u),this.sessionConfig?.sessionStateSnapshot&&(c.stateSnapshotProvider=this.sessionConfig.sessionStateSnapshot),this.sessionController=markRaw(new SessionController(this.sessionContentSources,60*this.sessionTimeLimit,this.dataLayer,this.getViewComponent,void 0,c)),this.sessionController.sessionRecord=this.sessionRecord,this.sessionConfig?.initHints&&(this.sessionController.setSessionHints(this.sessionConfig.initHints),console.log(`[StudySession] Applied init hints as session-durable hints`)),await this.sessionController.prepareSession(),this.intervalHandler=setInterval(this.tick,1e3),this.sessionPrepared=!0,console.log(`[StudySession] Session preparation complete, emitting session-prepared event`),this.$emit(`session-prepared`),console.log(`[StudySession] Event emission completed`)}catch(t){console.error(`[StudySession] Error during session preparation:`,t),this.$emit(`session-error`,{message:`Failed to prepare study session`,error:t});return}try{this.contentSources.filter(t=>t.type===`course`).forEach(async t=>this.courseNames[t.id]=(await this.dataLayer.getCoursesDB().getCourseConfig(t.id)).name),console.log(`[StudySession] Session created:
481
482
  ${this.sessionController?.toString()||`Session controller not initialized`}
482
483
  User courses: ${this.contentSources.filter(t=>t.type===`course`).map(t=>t.id).toString()}
483
484
  User classrooms: ${t.map(t=>t._id).toString()||`No classrooms`}
484
- `)}catch(t){console.error(`[StudySession] Error during final session setup:`,t)}if(this.sessionController)try{this.$emit(`session-started`),this.loadCard(await this.sessionController.nextCard())}catch(t){console.error(`[StudySession] Error loading next card:`,t),this.$emit(`session-error`,{message:`Failed to load study card`,error:t})}else console.error(`[StudySession] Cannot load card: session controller not initialized`),this.$emit(`session-error`,{message:`Study session initialization failed`})},countCardViews(t,c){return this.sessionRecord.filter(u=>u.card.course_id===t&&u.card.card_id===c).length},async processResponse(t){this.$emit(`card-response`,t),this.timerIsActive=!0,t.cardID=this.cardID,t.courseID=this.courseID,t.sessionId=this.sessionController?.sessionId,this.currentCard.records.push(t),console.log(`[StudySession] StudySession.processResponse is running...`);let c=this.logCardRecord(t).catch(t=>{throw console.error(`[StudySession] putCardRecord failed:`,t),t}),u=1,d=1;if(isQuestionView(this.$refs.cardViewer?.$refs.activeView)){let t=this.$refs.cardViewer.$refs.activeView;u=t.maxAttemptsPerView,d=t.maxSessionViews}let m=this.countCardViews(this.courseID,this.cardID),g=await this.sessionController.submitResponse(t,c,this.userCourseRegDoc,this.currentCard,this.courseID,this.cardID,u,d,m);try{this.handleUIFeedback(g)}catch(t){console.error(`[StudySession] Error handling UI feedback: ${t}.\n\nResult: ${JSON.stringify(g)}`)}if(this.replanPending){let t=this.replanOptions,c=t?.label,u=c?` [${c}]`:``;console.log(`[StudySession] Firing deferred replan (post-submitResponse)${u}`),this.replanPending=!1,this.replanOptions=null,this.sessionController.requestReplan(t??void 0),this.$emit(`replan-requested`)}g.deferred?(console.log(`[StudySession] Deferred advance — stashing action: ${g.nextCardAction}`),this.deferredNextCardAction=g.nextCardAction):g.shouldLoadNextCard&&this.loadCard(await this.sessionController.nextCard(g.nextCardAction)),g.shouldClearFeedbackShadow&&this.clearFeedbackShadow()},handleUIFeedback(t){if(t.isCorrect){if(!this.frameless)try{this.$refs.shadowWrapper&&t.performanceScore!==void 0&&(this.$refs.shadowWrapper.setAttribute(`style`,`--r: ${255*(1-t.performanceScore)}; --g:255`),this.$refs.shadowWrapper.classList.add(`correct`))}catch(t){console.warn(`[StudySession] Error setting shadowWrapper style: ${t}`)}this.sessionConfig.likesConfetti&&Ht({origin:{y:1,x:.25+.5*Math.random()},disableForReducedMotion:!0,angle:60+60*Math.random()})}else if(!this.frameless)try{this.$refs.shadowWrapper&&this.$refs.shadowWrapper.classList.add(`incorrect`)}catch(t){console.warn(`[StudySession] Error setting shadowWrapper style: ${t}`)}},clearFeedbackShadow(){this.frameless||setTimeout(()=>{try{this.$refs.shadowWrapper&&this.$refs.shadowWrapper.classList.remove(`correct`,`incorrect`)}catch(t){console.warn(`[StudySession] Error clearing shadowWrapper style: ${t}`)}},1250)},async logCardRecord(t){console.log(`[StudySession] About to call user.putCardRecord...`);let c=await this.user.putCardRecord(t);return console.log(`[StudySession] user.putCardRecord completed`),c},async loadCard(t){if(this.loading){console.warn(`Attempted to load card while loading another...`);return}if(console.log(`[StudySession] loading: ${JSON.stringify(t)}`),t===null){this.sessionFinished=!0,this.$emit(`session-finished`,this.sessionRecord);return}this.cardType=t.item.status,this.loading=!0,this.cardCount++,this.data=t.data,this.view=markRaw(t.view),this.cardID=t.item.cardID,this.courseID=t.item.courseID,this.card_elo=t.item.elo||1e3,this.sessionRecord.push({card:{course_id:t.item.courseID,card_id:t.item.cardID,card_elo:this.card_elo,tags:t.tags??[]},item:t.item,records:[]}),this.$emit(`card-loaded`,{courseID:t.item.courseID,cardID:t.item.cardID,cardCount:this.cardCount}),this.loading=!1}}}),Wt={key:0,class:`StudySession`},Gt={key:2},Kt={key:3,class:`session-finished-area`},qt={class:`text-h4`},Jt={key:0},Yt={key:4,ref:`shadowWrapper`,class:`card-transition-container`},Xt={key:0},__name(_sfc_render$15,`_sfc_render`),Zt=F$3(Ut,[[`render`,_sfc_render$15],[`__scopeId`,`data-v-c765534b`]]),Qt=defineComponent({name:`MultipleChoiceOption`,components:{MarkdownRenderer:defineAsyncComponent(()=>Promise.resolve().then(()=>(init_MarkdownRenderer_kStoDRNE(),MarkdownRenderer_kStoDRNE_exports)).then(t=>t.n))},props:{content:{type:String,required:!0},selected:{type:Boolean,required:!0},number:{type:Number,required:!0},setSelection:{type:Function,required:!0},submit:{type:Function,required:!0},markedWrong:{type:Boolean,required:!0}},computed:{className(){let t;switch(this.number){case 0:t=`bg-red`;break;case 1:t=`bg-purple`;break;case 2:t=`bg-indigo`;break;case 3:t=`bg-light-blue`;break;case 4:t=`bg-teal`;break;case 5:t=`bg-deep-orange`;break;default:t=`bg-grey`;break}if(this.selected&&!this.markedWrong)return`choice selected ${t} lighten-3 elevation-8`;if(!this.selected&&!this.markedWrong)return`choice not-selected ${t} lighten-4 elevation-1`;if(this.selected&&this.markedWrong)return`choice selected grey lighten-2 elevation-8`;if(!this.selected&&this.markedWrong)return`choice not-selected grey lighten-2 elevation-0`;throw Error(`'selected' and 'markedWrong' props in MultipleChoiceOption are in an impossible configuration.`)}},methods:{select(){this.setSelection(this.number)},submitThisOption(){this.markedWrong||(this.select(),this.submit())}}}),__name(_sfc_render$14,`_sfc_render`),$t=F$3(Qt,[[`render`,_sfc_render$14],[`__scopeId`,`data-v-96de7172`]]),en=defineComponent({name:`RadioMultipleChoice`,components:{MultipleChoiceOption:$t},extends:se$3,props:{choiceList:{type:Array,required:!0}},data(){return{currentSelection:-1,incorrectSelections:[],containerRef:null,_registeredHotkeys:[]}},watch:{choiceList:{immediate:!0,handler(t){t?.length&&this.bindKeys()}}},mounted(){this.containerRef&&this.containerRef.focus()},unmounted(){this.unbindKeys()},methods:{forwardSelection(){if(!this.choiceIsWrong(this.choiceList[this.currentSelection])&&this.currentSelection!==-1){let t={choiceList:this.choiceList,selection:this.currentSelection};this.submitAnswer(t).isCorrect||this.incorrectSelections.push(this.currentSelection)}},setSelection(t){t<this.choiceList.length&&(this.currentSelection=t)},incrementSelection(){this.currentSelection===-1?this.currentSelection=Math.ceil(this.choiceList.length/2):this.currentSelection=Math.min(this.choiceList.length-1,this.currentSelection+1)},decrementSelection(){this.currentSelection===-1?this.currentSelection=Math.floor(this.choiceList.length/2-1):this.currentSelection=Math.max(0,this.currentSelection-1)},choiceIsWrong(t){let c=!1;return this.incorrectSelections.forEach(u=>{this.choiceList[u]===t&&(c=!0)}),c},bindKeys(){let t=[{hotkey:`left`,callback:this.decrementSelection,command:`Move selection left`},{hotkey:`right`,callback:this.incrementSelection,command:`Move selection right`},{hotkey:`enter`,callback:this.forwardSelection,command:`Submit selection`},...Array.from({length:this.choiceList.length},(t,c)=>({hotkey:(c+1).toString(),callback:()=>this.setSelection(c),command:`Select ${(t=>{switch(t){case 0:return`first`;case 1:return`second`;case 2:return`third`;case 3:return`fourth`;case 4:return`fifth`;case 5:return`sixth`;default:return`${t+1}th`}})(c)} option`}))];I$2.addBinding(t),this._registeredHotkeys=t.map(t=>t.hotkey)},unbindKeys(){this._registeredHotkeys&&this._registeredHotkeys.forEach(t=>{I$2.removeBinding(t)})}}}),tn={ref:`containerRef`,class:`multipleChoice`},__name(_sfc_render$13,`_sfc_render`),nn=F$3(en,[[`render`,_sfc_render$13]]),rn=defineComponent({name:`TrueFalse`,components:{RadioMultipleChoice:nn},props:{MouseTrap:{type:Object,required:!0},submit:{type:Function,required:!0}}}),an={"data-viewable":`TrueFalse`},__name(_sfc_render$12,`_sfc_render`),on=F$3(rn,[[`render`,_sfc_render$12]]),sn=defineComponent({name:`UserInputNumber`,ref:{},extends:se$3,methods:{mounted(){this.$refs.input.focus()},isNumeric(t){return!isNaN(Number.parseFloat(t))},makeNumeric(t){if(typeof t==`string`)return Number.parseFloat(t);throw Error(`Expected a string, got `+typeof t)}}}),__name(_sfc_render$11,`_sfc_render`),cn=F$3(sn,[[`render`,_sfc_render$11],[`__scopeId`,`data-v-a56dcd1c`]]),ln=defineComponent({name:`CardLoader`,components:{CardViewer:Q$1},props:{sessionOrder:{type:Number,required:!1,default:0},qualified_id:{type:Object,required:!0},viewLookup:{type:Function,required:!0}},data(){return{loading:!0,view:null,data:[],courseID:``,cardID:``}},created(){this.loadCard()},watch:{qualified_id:{immediate:!0,handler(){this.loadCard()}}},methods:{processResponse(t){log$2(`
485
+ `)}catch(t){console.error(`[StudySession] Error during final session setup:`,t)}if(this.sessionController)try{this.$emit(`session-started`),this.loadCard(await this.sessionController.nextCard())}catch(t){console.error(`[StudySession] Error loading next card:`,t),this.$emit(`session-error`,{message:`Failed to load study card`,error:t})}else console.error(`[StudySession] Cannot load card: session controller not initialized`),this.$emit(`session-error`,{message:`Study session initialization failed`})},countCardViews(t,c){return this.sessionRecord.filter(u=>u.card.course_id===t&&u.card.card_id===c).length},async processResponse(t){this.$emit(`card-response`,t),this.timerIsActive=!0,t.cardID=this.cardID,t.courseID=this.courseID,t.sessionId=this.sessionController?.sessionId,this.currentCard.records.push(t),console.log(`[StudySession] StudySession.processResponse is running...`);let c=this.logCardRecord(t).catch(t=>{throw console.error(`[StudySession] putCardRecord failed:`,t),t}),u=1,d=1;if(isQuestionView(this.$refs.cardViewer?.$refs.activeView)){let t=this.$refs.cardViewer.$refs.activeView;u=t.maxAttemptsPerView,d=t.maxSessionViews}let m=this.countCardViews(this.courseID,this.cardID),g=await this.sessionController.submitResponse(t,c,this.userCourseRegDoc,this.currentCard,this.courseID,this.cardID,u,d,m);try{this.handleUIFeedback(g)}catch(t){console.error(`[StudySession] Error handling UI feedback: ${t}.\n\nResult: ${JSON.stringify(g)}`)}if(this.replanPending){let t=this.replanOptions,c=t?.label,u=c?` [${c}]`:``;console.log(`[StudySession] Firing deferred replan (post-submitResponse)${u}`),this.replanPending=!1,this.replanOptions=null,this.sessionController.requestReplan(t??void 0),this.$emit(`replan-requested`)}g.deferred?(console.log(`[StudySession] Deferred advance — stashing action: ${g.nextCardAction}`),this.deferredNextCardAction=g.nextCardAction):g.shouldLoadNextCard&&this.loadCard(await this.sessionController.nextCard(g.nextCardAction)),g.shouldClearFeedbackShadow&&this.clearFeedbackShadow()},handleUIFeedback(t){if(t.isCorrect){if(!this.frameless)try{this.$refs.shadowWrapper&&t.performanceScore!==void 0&&(this.$refs.shadowWrapper.setAttribute(`style`,`--r: ${255*(1-t.performanceScore)}; --g:255`),this.$refs.shadowWrapper.classList.add(`correct`))}catch(t){console.warn(`[StudySession] Error setting shadowWrapper style: ${t}`)}this.sessionConfig.likesConfetti&&Ht({origin:{y:1,x:.25+.5*Math.random()},disableForReducedMotion:!0,angle:60+60*Math.random()})}else if(!this.frameless)try{this.$refs.shadowWrapper&&this.$refs.shadowWrapper.classList.add(`incorrect`)}catch(t){console.warn(`[StudySession] Error setting shadowWrapper style: ${t}`)}},clearFeedbackShadow(){this.frameless||setTimeout(()=>{try{this.$refs.shadowWrapper&&this.$refs.shadowWrapper.classList.remove(`correct`,`incorrect`)}catch(t){console.warn(`[StudySession] Error clearing shadowWrapper style: ${t}`)}},1250)},async logCardRecord(t){console.log(`[StudySession] About to call user.putCardRecord...`);let c=await this.user.putCardRecord(t);return console.log(`[StudySession] user.putCardRecord completed`),c},async loadCard(t){if(this.loading){console.warn(`Attempted to load card while loading another...`);return}if(console.log(`[StudySession] loading: ${JSON.stringify(t)}`),t===null){this.sessionFinished=!0,this.$emit(`session-finished`,this.sessionRecord);return}this.cardType=t.item.status,this.loading=!0,this.cardCount++,this.data=t.data,this.view=markRaw(t.view),this.cardID=t.item.cardID,this.courseID=t.item.courseID,this.card_elo=t.item.elo||1e3,this.sessionRecord.push({card:{course_id:t.item.courseID,card_id:t.item.cardID,card_elo:this.card_elo,tags:t.tags??[]},item:t.item,records:[]}),this.$emit(`card-loaded`,{courseID:t.item.courseID,cardID:t.item.cardID,cardCount:this.cardCount}),this.loading=!1}}}),Wt={key:0,class:`StudySession`},Gt={key:2},Kt={key:3,class:`session-finished-area`},qt={class:`text-h4`},Jt={key:0},Yt={key:4,ref:`shadowWrapper`,class:`card-transition-container`},Xt={key:0},__name(_sfc_render$15,`_sfc_render`),Zt=F$3(Ut,[[`render`,_sfc_render$15],[`__scopeId`,`data-v-ad5e0df0`]]),Qt=defineComponent({name:`MultipleChoiceOption`,components:{MarkdownRenderer:defineAsyncComponent(()=>Promise.resolve().then(()=>(init_MarkdownRenderer_kStoDRNE(),MarkdownRenderer_kStoDRNE_exports)).then(t=>t.n))},props:{content:{type:String,required:!0},selected:{type:Boolean,required:!0},number:{type:Number,required:!0},setSelection:{type:Function,required:!0},submit:{type:Function,required:!0},markedWrong:{type:Boolean,required:!0}},computed:{className(){let t;switch(this.number){case 0:t=`bg-red`;break;case 1:t=`bg-purple`;break;case 2:t=`bg-indigo`;break;case 3:t=`bg-light-blue`;break;case 4:t=`bg-teal`;break;case 5:t=`bg-deep-orange`;break;default:t=`bg-grey`;break}if(this.selected&&!this.markedWrong)return`choice selected ${t} lighten-3 elevation-8`;if(!this.selected&&!this.markedWrong)return`choice not-selected ${t} lighten-4 elevation-1`;if(this.selected&&this.markedWrong)return`choice selected grey lighten-2 elevation-8`;if(!this.selected&&this.markedWrong)return`choice not-selected grey lighten-2 elevation-0`;throw Error(`'selected' and 'markedWrong' props in MultipleChoiceOption are in an impossible configuration.`)}},methods:{select(){this.setSelection(this.number)},submitThisOption(){this.markedWrong||(this.select(),this.submit())}}}),__name(_sfc_render$14,`_sfc_render`),$t=F$3(Qt,[[`render`,_sfc_render$14],[`__scopeId`,`data-v-96de7172`]]),en=defineComponent({name:`RadioMultipleChoice`,components:{MultipleChoiceOption:$t},extends:se$3,props:{choiceList:{type:Array,required:!0}},data(){return{currentSelection:-1,incorrectSelections:[],containerRef:null,_registeredHotkeys:[]}},watch:{choiceList:{immediate:!0,handler(t){t?.length&&this.bindKeys()}}},mounted(){this.containerRef&&this.containerRef.focus()},unmounted(){this.unbindKeys()},methods:{forwardSelection(){if(!this.choiceIsWrong(this.choiceList[this.currentSelection])&&this.currentSelection!==-1){let t={choiceList:this.choiceList,selection:this.currentSelection};this.submitAnswer(t).isCorrect||this.incorrectSelections.push(this.currentSelection)}},setSelection(t){t<this.choiceList.length&&(this.currentSelection=t)},incrementSelection(){this.currentSelection===-1?this.currentSelection=Math.ceil(this.choiceList.length/2):this.currentSelection=Math.min(this.choiceList.length-1,this.currentSelection+1)},decrementSelection(){this.currentSelection===-1?this.currentSelection=Math.floor(this.choiceList.length/2-1):this.currentSelection=Math.max(0,this.currentSelection-1)},choiceIsWrong(t){let c=!1;return this.incorrectSelections.forEach(u=>{this.choiceList[u]===t&&(c=!0)}),c},bindKeys(){let t=[{hotkey:`left`,callback:this.decrementSelection,command:`Move selection left`},{hotkey:`right`,callback:this.incrementSelection,command:`Move selection right`},{hotkey:`enter`,callback:this.forwardSelection,command:`Submit selection`},...Array.from({length:this.choiceList.length},(t,c)=>({hotkey:(c+1).toString(),callback:()=>this.setSelection(c),command:`Select ${(t=>{switch(t){case 0:return`first`;case 1:return`second`;case 2:return`third`;case 3:return`fourth`;case 4:return`fifth`;case 5:return`sixth`;default:return`${t+1}th`}})(c)} option`}))];I$2.addBinding(t),this._registeredHotkeys=t.map(t=>t.hotkey)},unbindKeys(){this._registeredHotkeys&&this._registeredHotkeys.forEach(t=>{I$2.removeBinding(t)})}}}),tn={ref:`containerRef`,class:`multipleChoice`},__name(_sfc_render$13,`_sfc_render`),nn=F$3(en,[[`render`,_sfc_render$13]]),rn=defineComponent({name:`TrueFalse`,components:{RadioMultipleChoice:nn},props:{MouseTrap:{type:Object,required:!0},submit:{type:Function,required:!0}}}),an={"data-viewable":`TrueFalse`},__name(_sfc_render$12,`_sfc_render`),on=F$3(rn,[[`render`,_sfc_render$12]]),sn=defineComponent({name:`UserInputNumber`,ref:{},extends:se$3,methods:{mounted(){this.$refs.input.focus()},isNumeric(t){return!isNaN(Number.parseFloat(t))},makeNumeric(t){if(typeof t==`string`)return Number.parseFloat(t);throw Error(`Expected a string, got `+typeof t)}}}),__name(_sfc_render$11,`_sfc_render`),cn=F$3(sn,[[`render`,_sfc_render$11],[`__scopeId`,`data-v-a56dcd1c`]]),ln=defineComponent({name:`CardLoader`,components:{CardViewer:Q$1},props:{sessionOrder:{type:Number,required:!1,default:0},qualified_id:{type:Object,required:!0},viewLookup:{type:Function,required:!0}},data(){return{loading:!0,view:null,data:[],courseID:``,cardID:``}},created(){this.loadCard()},watch:{qualified_id:{immediate:!0,handler(){this.loadCard()}}},methods:{processResponse(t){log$2(`
485
486
  Card was displayed at ${t.timeStamp}
486
487
  User spent ${t.timeSpent} milliseconds with the card.
487
488
  `),this.$emit(`emitResponse`,t)},async loadCard(){let t=this.qualified_id;console.log(`Card Loader displaying: ${t.courseID}::${t.cardID}`),this.loading=!0;let c=t.courseID,u=t.cardID,d=getDataLayer().getCourseDB(c);try{let t=await d.getCourseDoc(u),m=this.viewLookup(t.id_view),g=t.id_displayable_data.map(t=>d.getCourseDoc(t,{attachments:!0,binary:!0})),b=[];for(let t of g){let c=await t;b.unshift(displayableDataToViewData(c))}this.data=b,this.view=markRaw(m),this.cardID=u,this.courseID=c}catch(t){throw Error(`[CardLoader] Error loading card: ${JSON.stringify(t)}, ${t}`)}finally{this.loading=!1,this.$emit(`card-loaded`)}}}}),__name(_sfc_render$10,`_sfc_render`),un=F$3(ln,[[`render`,_sfc_render$10],[`__scopeId`,`data-v-93f758b5`]]),useAuthStore=()=>{let t=getPinia();return t&&setActivePinia(t),defineStore(`auth`,{state:()=>({_user:void 0,loginAndRegistration:{init:!1,loggedIn:!1,regDialogOpen:!1,loginDialogOpen:!1},onLoadComplete:!1}),actions:{async init(){try{this._user=getDataLayer().getUserDB(),this.loginAndRegistration.loggedIn=this._user?this._user.isLoggedIn():!1,this.onLoadComplete=!0,this.loginAndRegistration.init=!0}catch(t){console.error(`Failed to initialize auth store:`,t),this.loginAndRegistration.loggedIn=!1,this.onLoadComplete=!0,this.loginAndRegistration.init=!0}},setLoginDialog(t){this.loginAndRegistration.loginDialogOpen=t},setRegDialog(t){this.loginAndRegistration.regDialogOpen=t},async resetUserData(){try{if(!this._user)throw Error(`No user available for data reset`);let t=await this._user.resetUserData();if(t.status!==`ok`)throw Error(t.error||`Reset failed`);return console.log(`User data reset successfully`),t}catch(t){throw console.error(`Failed to reset user data:`,t),t}}},getters:{currentUser:async()=>getCurrentUser(),isLoggedIn:t=>t.loginAndRegistration.loggedIn,isInitialized:t=>t.loginAndRegistration.init,status:t=>({loggedIn:t.loginAndRegistration.loggedIn,init:t.loginAndRegistration.init,user:t._user})}})()},useConfigStore=()=>{let t=getPinia();return t&&setActivePinia(t),defineStore(`config`,{state:()=>({config:{darkMode:!1,likesConfetti:!1,sessionTimeLimit:5}}),actions:{updateConfig(t){this.config=t},async updateDarkMode(t){this.config.darkMode=t;let c=await getCurrentUser();c&&await c.setConfig({darkMode:t})},async updateLikesConfetti(t){this.config.likesConfetti=t;let c=await getCurrentUser();c&&await c.setConfig({likesConfetti:t})},async updateSessionTimeLimit(t){this.config.sessionTimeLimit=t;let c=await getCurrentUser();c&&await c.setConfig({sessionTimeLimit:t})},async hydrate(){try{let t=await getCurrentUser();if(t){let c=await t.getConfig();console.log(`user config: ${JSON.stringify(c)}`),this.updateConfig(c)}else console.log(`No user logged in, using default config`)}catch(t){console.warn(`Failed to hydrate config store, using defaults:`,t)}},async init(){await this.hydrate()},resetDefaults(){this.config={darkMode:!1,likesConfetti:!1,sessionTimeLimit:5}}}})()},dn=F$3(defineComponent({__name:`UserChip`,props:{showLoginButton:{type:Boolean},redirectToPath:{}},setup(t){let c=useRouter(),u=useAuthStore(),d=useConfigStore(),m=useAuthUI(),g=ref(``),b=ref([]),S=ref(!1),C=ref(``),w=computed(()=>C.value===`reset`),resetDialogState=()=>{C.value=``,S.value=!1},T=computed(()=>b.value.length>0),E=computed(()=>m.config.value||{showLoginRegistration:!0,showLogout:!0,showResetData:!1,logoutLabel:`Log out`,resetLabel:``});onMounted(async()=>{g.value=(await getCurrentUser()).getUsername(),await m.detectSyncStrategy()});let gotoSettings=async()=>{c.push(`/u/${(await getCurrentUser()).getUsername()}`)},gotoStats=async()=>{c.push(`/u/${(await getCurrentUser()).getUsername()}/stats`)},dismiss=t=>{let c=b.value.indexOf(t);b.value.splice(c,1)},logout=async()=>{(await u._user.logout()).ok&&(u.loginAndRegistration={init:!0,loggedIn:!1,regDialogOpen:!1,loginDialogOpen:!1},d.resetDefaults(),c.push(`/home`))},executeReset=async()=>{try{await u.resetUserData(),d.resetDefaults(),resetDialogState(),c.push(`/home`)}catch(t){console.error(`Failed to reset user data:`,t)}};return(t,c)=>{let u=resolveComponent(`v-icon`),d=resolveComponent(`v-avatar`),m=resolveComponent(`v-chip`),D=resolveComponent(`v-list-item-title`),O=resolveComponent(`v-list-item`),xr=resolveComponent(`v-divider`),Sr=resolveComponent(`v-list`),Cr=resolveComponent(`v-menu`),wr=resolveComponent(`v-badge`),Tr=resolveComponent(`v-card-title`),Er=resolveComponent(`v-text-field`),Dr=resolveComponent(`v-card-text`),Or=resolveComponent(`v-spacer`),kr=resolveComponent(`v-btn`),Ar=resolveComponent(`v-card-actions`),jr=resolveComponent(`v-card`),Mr=resolveComponent(`v-dialog`);return openBlock(),createElementBlock(Fragment,null,[createVNode(wr,{content:b.value.length,"model-value":T.value,color:`accent`,location:`end top`},{default:withCtx(()=>[createVNode(Cr,{location:`bottom end`,transition:`scale-transition`},{activator:withCtx(({props:t})=>[createVNode(m,mergeProps(t,{class:`ma-2`}),{default:withCtx(()=>[createVNode(d,{start:``,class:`bg-primary`},{default:withCtx(()=>[createVNode(u,null,{default:withCtx(()=>c[4]||(c[4]=[createTextVNode(`mdi-school`)])),_:1})]),_:1}),createTextVNode(` `+toDisplayString(g.value),1)]),_:2},1040)]),default:withCtx(()=>[createVNode(Sr,null,{default:withCtx(()=>[(openBlock(!0),createElementBlock(Fragment,null,renderList(b.value,t=>(openBlock(),createBlock(O,{key:t,onClick:c=>dismiss(t)},{default:withCtx(()=>[createVNode(D,null,{default:withCtx(()=>[createTextVNode(toDisplayString(t),1)]),_:2},1024)]),_:2},1032,[`onClick`]))),128)),b.value.length?(openBlock(),createBlock(xr,{key:0})):createCommentVNode(``,!0),createVNode(O,{onClick:gotoStats},{prepend:withCtx(()=>[createVNode(u,null,{default:withCtx(()=>c[5]||(c[5]=[createTextVNode(`mdi-trending-up`)])),_:1})]),default:withCtx(()=>[createVNode(D,null,{default:withCtx(()=>c[6]||(c[6]=[createTextVNode(`Stats`)])),_:1})]),_:1}),createVNode(O,{onClick:gotoSettings},{prepend:withCtx(()=>[createVNode(u,null,{default:withCtx(()=>c[7]||(c[7]=[createTextVNode(`mdi-cog`)])),_:1})]),default:withCtx(()=>[createVNode(D,null,{default:withCtx(()=>c[8]||(c[8]=[createTextVNode(`Settings`)])),_:1})]),_:1}),E.value.showLogout?(openBlock(),createBlock(O,{key:1,onClick:logout},{prepend:withCtx(()=>[createVNode(u,null,{default:withCtx(()=>c[9]||(c[9]=[createTextVNode(`mdi-logout`)])),_:1})]),default:withCtx(()=>[createVNode(D,null,{default:withCtx(()=>[createTextVNode(toDisplayString(E.value.logoutLabel),1)]),_:1})]),_:1})):createCommentVNode(``,!0),E.value.showResetData?(openBlock(),createBlock(O,{key:2,onClick:c[0]||(c[0]=t=>S.value=!0)},{prepend:withCtx(()=>[createVNode(u,null,{default:withCtx(()=>c[10]||(c[10]=[createTextVNode(`mdi-delete-sweep`)])),_:1})]),default:withCtx(()=>[createVNode(D,null,{default:withCtx(()=>[createTextVNode(toDisplayString(E.value.resetLabel),1)]),_:1})]),_:1})):createCommentVNode(``,!0)]),_:1})]),_:1})]),_:1},8,[`content`,`model-value`]),createVNode(Mr,{modelValue:S.value,"onUpdate:modelValue":c[3]||(c[3]=t=>S.value=t),"max-width":`500px`,persistent:``},{default:withCtx(()=>[createVNode(jr,null,{default:withCtx(()=>[createVNode(Tr,{class:`text-h5 d-flex align-center`},{default:withCtx(()=>[createVNode(u,{color:`warning`,class:`mr-3`},{default:withCtx(()=>c[11]||(c[11]=[createTextVNode(`mdi-alert-circle`)])),_:1}),c[12]||(c[12]=createTextVNode(` Reset All User Data `))]),_:1}),createVNode(Dr,null,{default:withCtx(()=>[c[13]||(c[13]=createBaseVNode(`p`,{class:`mb-4`},`This will permanently delete:`,-1)),c[14]||(c[14]=createBaseVNode(`ul`,{class:`mb-4`},[createBaseVNode(`li`,null,`All course progress and history`),createBaseVNode(`li`,null,`Scheduled card reviews`),createBaseVNode(`li`,null,`Course registrations`),createBaseVNode(`li`,null,`User preferences`)],-1)),c[15]||(c[15]=createBaseVNode(`p`,{class:`mb-4 text-error font-weight-bold`},`This cannot be undone.`,-1)),createVNode(Er,{modelValue:C.value,"onUpdate:modelValue":c[1]||(c[1]=t=>C.value=t),label:`Type "reset" to confirm`,outlined:``,dense:``,onKeyup:c[2]||(c[2]=withKeys(t=>w.value&&executeReset(),[`enter`]))},null,8,[`modelValue`])]),_:1}),createVNode(Ar,null,{default:withCtx(()=>[createVNode(Or),createVNode(kr,{text:``,onClick:resetDialogState},{default:withCtx(()=>c[16]||(c[16]=[createTextVNode(`Cancel`)])),_:1}),createVNode(kr,{color:`error`,disabled:!w.value,onClick:executeReset},{default:withCtx(()=>c[17]||(c[17]=[createTextVNode(` Reset All Data `)])),_:1},8,[`disabled`])]),_:1})]),_:1})]),_:1},8,[`modelValue`])],64)}}}),[[`__scopeId`,`data-v-9a38a213`]]),fn={class:`d-flex flex-column align-start`},pn={class:`mb-2`},mn=`Username or password was incorrect.`,hn=`Login is temporarily unavailable. Please try again in a moment.`,gn=F$3(defineComponent({__name:`UserLogin`,props:{redirectTo:{default:`/study`}},emits:[`toggle`,`loginSuccess`,`forgotPassword`],setup(t,{emit:c}){let u=t,d=c,m=useRouter(),g=useRoute(),b=useAuthStore(),S=useConfigStore(),C=ref(``),w=ref(``),T=ref(!1),E=ref(!1),D=ref(!1),O=ref(7e3),xr=ref(`Username or password was incorrect.`),Sr=ref(void 0),Cr=computed(()=>g.name===`login`),wr=computed(()=>({color:D.value?`error`:`success`,text:D.value?`Try again`:`Log In`})),initBadLogin=(t=mn)=>{xr.value=t,D.value=!0,Z$2({text:t,status:Status.error,timeout:O.value}),setTimeout(()=>{D.value=!1},O.value)},login=async()=>{E.value=!0,log$2(`Starting login attempt`),log$2(`Login attempt for identifier: ${C.value}`);try{log$2(`Attempting to get User instance`),Sr.value=await getCurrentUser(),log$2(`Got User instance, attempting login`);let t=C.value;if(C.value.includes(`@`)){let c=await resolveLoginIdentifier(C.value,w.value);if(!c.ok||!c.username){c.status===401?(log$2(`Email identifier did not resolve: invalid credentials`),initBadLogin()):(log$2(`Email login unavailable (resolver error: ${c.error??`network`})`),initBadLogin(hn)),E.value=!1;return}t=c.username}await Sr.value.login(t,w.value),log$2(`Login successful`),log$2(`Initializing user config`),S.init(),log$2(`User config initialized`),log$2(`Setting authentication state`),b.loginAndRegistration.loggedIn=!0,log$2(`Authentication state set, redirecting to: ${u.redirectTo}`),d(`loginSuccess`,u.redirectTo),m.push(u.redirectTo),log$2(`Login and redirect complete`)}catch(t){log$2(`Login attempt failed`),log$2(`Login error details: ${JSON.stringify(t)}`),console.log(`login error: ${JSON.stringify(t)}`),log$2(`Initiating bad login feedback`),initBadLogin()}log$2(`Resetting awaiting response state`),E.value=!1},toggle=()=>{log$2(`Toggling registration / login forms.`),d(`toggle`)},handleForgotPassword=()=>{log$2(`Forgot password clicked`),Cr.value?m.push(`/request-reset`):d(`forgotPassword`)};return(t,c)=>{let u=resolveComponent(`v-card-title`),d=resolveComponent(`v-text-field`),m=resolveComponent(`v-btn`),g=resolveComponent(`v-snackbar`),b=resolveComponent(`v-icon`),S=resolveComponent(`router-link`),Sr=resolveComponent(`v-form`),Tr=resolveComponent(`v-card-text`),Er=resolveComponent(`v-card`);return openBlock(),createBlock(Er,null,{default:withCtx(()=>[Cr.value?createCommentVNode(``,!0):(openBlock(),createBlock(u,{key:0,class:`text-h5 bg-grey-lighten-2`},{default:withCtx(()=>c[5]||(c[5]=[createTextVNode(`Log In`)])),_:1})),createVNode(Tr,null,{default:withCtx(()=>[createVNode(Sr,{onsubmit:`return false;`,onSubmit:withModifiers(login,[`prevent`])},{default:withCtx(()=>[createVNode(d,{id:``,modelValue:C.value,"onUpdate:modelValue":c[0]||(c[0]=t=>C.value=t),autofocus:``,name:`username`,label:`Username or email`,"prepend-icon":`mdi-account-circle`},null,8,[`modelValue`]),createVNode(d,{modelValue:w.value,"onUpdate:modelValue":c[1]||(c[1]=t=>w.value=t),"prepend-icon":`mdi-lock`,name:`password`,hover:`Show password input`,label:`Enter your password`,hint:``,min:`0`,"append-icon":T.value?`mdi-eye-off`:`mdi-eye`,type:T.value?`text`:`password`,"onClick:append":c[2]||(c[2]=()=>T.value=!T.value)},null,8,[`modelValue`,`append-icon`,`type`]),createVNode(g,{modelValue:D.value,"onUpdate:modelValue":c[4]||(c[4]=t=>D.value=t),location:`bottom right`,timeout:O.value},{default:withCtx(()=>[createTextVNode(toDisplayString(xr.value)+` `,1),createVNode(m,{color:`pink`,variant:`text`,onClick:c[3]||(c[3]=t=>D.value=!1)},{default:withCtx(()=>c[6]||(c[6]=[createTextVNode(`Close`)])),_:1})]),_:1},8,[`modelValue`,`timeout`]),createBaseVNode(`div`,fn,[createBaseVNode(`div`,pn,[createVNode(m,{class:`mr-2`,type:`submit`,loading:E.value,color:wr.value.color},{default:withCtx(()=>[createVNode(b,{start:``},{default:withCtx(()=>c[7]||(c[7]=[createTextVNode(`mdi-lock-open`)])),_:1}),c[8]||(c[8]=createTextVNode(` Log In `))]),_:1},8,[`loading`,`color`]),Cr.value?(openBlock(),createBlock(S,{key:0,to:`signup`},{default:withCtx(()=>[createVNode(m,{variant:`text`},{default:withCtx(()=>c[9]||(c[9]=[createTextVNode(`Create New Account`)])),_:1})]),_:1})):(openBlock(),createBlock(m,{key:1,variant:`text`,onClick:toggle},{default:withCtx(()=>c[10]||(c[10]=[createTextVNode(`Create New Account`)])),_:1}))]),renderSlot(t.$slots,`forgot-password`,{},()=>[createBaseVNode(`a`,{href:`#`,class:`text-caption text-decoration-none`,onClick:withModifiers(handleForgotPassword,[`prevent`])},` Forgot password? `)],!0)])]),_:3})]),_:3})]),_:3})}}}),[[`__scopeId`,`data-v-764d1a76`]]),_n=defineComponent({name:`UserRegistration`,props:{onSignupSuccess:{type:Function,required:!1}},emits:[`toggle`,`signup-success`],data(){return{email:``,username:``,password:``,retypedPassword:``,passwordVisible:!1,emailError:!1,emailHint:``,usernameValidationInProgress:!1,usernameError:!1,usernameHint:``,awaitingResponse:!1,badLoginAttempt:!1,userSecret:``,secret:`goons`,user:null,roles:[`Student`,`Teacher`,`Author`],student:!0,teacher:!1,author:!1,authStore:useAuthStore()}},computed:{registrationRoute(){return typeof this.$route.name==`string`&&this.$route.name.toLowerCase()===`signup`},buttonStatus(){return{color:this.badLoginAttempt?`error`:`success`,text:this.badLoginAttempt?`Try again`:`Log In`}},passwordError(){return validatePassword(this.password)},passwordRetypeError(){return console.log(`[RTE]`),this.password===this.retypedPassword?``:`Passwords must match.`}},async created(){this.user=await getCurrentUser()},methods:{toggle(){log$2(`Toggling registration / login forms.`),this.$emit(`toggle`)},validateEmail(){this.emailError=!1,this.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email)?(this.emailError=!0,this.emailHint=`Please enter a valid email address`):this.emailHint=``},validateUsername(){this.usernameError=!1},async createUser(){if(this.awaitingResponse=!0,this.passwordError){Z$2({text:this.passwordError,status:Status.error}),this.awaitingResponse=!1;return}if(log$2(`