@vue-skuilder/standalone-ui 0.2.22 → 0.2.24
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/assets/{TagViewer-DTw1XW6s.js → TagViewer-CaWYUA6E.js} +2 -2
- package/dist/assets/{TagViewer-DTw1XW6s.js.map → TagViewer-CaWYUA6E.js.map} +1 -1
- package/dist/assets/{common-ui.es-Y_oscvt6.js → common-ui.es-C4k62zm7.js} +4 -4
- package/dist/assets/{common-ui.es-Y_oscvt6.js.map → common-ui.es-C4k62zm7.js.map} +1 -1
- package/dist/assets/common-ui.es-CP2uUBVn.js +1 -0
- package/dist/assets/{dist-CPj9LVe-.js → dist-sGjj1CQf.js} +13 -13
- package/dist/assets/{dist-CPj9LVe-.js.map → dist-sGjj1CQf.js.map} +1 -1
- package/dist/assets/{index-ahvM1xq8.js → index-DC8q8K83.js} +5 -5
- package/dist/assets/{index-ahvM1xq8.js.map → index-DC8q8K83.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist-lib/questions.cjs.js +12 -12
- package/dist-lib/questions.cjs.js.map +1 -1
- package/dist-lib/questions.mjs +95 -38
- package/dist-lib/questions.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/assets/common-ui.es-DmL6U7sK.js +0 -1
package/dist/index.html
CHANGED
|
@@ -9,11 +9,11 @@
|
|
|
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-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-DC8q8K83.js"></script>
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/dist-DCANvFNh.js">
|
|
14
|
-
<link rel="modulepreload" crossorigin href="/assets/dist-
|
|
14
|
+
<link rel="modulepreload" crossorigin href="/assets/dist-sGjj1CQf.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/MarkdownRenderer-kStoDRNE-lsnQ9xYB.js">
|
|
16
|
-
<link rel="modulepreload" crossorigin href="/assets/common-ui.es-
|
|
16
|
+
<link rel="modulepreload" crossorigin href="/assets/common-ui.es-C4k62zm7.js">
|
|
17
17
|
<link rel="stylesheet" crossorigin href="/assets/common-ui-BY2Ut5jf.css">
|
|
18
18
|
<link rel="stylesheet" crossorigin href="/assets/index-CAj8AHaU.css">
|
|
19
19
|
</head>
|
|
@@ -395,17 +395,17 @@ Examples:
|
|
|
395
395
|
window.skuilder.userdb.showScheduledReviews('course123')
|
|
396
396
|
window.skuilder.userdb.queryByType('SCHEDULED_CARD', 10)
|
|
397
397
|
window.skuilder.userdb.raw(db => db.allDocs({ limit: 5 }))
|
|
398
|
-
`)}},mountUserDBDebugger()}}),init_core=__esm({"src/core/index.ts"(){"use strict";init_interfaces(),init_types_legacy(),init_user(),init_strategyState(),init_userOutcome(),init_studySession(),init_hydration(),init_Loggable(),init_util(),init_navigators(),init_bulkImport(),init_orchestration(),init_UserDBDebugger()}}),init_core(),init_courseLookupDB(),init_logger(),init_couch(),init_util(),init_logger(),duration=hooks.duration,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_logger(),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)
|
|
399
|
-
User: ${JSON.stringify(
|
|
400
|
-
Card: ${JSON.stringify(
|
|
398
|
+
`)}},mountUserDBDebugger()}}),init_core=__esm({"src/core/index.ts"(){"use strict";init_interfaces(),init_types_legacy(),init_user(),init_strategyState(),init_userOutcome(),init_studySession(),init_hydration(),init_Loggable(),init_util(),init_navigators(),init_bulkImport(),init_orchestration(),init_UserDBDebugger()}}),init_core(),init_courseLookupDB(),init_logger(),init_couch(),init_util(),init_logger(),duration=hooks.duration,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_logger(),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:
|
|
399
|
+
User: ${JSON.stringify(E.userElo)})
|
|
400
|
+
Card: ${JSON.stringify(E.cardElo)})
|
|
401
401
|
`)}else logger.warn(`[EloService] Partial ELO update:
|
|
402
|
-
User ELO update: ${
|
|
403
|
-
Card ELO update: ${
|
|
404
|
-
User: ${JSON.stringify(
|
|
405
|
-
Card: ${JSON.stringify(
|
|
402
|
+
User ELO update: ${Sr?`SUCCESS`:`FAILED`}
|
|
403
|
+
Card ELO update: ${Cr?`SUCCESS`:`FAILED`}`),!Sr&&xr[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,xr[0].reason),!Cr&&xr[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,xr[1].reason);return O}return null}async updateUserAndCardEloPerTag(t,c,u,d,m){let g=this.dataLayer.getCourseDB(m.card.course_id),b=d.courses.find(t=>t.courseID===c);if(!b)return logger.error(`[EloService] No registration for course ${c} on user's registration doc \u2014 skipping per-tag ELO update for card ${u}. (Is the user registered for this course?)`),null;let S=toCourseElo(b.elo),[C,w]=await Promise.all([g.getCardEloData([m.card.card_id]),g.getAppliedTagsBatch([u])]),T=C[0],E=w.get(u)??[],D={...t},O=t._global;for(let t of E)t in D||(D[t]=O);if(T&&S){let t=S.global.score,d=T.global.score,m=Object.keys(D).filter(t=>t!==`_global`),C={};for(let t of m)C[t]=S.tags[t]?.score??S.global.score;let w=adjustCourseScoresPerTag(S,T,D);b.elo=w.userElo;let E={};for(let t of m){let c=D[t],u=c===null?C[t]:w.userElo.tags[t]?.score??C[t];E[t]={before:C[t],after:u,score:c}}let xr={cardId:u,at:new Date().toISOString(),userScore:O,global:{before:t,after:w.userElo.global.score},card:{before:d,after:w.cardElo.global.score},...m.length?{tags:E}:{}},Sr=await Promise.allSettled([this.user.updateUserElo(c,w.userElo),g.updateCardElo(u,w.cardElo)]),Cr=Sr[0].status===`fulfilled`,wr=Sr[1].status===`fulfilled`;if(Cr&&wr){let t=Sr[0].value,c=Sr[1].value;if(t.ok&&c&&c.ok){let t=Object.keys(D).length-1;logger.info(`[EloService] Updated ELOS (per-tag, ${t} tags):
|
|
404
|
+
User: ${JSON.stringify(w.userElo)})
|
|
405
|
+
Card: ${JSON.stringify(w.cardElo)})
|
|
406
406
|
`)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
|
|
407
|
-
User ELO update: ${
|
|
408
|
-
Card ELO update: ${
|
|
407
|
+
User ELO update: ${Cr?`SUCCESS`:`FAILED`}
|
|
408
|
+
Card ELO update: ${wr?`SUCCESS`:`FAILED`}`),!Cr&&Sr[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,Sr[0].reason),!wr&&Sr[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,Sr[1].reason);return xr}return null}},init_core(),init_logger(),ResponseProcessor=class{constructor(t,c,u){_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`onEloEvent`,void 0),this.srsService=t,this.eloService=c,this.onEloEvent=u}logEloFailure(t,c){return u=>logger.error(`[ResponseProcessor] ELO update failed (${t}) for ${c}:`,u)}trackElo(t,c,u){t.then(t=>{t&&this.onEloEvent?.(t)}).catch(this.logEloFailure(c,u))}parsePerformance(t){return typeof t==`number`?{globalScore:t,taggedPerformance:null}:isTaggedPerformance(t)?{globalScore:t._global,taggedPerformance:t}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:t}),{globalScore:.5,taggedPerformance:null})}async processResponse(t,c,u,d,m,g,b,S,C,w){if(!isQuestionRecord(t))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let T=await c,E;return E=t.isCorrect?this.processCorrectResponse(t,T,u,d,m,g,b,C,w):this.processIncorrectResponse(t,T,d,m,g,b,S,C,w),t.deferAdvance&&E.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:E.nextCardAction}),E={...E,shouldLoadNextCard:!1,deferred:!0}),E}catch(t){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e:t,cardId:b}),t}}processCorrectResponse(t,c,u,d,m,g,b,S,C){if(t.priorAttemps===0){m.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(c,u);let{globalScore:S,taggedPerformance:C}=this.parsePerformance(t.performance);if(C){let u=Object.keys(C).filter(t=>t!==`_global`),S=u.filter(t=>C[t]===null),w=u.filter(t=>C[t]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}): scored=[${w.join(`, `)}] count-only=[${S.join(`, `)}]`),this.trackElo(this.eloService.updateUserAndCardEloPerTag(C,g,b,d,m),`correct per-tag`,b)}else{let u=.5+S/2;if(c.records.length===1)this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m),`correct`,b);else{let t=Math.ceil(32/c.records.length);this.trackElo(this.eloService.updateUserAndCardElo(u,g,b,d,m,t),`correct repeat-view`,b)}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${u.toFixed(3)}) for ${b} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:S,shouldClearFeedbackShadow:!0}}else{let c=C>=S;logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${C}/${S} -> ${c?`dismiss-success`:`marked-failed`}`);let{globalScore:u}=this.parsePerformance(t.performance);return{nextCardAction:c?`dismiss-success`:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:u,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(t,c,u,d,m,g,b,S,C){let{taggedPerformance:w}=this.parsePerformance(t.performance),T=!1;return t.priorAttemps===0?(w?(this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`incorrect per-tag`,g),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps}, tags=${Object.keys(w).length-1})`)):(this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`incorrect`,g),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`)),T=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${g} (historyLen=${c.records.length}, priorAttemps=${t.priorAttemps})`),d.records.length>=b?C>=S?(T?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${g}`):(w?this.trackElo(this.eloService.updateUserAndCardEloPerTag(w,m,g,u,d),`dismiss-failed per-tag`,g):this.trackElo(this.eloService.updateUserAndCardElo(0,m,g,u,d),`dismiss-failed`,g),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${g} (historyLen=${c.records.length}, sessionViews=${C})`)),{nextCardAction:`dismiss-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}):{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!1,shouldClearFeedbackShadow:!0}:{nextCardAction:`none`,shouldLoadNextCard:!1,isCorrect:!1,shouldClearFeedbackShadow:!0}}},init_logger(),CardHydrationService=class{constructor(t,c,u){_defineProperty$2(this,`hydratedCards`,new Map),_defineProperty$2(this,`hydrationInFlight`,new Set),_defineProperty$2(this,`hydrationInProgress`,!1),this.getViewComponent=t,this.getCourseDB=c,this.getItemsToHydrate=u}getHydratedCard(t){return this.hydratedCards.get(t)??null}hasHydratedCard(t){return this.hydratedCards.has(t)}removeCard(t){this.hydratedCards.delete(t)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(t){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);this.hydrationInProgress||this.fillHydratedCards();let c=1e4,u=25,d=0;for(;d<1e4;){if(this.hydratedCards.has(t))return this.hydratedCards.get(t);if(!this.hydrationInFlight.has(t)&&!this.hydrationInProgress)break;await new Promise(t=>setTimeout(t,25)),d+=25}return this.hydratedCards.get(t)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let t=this.getItemsToHydrate();for(let c of t)if(!(this.hydratedCards.has(c.cardID)||this.hydrationInFlight.has(c.cardID)))try{await this.hydrateCard(c)}catch(t){logger.error(`[CardHydrationService] Error hydrating card ${c.cardID}:`,t)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(t){if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID))){this.hydrationInFlight.add(t.cardID);try{let c=this.getCourseDB(t.courseID),[u,d]=await Promise.all([c.getCourseDoc(t.cardID),c.getAppliedTagsBatch([t.cardID])]);isCourseElo(u.elo)||(u.elo=toCourseElo(u.elo));let m=this.getViewComponent(u.id_view),g=await Promise.all(u.id_displayable_data.map(t=>c.getCourseDoc(t,{attachments:!0,binary:!0}))),b=[];g.forEach(t=>{t.data.forEach(t=>{b.push(...parseAudioURIs(t.data))})});let S=[...new Set(b)];S.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${S.length} audio files for card ${t.cardID}`),await Promise.allSettled(S.map(prefetchAudio)));let C=g.map(displayableDataToViewData).reverse();this.hydratedCards.set(t.cardID,{item:{...t,elo:toCourseElo(u.elo).global.score},view:m,data:C,tags:d.get(t.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${t.cardID}`)}finally{this.hydrationInFlight.delete(t.cardID)}}}},ItemQueue=class{constructor(){_defineProperty$2(this,`q`,[]),_defineProperty$2(this,`seenCardIds`,[]),_defineProperty$2(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(t,c){this.seenCardIds.find(t=>t===c)||(this.seenCardIds.push(c),this.q.push(t))}addAll(t,c){t.forEach(t=>this.add(t,c(t)))}get length(){return this.q.length}peek(t){return this.q[t]}dequeue(t){if(this.q.length!==0){this._dequeueCount++;let c=this.q.splice(0,1)[0];if(t){let u=t(c),d=this.seenCardIds.indexOf(u);d>-1&&this.seenCardIds.splice(d,1)}return c}else return null}replaceAll(t,c){this.q=[],this.seenCardIds=[];for(let u of t){let t=c(u);this.seenCardIds.includes(t)||(this.seenCardIds.push(t),this.q.push(u))}}mergeToFront(t,c,u){let d=0,m=[];for(let g of t){let t=c(g);if(!this.seenCardIds.includes(t))this.seenCardIds.push(t),m.push(g),d++;else if(u?.has(t)){let u=this.q.findIndex(u=>c(u)===t);u>=0&&m.push(...this.q.splice(u,1))}}return this.q.unshift(...m),d}get toString(){return`${typeof this.q[0]}:
|
|
409
409
|
`+this.q.map(t=>` ${t.courseID}+${t.cardID}: ${t.status}`).join(`
|
|
410
410
|
`)}},init_couch(),init_core(),init_types_legacy(),init_studySession(),init_recording(),init_Loggable(),init_types_legacy(),init_logger(),CouchDBToStaticPacker=class{constructor(t={}){_defineProperty$2(this,`config`,void 0),_defineProperty$2(this,`sourceDB`,null),this.config={chunkSize:1e3,includeAttachments:!0,...t}}async packCourse(t,c){logger.info(`Starting static pack for course: ${c}`),this.sourceDB=t;let u={version:`1.0.0`,courseId:c,courseName:``,courseConfig:null,lastUpdated:new Date().toISOString(),documentCount:0,chunks:[],indices:[],designDocs:[]},d=await this.extractCourseConfig(t);u.courseName=d.name,u.courseConfig=d,u.designDocs=await this.extractDesignDocs(t);let m=await this.extractDocumentsByType(t),g=new Map;this.config.includeAttachments&&await this.extractAllAttachments(m,g);let b=new Map;for(let[t,c]of Object.entries(m)){let d=this.createChunks(c,t);u.chunks.push(...d),u.documentCount+=c.length,this.prepareChunkData(d,c,b)}let S=new Map;return u.indices=await this.buildIndices(m,u.designDocs,S),{manifest:u,chunks:b,indices:S,attachments:g}}async packCourseToFiles(t,c,u,d){logger.info(`Packing course ${c} to files in ${u}`);let m=await this.packCourse(t,c),g=await this.writePackedDataToFiles(m,u,d);return{manifest:m.manifest,filesWritten:g,attachmentsFound:m.attachments?m.attachments.size:0}}async writePackedDataToFiles(t,c,u){let d=0;await u.ensureDir(c);let m=u.joinPath(c,`manifest.json`);await u.writeJson(m,t.manifest,{spaces:2}),d++,logger.info(`Wrote manifest: ${m}`);let g=u.joinPath(c,`chunks`),b=u.joinPath(c,`indices`);await u.ensureDir(g),await u.ensureDir(b);for(let[c,m]of t.chunks){let t=u.joinPath(g,`${c}.json`);await u.writeJson(t,m),d++}logger.info(`Wrote ${t.chunks.size} chunk files`);for(let[c,m]of t.indices){let t=u.joinPath(b,`${c}.json`);await u.writeJson(t,m,{spaces:2}),d++}if(logger.info(`Wrote ${t.indices.size} index files`),t.attachments&&t.attachments.size>0){for(let[m,g]of t.attachments){let t=u.joinPath(c,m),b=u.dirname(t);await u.ensureDir(b),await u.writeFile(t,g.buffer),d++}logger.info(`Wrote ${t.attachments.size} attachment files`)}return d}async extractCourseConfig(t){try{return await t.get(`CourseConfig`)}catch(t){throw logger.error(`Failed to extract course config:`,t),Error(`Course config not found`)}}async extractDesignDocs(t){return(await t.allDocs({startkey:`_design/`,endkey:`_design/`,include_docs:!0})).rows.map(t=>({_id:t.id,views:t.doc.views||{}}))}async extractDocumentsByType(t){let c=await t.allDocs({include_docs:!0}),u={};for(let t of c.rows){if(t.id.startsWith(`_`))continue;let c=t.doc;c.docType&&(u[c.docType]||(u[c.docType]=[]),u[c.docType].push(c))}return u}createChunks(t,c){let u=[],d=t.sort((t,c)=>t._id.localeCompare(c._id));for(let t=0;t<d.length;t+=this.config.chunkSize){let m=d.slice(t,t+this.config.chunkSize),g=`${c}-${String(Math.floor(t/this.config.chunkSize)).padStart(4,`0`)}`;u.push({id:g,docType:c,startKey:m[0]._id,endKey:m[m.length-1]._id,documentCount:m.length,path:`chunks/${g}.json`})}return u}prepareChunkData(t,c,u){let d=c.sort((t,c)=>t._id.localeCompare(c._id));for(let c of t){let t=d.filter(t=>t._id>=c.startKey&&t._id<=c.endKey).map(t=>{let c={...t};return delete c._rev,this.config.includeAttachments&&c._attachments?c._attachments=this.transformAttachmentStubs(c._attachments,c._id):this.config.includeAttachments||delete c._attachments,c});u.set(c.id,t)}}async buildIndices(t,c,u){let d=[];if(t.CARD){let c=await this.buildEloIndex(t.CARD,u);d.push(c)}if(t.TAG){let c=await this.buildTagIndex(t.TAG,u);d.push(c)}for(let t of c)for(let[c,m]of Object.entries(t.views))if(m.map){logger.info(`Processing view: ${t._id}/${c}`);let m=await this.buildViewIndex(c,t,u);m?(d.push(m),logger.info(`Successfully built index: ${m.name}`)):logger.warn(`Skipped view index: ${t._id}/${c}`)}return d}async buildEloIndex(t,c){let u=[];for(let c of t)c.elo?.global?.score&&u.push({elo:c.elo.global.score,cardId:c._id});u.sort((t,c)=>t.elo-c.elo);let d={},m=50;for(let t of u){let c=Math.floor(t.elo/50)*50;d[c]||(d[c]=[]),d[c].push(t.cardId)}return c.set(`elo`,{sorted:u,buckets:d,stats:{min:u[0]?.elo||0,max:u[u.length-1]?.elo||0,count:u.length}}),{name:`elo`,type:`btree`,path:`indices/elo.json`}}async buildTagIndex(t,c){let u={};for(let c of t)u[c.name]={cardIds:c.taggedCards,snippet:c.snippet,count:c.taggedCards.length};let d={};for(let c of t)for(let t of c.taggedCards)d[t]||(d[t]=[]),d[t].push(c.name);return c.set(`tags`,{byTag:u,byCard:d}),{name:`tags`,type:`hash`,path:`indices/tags.json`}}async buildViewIndex(t,c,u){if(!this.sourceDB)return logger.error(`Source database not available for view querying`),null;try{let d=`${c._id.replace(`_design/`,``)}/${t}`;logger.info(`Querying CouchDB view: ${d}`);let m=await this.sourceDB.query(d,{include_docs:!1});if(!m.rows||m.rows.length===0)return logger.warn(`View ${d} returned no results`),null;logger.info(`Successfully queried view ${d}: ${m.rows.length} results`);let g=this.formatViewResults(t,m.rows,c),b=`view-${c._id.replace(`_design/`,``)}-${t}`;return u.set(b,g),{name:b,type:`view`,path:`indices/${b}.json`}}catch(u){return logger.error(`Failed to query view ${c._id}/${t}:`,u),null}}formatViewResults(t,c,u){let d={type:`couchdb-view`,viewName:t,designDoc:u._id,results:c,metadata:{resultCount:c.length,generatedAt:new Date().toISOString()}};switch(t){case`elo`:return this.formatEloViewIndex(c,d);case`getTags`:return this.formatTagsViewIndex(c,d);case`cardsByInexperience`:return this.formatInexperienceViewIndex(c,d);default:return this.formatGenericViewIndex(c,d)}}formatEloViewIndex(t,c){let u=t.sort((t,c)=>typeof t.key==`number`&&typeof c.key==`number`?t.key-c.key:0);return{...c,sorted:u,stats:{min:u[0]?.key||0,max:u[u.length-1]?.key||0,count:u.length}}}formatTagsViewIndex(t,c){let u={};for(let c of t){let t=c.key;typeof t==`string`&&(u[t]||(u[t]=[]),u[t].push(c.id))}return{...c,byTag:u,tagCount:Object.keys(u).length}}formatInexperienceViewIndex(t,c){let u=t.sort((t,c)=>typeof t.key==`number`&&typeof c.key==`number`?t.key-c.key:0);return{...c,sorted:u,stats:{minInexperience:u[0]?.key||0,maxInexperience:u[u.length-1]?.key||0,count:u.length}}}formatGenericViewIndex(t,c){return{...c}}async extractAllAttachments(t,c){logger.info(`Extracting attachments...`);let u=[];for(let c of Object.values(t))u.push(...c);let d=u.filter(t=>t._attachments&&Object.keys(t._attachments).length>0);if(d.length===0){logger.info(`No attachments found`);return}logger.info(`Found ${d.length} documents with attachments`);let m=d.map(t=>this.extractDocumentAttachments(t,c));await Promise.all(m),logger.info(`Extracted ${c.size} attachment files`)}async extractDocumentAttachments(t,c){if(!t._attachments||!this.sourceDB)return;let u=t._id;for(let[d,m]of Object.entries(t._attachments))try{let t=await this.sourceDB.getAttachment(u,d),g;if(t instanceof ArrayBuffer)g=Buffer.from(t);else if(Buffer.isBuffer(t))g=t;else{let c=t;g=Buffer.from(await c.arrayBuffer())}let b=`${d}${this.getFileExtension(m.content_type)}`,S=`attachments/${u}/${b}`;c.set(S,{docId:u,attachmentName:d,filename:b,path:S,contentType:m.content_type,length:m.length||g.length,digest:m.digest,buffer:g}),logger.debug(`Extracted attachment: ${S}`)}catch(t){throw logger.error(`Failed to extract attachment ${u}/${d}:`,t),Error(`Failed to extract attachment ${u}/${d}: ${t}`)}}transformAttachmentStubs(t,c){let u={};for(let[d,m]of Object.entries(t))u[d]={path:`attachments/${c}/${`${d}${this.getFileExtension(m.content_type)}`}`,content_type:m.content_type,length:m.length,digest:m.digest,stub:!1};return u}getFileExtension(t){return{"image/jpeg":`.jpg`,"image/jpg":`.jpg`,"image/png":`.png`,"image/gif":`.gif`,"image/webp":`.webp`,"audio/mpeg":`.mp3`,"audio/mp3":`.mp3`,"audio/wav":`.wav`,"audio/ogg":`.ogg`,"video/mp4":`.mp4`,"video/webm":`.webm`,"application/pdf":`.pdf`,"text/plain":`.txt`,"application/json":`.json`}[t]||``}},init_logger(),DEFAULT_MIGRATION_OPTIONS={chunkBatchSize:100,validateRoundTrip:!1,cleanupOnFailure:!0,timeout:3e5},init_logger(),FileSystemError=class extends Error{constructor(t,c,u,d){super(t),this.operation=c,this.filePath=u,this.cause=d,this.name=`FileSystemError`}},nodeFS2=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS2=eval(`require`)(`fs`),nodeFS2.promises=nodeFS2.promises||eval(`require`)(`fs`).promises)}catch{}nodeFS3=null,nodePath=null;try{typeof window>`u`&&typeof process<`u`&&process.versions?.node&&(nodeFS3=eval(`require`)(`fs`),nodePath=eval(`require`)(`path`),nodeFS3.promises=nodeFS3.promises||eval(`require`)(`fs`).promises)}catch{}StaticToCouchDBMigrator=class{constructor(t={},c){_defineProperty$2(this,`options`,void 0),_defineProperty$2(this,`progressCallback`,void 0),_defineProperty$2(this,`fs`,void 0),this.options={...DEFAULT_MIGRATION_OPTIONS,...t},this.fs=c}setProgressCallback(t){this.progressCallback=t}async migrateCourse(t,c){let u=Date.now(),d={success:!1,documentsRestored:0,attachmentsRestored:0,designDocsRestored:0,courseConfigRestored:0,errors:[],warnings:[],migrationTime:0};try{logger.info(`Starting migration from ${t} to CouchDB`),this.reportProgress(`manifest`,0,1,`Validating static course...`);let m=await validateStaticCourse(t,this.fs);if(!m.valid)throw d.errors.push(...m.errors),Error(`Static course validation failed: ${m.errors.join(`, `)}`);d.warnings.push(...m.warnings),this.reportProgress(`manifest`,1,1,`Loading course manifest...`);let g=await this.loadManifest(t);logger.info(`Loaded manifest for course: ${g.courseId} (${g.courseName})`),this.reportProgress(`design_docs`,0,g.designDocs.length,`Restoring design documents...`);let b=await this.restoreDesignDocuments(g.designDocs,c);d.designDocsRestored=b.restored,d.errors.push(...b.errors),d.warnings.push(...b.warnings),this.reportProgress(`course_config`,0,1,`Restoring CourseConfig document...`);let S=await this.restoreCourseConfig(g,c);d.courseConfigRestored=S.restored,d.errors.push(...S.errors),d.warnings.push(...S.warnings),this.reportProgress(`course_config`,1,1,`CourseConfig document restored`);let C=this.calculateExpectedCounts(g);this.reportProgress(`documents`,0,g.documentCount,`Aggregating documents from chunks...`);let w=await this.aggregateDocuments(t,g),T=w.filter(t=>t._id!==`CourseConfig`);w.length!==T.length&&d.warnings.push(`Filtered out ${w.length-T.length} CourseConfig document(s) from chunks to prevent conflicts`),this.reportProgress(`documents`,T.length,g.documentCount,`Uploading documents to CouchDB...`);let E=await this.uploadDocuments(T,c);d.documentsRestored=E.restored,d.errors.push(...E.errors),d.warnings.push(...E.warnings);let D=w.filter(t=>t._attachments&&Object.keys(t._attachments).length>0);this.reportProgress(`attachments`,0,D.length,`Uploading attachments...`);let O=await this.uploadAttachments(t,D,c);if(d.attachmentsRestored=O.restored,d.errors.push(...O.errors),d.warnings.push(...O.warnings),this.options.validateRoundTrip){this.reportProgress(`validation`,0,1,`Validating migration...`);let t=await validateMigration(c,C,g);t.valid||(d.warnings.push(`Migration validation found issues`),t.issues.forEach(t=>{t.type===`error`?d.errors.push(`Validation: ${t.message}`):d.warnings.push(`Validation: ${t.message}`)})),this.reportProgress(`validation`,1,1,`Migration validation completed`)}d.success=d.errors.length===0,d.migrationTime=Date.now()-u,logger.info(`Migration completed in ${d.migrationTime}ms`),logger.info(`Documents restored: ${d.documentsRestored}`),logger.info(`Attachments restored: ${d.attachmentsRestored}`),logger.info(`Design docs restored: ${d.designDocsRestored}`),logger.info(`CourseConfig restored: ${d.courseConfigRestored}`),d.errors.length>0&&logger.error(`Migration completed with ${d.errors.length} errors`),d.warnings.length>0&&logger.warn(`Migration completed with ${d.warnings.length} warnings`)}catch(t){d.success=!1,d.migrationTime=Date.now()-u;let m=t instanceof Error?t.message:String(t);if(d.errors.push(`Migration failed: ${m}`),logger.error(`Migration failed:`,t),this.options.cleanupOnFailure)try{await this.cleanupFailedMigration(c)}catch(t){logger.error(`Failed to cleanup after migration failure:`,t),d.warnings.push(`Failed to cleanup after migration failure`)}}return d}async loadManifest(t){try{let c,u;if(this.fs)u=this.fs.joinPath(t,`manifest.json`),c=await this.fs.readFile(u);else if(u=nodeFS3&&nodePath?nodePath.join(t,`manifest.json`):`${t}/manifest.json`,nodeFS3&&this.isLocalPath(t))c=await nodeFS3.promises.readFile(u,`utf8`);else{let t=await fetch(u);if(!t.ok)throw Error(`Failed to fetch manifest: ${t.status} ${t.statusText}`);c=await t.text()}let d=JSON.parse(c);if(!d.version||!d.courseId||!d.chunks)throw Error(`Invalid manifest structure`);return d}catch(t){let c=t instanceof FileSystemError?t.message:`Failed to load manifest: ${t instanceof Error?t.message:String(t)}`;throw Error(c)}}async restoreDesignDocuments(t,c){let u={restored:0,errors:[],warnings:[]};for(let d=0;d<t.length;d++){let m=t[d];this.reportProgress(`design_docs`,d,t.length,`Restoring ${m._id}...`);try{let t;try{t=await c.get(m._id)}catch{}let d={_id:m._id,views:m.views};t?(d._rev=t._rev,logger.debug(`Updating existing design document: ${m._id}`)):logger.debug(`Creating new design document: ${m._id}`),await c.put(d),u.restored++}catch(t){let c=`Failed to restore design document ${m._id}: ${t instanceof Error?t.message:String(t)}`;u.errors.push(c),logger.error(c)}}return this.reportProgress(`design_docs`,t.length,t.length,`Restored ${u.restored} design documents`),u}async aggregateDocuments(t,c){let u=[],d=new Map;for(let m=0;m<c.chunks.length;m++){let g=c.chunks[m];this.reportProgress(`documents`,u.length,c.documentCount,`Loading chunk ${g.id}...`);try{let c=await this.loadChunk(t,g);for(let t of c){if(!t._id){logger.warn(`Document without _id found in chunk ${g.id}, skipping`);continue}d.has(t._id)&&logger.warn(`Duplicate document ID found: ${t._id}, using latest version`),d.set(t._id,t)}}catch(t){throw Error(`Failed to load chunk ${g.id}: ${t instanceof Error?t.message:String(t)}`)}}return u.push(...d.values()),logger.info(`Aggregated ${u.length} unique documents from ${c.chunks.length} chunks`),u}async loadChunk(t,c){try{let u,d;if(this.fs)d=this.fs.joinPath(t,c.path),u=await this.fs.readFile(d);else if(d=nodeFS3&&nodePath?nodePath.join(t,c.path):`${t}/${c.path}`,nodeFS3&&this.isLocalPath(t))u=await nodeFS3.promises.readFile(d,`utf8`);else{let t=await fetch(d);if(!t.ok)throw Error(`Failed to fetch chunk: ${t.status} ${t.statusText}`);u=await t.text()}let m=JSON.parse(u);if(!Array.isArray(m))throw Error(`Chunk file does not contain an array of documents`);return m}catch(t){let c=t instanceof FileSystemError?t.message:`Failed to load chunk: ${t instanceof Error?t.message:String(t)}`;throw Error(c)}}async uploadDocuments(t,c){let u={restored:0,errors:[],warnings:[]},d=this.options.chunkBatchSize;for(let m=0;m<t.length;m+=d){let g=t.slice(m,m+d);this.reportProgress(`documents`,m,t.length,`Uploading batch ${Math.floor(m/d)+1}...`);try{let t=g.map(t=>{let c={...t};return delete c._rev,delete c._attachments,c}),d=await c.bulkDocs(t);for(let t=0;t<d.length;t++){let c=d[t],m=g[t];if(`error`in c){let t=`Failed to upload document ${m._id}: ${c.error} - ${c.reason}`;u.errors.push(t),logger.error(t)}else u.restored++}}catch(t){let c;c=t instanceof Error||t&&typeof t==`object`&&`message`in t?`Failed to upload document batch starting at index ${m}: ${t.message}`:`Failed to upload document batch starting at index ${m}: ${JSON.stringify(t)}`,u.errors.push(c),logger.error(c)}}return this.reportProgress(`documents`,t.length,t.length,`Uploaded ${u.restored} documents`),u}async uploadAttachments(t,c,u){let d={restored:0,errors:[],warnings:[]},m=0;for(let g of c)if(this.reportProgress(`attachments`,m,c.length,`Processing attachments for ${g._id}...`),m++,g._attachments)for(let[c,m]of Object.entries(g._attachments))try{let b=await this.uploadSingleAttachment(t,g._id,c,m,u);b.success?d.restored++:d.errors.push(b.error||`Unknown attachment upload error`)}catch(t){let u=`Failed to upload attachment ${g._id}/${c}: ${t instanceof Error?t.message:String(t)}`;d.errors.push(u),logger.error(u)}return this.reportProgress(`attachments`,c.length,c.length,`Uploaded ${d.restored} attachments`),d}async uploadSingleAttachment(t,c,u,d,m){let g={success:!1,attachmentName:u,docId:c};try{if(!d.path)return g.error=`Attachment metadata missing file path`,g;let b,S;if(this.fs)S=this.fs.joinPath(t,d.path),b=await this.fs.readBinary(S);else if(S=nodeFS3&&nodePath?nodePath.join(t,d.path):`${t}/${d.path}`,nodeFS3&&this.isLocalPath(t))b=await nodeFS3.promises.readFile(S);else{let t=await fetch(S);if(!t.ok)return g.error=`Failed to fetch attachment: ${t.status} ${t.statusText}`,g;b=await t.arrayBuffer()}let C=await m.get(c);await m.putAttachment(c,u,C._rev,b,d.content_type),g.success=!0}catch(t){g.error=t instanceof Error?t.message:String(t)}return g}async restoreCourseConfig(t,c){let u={restored:0,errors:[],warnings:[]};try{if(!t.courseConfig)return u.warnings.push(`No courseConfig found in manifest, skipping CourseConfig document creation`),u;let d={_id:`CourseConfig`,...t.courseConfig,courseID:t.courseId};delete d._rev,await c.put(d),u.restored=1,logger.info(`CourseConfig document created for course: ${t.courseId}`)}catch(t){let c=t instanceof Error?t.message:JSON.stringify(t);u.errors.push(`Failed to restore CourseConfig: ${c}`),logger.error(`CourseConfig restoration failed:`,t)}return u}calculateExpectedCounts(t){let c={};for(let u of t.chunks)c[u.docType]=(c[u.docType]||0)+u.documentCount;return t.designDocs.length>0&&(c._design=t.designDocs.length),c}async cleanupFailedMigration(t){logger.info(`Cleaning up failed migration...`);try{let c=(await t.allDocs()).rows.map(t=>({_id:t.id,_rev:t.value.rev,_deleted:!0}));c.length>0&&(await t.bulkDocs(c),logger.info(`Cleaned up ${c.length} documents from failed migration`))}catch(t){throw logger.error(`Failed to cleanup documents:`,t),t}}reportProgress(t,c,u,d){this.progressCallback&&this.progressCallback({phase:t,current:c,total:u,message:d})}isLocalPath(t){return!t.startsWith(`http://`)&&!t.startsWith(`https://`)}},init_dataDirectory(),init_navigators(),init_Pipeline(),QuotaRoundRobinMixer=class{mix(t,c){if(t.length===0)return[];let u=Math.ceil(c/t.length),d=t.map(t=>[...t.weighted].sort((t,c)=>c.score-t.score).slice(0,u));for(let t=d.length-1;t>0;t--){let c=Math.floor(Math.random()*(t+1));[d[t],d[c]]=[d[c],d[t]]}let m=[],g=0,b=Array(d.length).fill(0);for(;m.length<c&&g<d.length;){g=0;for(let t=0;t<d.length&&!(m.length>=c);t++)b[t]<d[t].length?(m.push(d[t][b[t]]),b[t]++):g++}return m}},init_logger(),init_navigators(),MAX_RUNS2=10,runHistory2=[],mixerDebugAPI={get runs(){return[...runHistory2]},showRun(t=0){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let c;if(typeof t==`number`){if(c=runHistory2[t],!c){logger.info(`[Mixer Debug] No run found at index ${t}. History length: ${runHistory2.length}`);return}}else if(c=runHistory2.find(c=>c.runId.endsWith(t)),!c){logger.info(`[Mixer Debug] No run found matching ID '${t}'.`);return}printMixerSummary(c)},showLastMix(){this.showRun(0)},explainSourceBalance(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t=runHistory2[0];console.group(`⚖️ Source Balance Analysis`),logger.info(`Mixer: ${t.mixerType}`),logger.info(`Requested limit: ${t.requestedLimit}`),t.quotaPerSource&&logger.info(`Quota per source: ${t.quotaPerSource}`),console.group(`Input Distribution:`);for(let c of t.sourceSummaries){let t=c.sourceName||c.sourceId;logger.info(`${t}:`),logger.info(` Provided: ${c.totalCards} cards (${c.reviewCount} reviews, ${c.newCount} new)`),logger.info(` Score range: [${c.scoreRange[0].toFixed(2)}, ${c.scoreRange[1].toFixed(2)}]`)}console.groupEnd(),console.group(`Selection Results:`);for(let c of t.sourceBreakdowns){let t=c.sourceName||c.sourceId;logger.info(`${t}:`),logger.info(` Selected: ${c.totalSelected}/${c.reviewsProvided+c.newProvided} (${c.selectionRate.toFixed(1)}%)`),logger.info(` Reviews: ${c.reviewsSelected}/${c.reviewsProvided}`),logger.info(` New: ${c.newSelected}/${c.newProvided}`),c.reviewsProvided>0&&c.reviewsSelected===0&&logger.info(` ⚠️ Had reviews but none selected!`),c.totalSelected===0&&c.reviewsProvided+c.newProvided>0&&logger.info(` ⚠️ Had cards but none selected!`)}console.groupEnd();let c=t.sourceBreakdowns.map(t=>t.selectionRate),u=c.reduce((t,c)=>t+c,0)/c.length,d=Math.max(...c.map(t=>Math.abs(t-u)));d>20&&(logger.info(`
|
|
411
411
|
\u26A0\uFE0F Significant imbalance detected (max deviation: ${d.toFixed(1)}%)`),logger.info(`Possible causes:`),logger.info(` - Score range differences between sources`),logger.info(` - One source has much better quality cards`),logger.info(` - Different card availability (reviews vs new)`)),console.groupEnd()},compareScores(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t=runHistory2[0];console.group(`📊 Score Distribution Comparison`),console.table(t.sourceSummaries.map(t=>({source:t.sourceName||t.sourceId,cards:t.totalCards,min:t.bottomScore.toFixed(3),max:t.topScore.toFixed(3),avg:t.avgScore.toFixed(3),range:(t.topScore-t.bottomScore).toFixed(3)})));let c=t.sourceSummaries.map(t=>t.topScore-t.bottomScore),u=t.sourceSummaries.map(t=>t.avgScore),d=Math.max(...c)-Math.min(...c),m=Math.max(...u)-Math.min(...u);(d>.3||m>.2)&&(logger.info(`
|
|
@@ -449,15 +449,15 @@ Example:
|
|
|
449
449
|
window.skuilder.session.showInterleaving()
|
|
450
450
|
window.skuilder.session.showQueue()
|
|
451
451
|
`)}},mountSessionDebugger(),init_logger(),SessionController=(_SessionController2=class _SessionController extends Loggable{set sessionRecord(t){this._sessionRecord=t}get secondsRemaining(){return this._secondsRemaining}get hasCardGuarantee(){return this._minCardsGuarantee>0}get report(){let t=this.supplyQ.dequeueCount;return`${t} supply ${t===1?`card`:`cards`} drawn`}get detailedReport(){return this.supplyQ.toString+`
|
|
452
|
-
`+this.failedQ.toString}constructor(t,c,u,d,m,g){super(),_defineProperty$2(this,`_className`,`SessionController`),_defineProperty$2(this,`services`,void 0),_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`hydrationService`,void 0),_defineProperty$2(this,`mixer`,void 0),_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`courseNameCache`,new Map),_defineProperty$2(this,`_defaultBatchLimit`,20),_defineProperty$2(this,`sources`,void 0),_defineProperty$2(this,`_sessionRecord`,[]),_defineProperty$2(this,`_currentCard`,null),_defineProperty$2(this,`supplyQ`,new ItemQueue),_defineProperty$2(this,`failedQ`,new ItemQueue),_defineProperty$2(this,`_supplyDrawsSinceFailed`,0),_defineProperty$2(this,`_replanPromise`,null),_defineProperty$2(this,`_activeReplanLabel`,null),_defineProperty$2(this,`_wellIndicatedRemaining`,0),_defineProperty$2(this,`_suppressQualityReplan`,!1),_defineProperty$2(this,`_minCardsGuarantee`,0),_defineProperty$2(this,`_sessionHints`,null),_defineProperty$2(this,`_servedCardIds`,new Set),_defineProperty$2(this,`_outcomeObservers`,[]),_defineProperty$2(this,`_sessionControls`,null),_defineProperty$2(this,`sessionId`,void 0),_defineProperty$2(this,`_courseId`,void 0),_defineProperty$2(this,`_stateSnapshotProvider`,void 0),_defineProperty$2(this,`_sessionDoc`,null),_defineProperty$2(this,`_openDocPromise`,null),_defineProperty$2(this,`_runLog`,[]),_defineProperty$2(this,`_sessionClosed`,!1),_defineProperty$2(this,`startTime`,void 0),_defineProperty$2(this,`endTime`,void 0),_defineProperty$2(this,`_secondsRemaining`,void 0),_defineProperty$2(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=u,this.mixer=m||new QuotaRoundRobinMixer,this.srsService=new SrsService(u.getUserDB()),this.eloService=new EloService(u,u.getUserDB()),this.hydrationService=new CardHydrationService(d,t=>u.getCourseDB(t),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService)},this.sources=t,this.startTime=new Date,this._secondsRemaining=c,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),g?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=g.defaultBatchLimit),g?.outcomeObservers?.length&&(this._outcomeObservers=[...g.outcomeObservers]),this._courseId=g?.courseId,this._stateSnapshotProvider=g?.stateSnapshotProvider,this.log(`Session constructed:
|
|
452
|
+
`+this.failedQ.toString}constructor(t,c,u,d,m,g){super(),_defineProperty$2(this,`_className`,`SessionController`),_defineProperty$2(this,`services`,void 0),_defineProperty$2(this,`srsService`,void 0),_defineProperty$2(this,`eloService`,void 0),_defineProperty$2(this,`hydrationService`,void 0),_defineProperty$2(this,`mixer`,void 0),_defineProperty$2(this,`dataLayer`,void 0),_defineProperty$2(this,`courseNameCache`,new Map),_defineProperty$2(this,`_defaultBatchLimit`,20),_defineProperty$2(this,`sources`,void 0),_defineProperty$2(this,`_sessionRecord`,[]),_defineProperty$2(this,`_currentCard`,null),_defineProperty$2(this,`supplyQ`,new ItemQueue),_defineProperty$2(this,`failedQ`,new ItemQueue),_defineProperty$2(this,`_supplyDrawsSinceFailed`,0),_defineProperty$2(this,`_replanPromise`,null),_defineProperty$2(this,`_activeReplanLabel`,null),_defineProperty$2(this,`_wellIndicatedRemaining`,0),_defineProperty$2(this,`_suppressQualityReplan`,!1),_defineProperty$2(this,`_minCardsGuarantee`,0),_defineProperty$2(this,`_sessionHints`,null),_defineProperty$2(this,`_servedCardIds`,new Set),_defineProperty$2(this,`_outcomeObservers`,[]),_defineProperty$2(this,`_sessionControls`,null),_defineProperty$2(this,`sessionId`,void 0),_defineProperty$2(this,`_courseId`,void 0),_defineProperty$2(this,`_stateSnapshotProvider`,void 0),_defineProperty$2(this,`_sessionDoc`,null),_defineProperty$2(this,`_openDocPromise`,null),_defineProperty$2(this,`_runLog`,[]),_defineProperty$2(this,`_eloLog`,[]),_defineProperty$2(this,`_sessionClosed`,!1),_defineProperty$2(this,`startTime`,void 0),_defineProperty$2(this,`endTime`,void 0),_defineProperty$2(this,`_secondsRemaining`,void 0),_defineProperty$2(this,`_intervalHandle`,void 0),this.sessionId=newSessionId(),setDebugSessionId(this.sessionId),this.dataLayer=u,this.mixer=m||new QuotaRoundRobinMixer,this.srsService=new SrsService(u.getUserDB()),this.eloService=new EloService(u,u.getUserDB()),this.hydrationService=new CardHydrationService(d,t=>u.getCourseDB(t),()=>this._getItemsToHydrate()),this.services={response:new ResponseProcessor(this.srsService,this.eloService,t=>this._recordEloEvent(t))},this.sources=t,this.startTime=new Date,this._secondsRemaining=c,this.endTime=new Date(this.startTime.valueOf()+1e3*this._secondsRemaining),g?.defaultBatchLimit!==void 0&&(this._defaultBatchLimit=g.defaultBatchLimit),g?.outcomeObservers?.length&&(this._outcomeObservers=[...g.outcomeObservers]),this._courseId=g?.courseId,this._stateSnapshotProvider=g?.stateSnapshotProvider,this.log(`Session constructed:
|
|
453
453
|
sessionId: ${this.sessionId}
|
|
454
454
|
startTime: ${this.startTime}
|
|
455
455
|
endTime: ${this.endTime}
|
|
456
|
-
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})}}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}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:
|
|
456
|
+
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:
|
|
457
457
|
`:`Mixed content session created with:
|
|
458
458
|
`,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})
|
|
459
459
|
`,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
|
|
460
|
-
`}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],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(_SessionController2,`MAX_LOGGED_RUNS`,100),_defineProperty$2(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty$2(_SessionController2,`WELL_INDICATED_SCORE`,.1),_defineProperty$2(_SessionController2,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty$2(_SessionController2,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty$2(_SessionController2,`FAILED_ENDGAME_SLACK_SECONDS`,20),_SessionController2),init_TagFilteredContentSource(),init_factory(),init_userDBHelpers()}));function useRouter(){return inject(routerKey)}function useRoute(t){return inject(routeLocationKey)}var isArray,NavigationType,NavigationDirection,NavigationFailureSymbol,NavigationFailureType,matchedRouteKey,viewDepthKey,routerKey,routeLocationKey,routerViewLocationKey,init_vue_router=__esmMin((()=>{init_vue_runtime_esm_bundler(),Array.isArray,(function(t){t.pop=`pop`,t.push=`push`})(NavigationType||(NavigationType={})),(function(t){t.back=`back`,t.forward=`forward`,t.unknown=``})(NavigationDirection||(NavigationDirection={})),Symbol(process.env.NODE_ENV===`production`?``:`navigation failure`),(function(t){t[t.aborted=4]=`aborted`,t[t.cancelled=8]=`cancelled`,t[t.duplicated=16]=`duplicated`})(NavigationFailureType||(NavigationFailureType={})),Symbol(process.env.NODE_ENV===`production`?``:`router view location matched`),Symbol(process.env.NODE_ENV===`production`?``:`router view depth`),routerKey=Symbol(process.env.NODE_ENV===`production`?``:`router`),routeLocationKey=Symbol(process.env.NODE_ENV===`production`?``:`route location`),Symbol(process.env.NODE_ENV===`production`?``:`router view location`)})),init_style=__esmMin((()=>{}));function registerRuntimeHelpers(t){Object.getOwnPropertySymbols(t).forEach(c=>{helperNameMap[c]=t[c]})}function createRoot(t,c=``){return{type:0,source:c,children:t,helpers:new Set,components:[],directives:[],hoists:[],imports:[],cached:[],temps:0,codegenNode:void 0,loc:locStub}}function createVNodeCall(t,c,u,d,m,g,b,S=!1,C=!1,w=!1,T=locStub){return t&&(S?(t.helper(OPEN_BLOCK),t.helper(getVNodeBlockHelper(t.inSSR,w))):t.helper(getVNodeHelper(t.inSSR,w)),b&&t.helper(WITH_DIRECTIVES)),{type:13,tag:c,props:u,children:d,patchFlag:m,dynamicProps:g,directives:b,isBlock:S,disableTracking:C,isComponent:w,loc:T}}function createArrayExpression(t,c=locStub){return{type:17,loc:c,elements:t}}function createObjectExpression(t,c=locStub){return{type:15,loc:c,properties:t}}function createObjectProperty(t,c){return{type:16,loc:locStub,key:isString$1(t)?createSimpleExpression(t,!0):t,value:c}}function createSimpleExpression(t,c=!1,u=locStub,d=0){return{type:4,loc:u,content:t,isStatic:c,constType:c?3:d}}function createInterpolation(t,c){return{type:5,loc:c,content:isString$1(t)?createSimpleExpression(t,!1,c):t}}function createCompoundExpression(t,c=locStub){return{type:8,loc:c,children:t}}function createCallExpression(t,c=[],u=locStub){return{type:14,loc:u,callee:t,arguments:c}}function createFunctionExpression(t,c=void 0,u=!1,d=!1,m=locStub){return{type:18,params:t,returns:c,newline:u,isSlot:d,loc:m}}function createConditionalExpression(t,c,u,d=!0){return{type:19,test:t,consequent:c,alternate:u,newline:d,loc:locStub}}function createCacheExpression(t,c,u=!1,d=!1){return{type:20,index:t,value:c,needPauseTracking:u,inVOnce:d,needArraySpread:!1,loc:locStub}}function createBlockStatement(t){return{type:21,body:t,loc:locStub}}function createTemplateLiteral(t){return{type:22,elements:t,loc:locStub}}function createIfStatement(t,c,u){return{type:23,test:t,consequent:c,alternate:u,loc:locStub}}function createAssignmentExpression(t,c){return{type:24,left:t,right:c,loc:locStub}}function createSequenceExpression(t){return{type:25,expressions:t,loc:locStub}}function createReturnStatement(t){return{type:26,returns:t,loc:locStub}}function getVNodeHelper(t,c){return t||c?CREATE_VNODE:CREATE_ELEMENT_VNODE}function getVNodeBlockHelper(t,c){return t||c?CREATE_BLOCK:CREATE_ELEMENT_BLOCK}function convertToBlock(t,{helper:c,removeHelper:u,inSSR:d}){t.isBlock||(t.isBlock=!0,u(getVNodeHelper(d,t.isComponent)),c(OPEN_BLOCK),c(getVNodeBlockHelper(d,t.isComponent)))}function isTagStartChar(t){return t>=97&&t<=122||t>=65&&t<=90}function isWhitespace(t){return t===32||t===10||t===9||t===12||t===13}function isEndOfTagSection(t){return t===47||t===62||isWhitespace(t)}function toCharCodes(t){let c=new Uint8Array(t.length);for(let u=0;u<t.length;u++)c[u]=t.charCodeAt(u);return c}function getCompatValue(t,{compatConfig:c}){let u=c&&c[t];return t===`MODE`?u||3:u}function isCompatEnabled(t,c){let u=getCompatValue(`MODE`,c),d=getCompatValue(t,c);return u===3?d===!0:d!==!1}function checkCompatEnabled(t,c,u,...d){let m=isCompatEnabled(t,c);return process.env.NODE_ENV!==`production`&&m&&warnDeprecation(t,c,u,...d),m}function warnDeprecation(t,c,u,...d){if(getCompatValue(t,c)===`suppress-warning`)return;let{message:m,link:g}=deprecationData[t],b=`(deprecation ${t}) ${typeof m==`function`?m(...d):m}${g?`
|
|
460
|
+
`}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(_SessionController2,`MAX_LOGGED_RUNS`,100),_defineProperty$2(_SessionController2,`MAX_LOGGED_ELO_EVENTS`,2e3),_defineProperty$2(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty$2(_SessionController2,`WELL_INDICATED_SCORE`,.1),_defineProperty$2(_SessionController2,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty$2(_SessionController2,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty$2(_SessionController2,`FAILED_ENDGAME_SLACK_SECONDS`,20),_SessionController2),init_TagFilteredContentSource(),init_factory(),init_userDBHelpers()}));function useRouter(){return inject(routerKey)}function useRoute(t){return inject(routeLocationKey)}var isArray,NavigationType,NavigationDirection,NavigationFailureSymbol,NavigationFailureType,matchedRouteKey,viewDepthKey,routerKey,routeLocationKey,routerViewLocationKey,init_vue_router=__esmMin((()=>{init_vue_runtime_esm_bundler(),Array.isArray,(function(t){t.pop=`pop`,t.push=`push`})(NavigationType||(NavigationType={})),(function(t){t.back=`back`,t.forward=`forward`,t.unknown=``})(NavigationDirection||(NavigationDirection={})),Symbol(process.env.NODE_ENV===`production`?``:`navigation failure`),(function(t){t[t.aborted=4]=`aborted`,t[t.cancelled=8]=`cancelled`,t[t.duplicated=16]=`duplicated`})(NavigationFailureType||(NavigationFailureType={})),Symbol(process.env.NODE_ENV===`production`?``:`router view location matched`),Symbol(process.env.NODE_ENV===`production`?``:`router view depth`),routerKey=Symbol(process.env.NODE_ENV===`production`?``:`router`),routeLocationKey=Symbol(process.env.NODE_ENV===`production`?``:`route location`),Symbol(process.env.NODE_ENV===`production`?``:`router view location`)})),init_style=__esmMin((()=>{}));function registerRuntimeHelpers(t){Object.getOwnPropertySymbols(t).forEach(c=>{helperNameMap[c]=t[c]})}function createRoot(t,c=``){return{type:0,source:c,children:t,helpers:new Set,components:[],directives:[],hoists:[],imports:[],cached:[],temps:0,codegenNode:void 0,loc:locStub}}function createVNodeCall(t,c,u,d,m,g,b,S=!1,C=!1,w=!1,T=locStub){return t&&(S?(t.helper(OPEN_BLOCK),t.helper(getVNodeBlockHelper(t.inSSR,w))):t.helper(getVNodeHelper(t.inSSR,w)),b&&t.helper(WITH_DIRECTIVES)),{type:13,tag:c,props:u,children:d,patchFlag:m,dynamicProps:g,directives:b,isBlock:S,disableTracking:C,isComponent:w,loc:T}}function createArrayExpression(t,c=locStub){return{type:17,loc:c,elements:t}}function createObjectExpression(t,c=locStub){return{type:15,loc:c,properties:t}}function createObjectProperty(t,c){return{type:16,loc:locStub,key:isString$1(t)?createSimpleExpression(t,!0):t,value:c}}function createSimpleExpression(t,c=!1,u=locStub,d=0){return{type:4,loc:u,content:t,isStatic:c,constType:c?3:d}}function createInterpolation(t,c){return{type:5,loc:c,content:isString$1(t)?createSimpleExpression(t,!1,c):t}}function createCompoundExpression(t,c=locStub){return{type:8,loc:c,children:t}}function createCallExpression(t,c=[],u=locStub){return{type:14,loc:u,callee:t,arguments:c}}function createFunctionExpression(t,c=void 0,u=!1,d=!1,m=locStub){return{type:18,params:t,returns:c,newline:u,isSlot:d,loc:m}}function createConditionalExpression(t,c,u,d=!0){return{type:19,test:t,consequent:c,alternate:u,newline:d,loc:locStub}}function createCacheExpression(t,c,u=!1,d=!1){return{type:20,index:t,value:c,needPauseTracking:u,inVOnce:d,needArraySpread:!1,loc:locStub}}function createBlockStatement(t){return{type:21,body:t,loc:locStub}}function createTemplateLiteral(t){return{type:22,elements:t,loc:locStub}}function createIfStatement(t,c,u){return{type:23,test:t,consequent:c,alternate:u,loc:locStub}}function createAssignmentExpression(t,c){return{type:24,left:t,right:c,loc:locStub}}function createSequenceExpression(t){return{type:25,expressions:t,loc:locStub}}function createReturnStatement(t){return{type:26,returns:t,loc:locStub}}function getVNodeHelper(t,c){return t||c?CREATE_VNODE:CREATE_ELEMENT_VNODE}function getVNodeBlockHelper(t,c){return t||c?CREATE_BLOCK:CREATE_ELEMENT_BLOCK}function convertToBlock(t,{helper:c,removeHelper:u,inSSR:d}){t.isBlock||(t.isBlock=!0,u(getVNodeHelper(d,t.isComponent)),c(OPEN_BLOCK),c(getVNodeBlockHelper(d,t.isComponent)))}function isTagStartChar(t){return t>=97&&t<=122||t>=65&&t<=90}function isWhitespace(t){return t===32||t===10||t===9||t===12||t===13}function isEndOfTagSection(t){return t===47||t===62||isWhitespace(t)}function toCharCodes(t){let c=new Uint8Array(t.length);for(let u=0;u<t.length;u++)c[u]=t.charCodeAt(u);return c}function getCompatValue(t,{compatConfig:c}){let u=c&&c[t];return t===`MODE`?u||3:u}function isCompatEnabled(t,c){let u=getCompatValue(`MODE`,c),d=getCompatValue(t,c);return u===3?d===!0:d!==!1}function checkCompatEnabled(t,c,u,...d){let m=isCompatEnabled(t,c);return process.env.NODE_ENV!==`production`&&m&&warnDeprecation(t,c,u,...d),m}function warnDeprecation(t,c,u,...d){if(getCompatValue(t,c)===`suppress-warning`)return;let{message:m,link:g}=deprecationData[t],b=`(deprecation ${t}) ${typeof m==`function`?m(...d):m}${g?`
|
|
461
461
|
Details: ${g}`:``}`,S=SyntaxError(b);S.code=t,u&&(S.loc=u),c.onWarn(S)}function defaultOnError(t){throw t}function defaultOnWarn(t){process.env.NODE_ENV!==`production`&&console.warn(`[Vue warn] ${t.message}`)}function createCompilerError(t,c,u,d){let m=process.env.NODE_ENV===`production`?`https://vuejs.org/error-reference/#compiler-${t}`:(u||errorMessages)[t]+(d||``),g=SyntaxError(String(m));return g.code=t,g.loc=c,g}function walkIdentifiers(t,c,u=!1,d=[],m=Object.create(null)){}function isReferencedIdentifier(t,c,u){return!1}function isInDestructureAssignment(t,c){if(t&&(t.type===`ObjectProperty`||t.type===`ArrayPattern`)){let t=c.length;for(;t--;){let u=c[t];if(u.type===`AssignmentExpression`)return!0;if(u.type!==`ObjectProperty`&&!u.type.endsWith(`Pattern`))break}}return!1}function isInNewExpression(t){let c=t.length;for(;c--;){let u=t[c];if(u.type===`NewExpression`)return!0;if(u.type!==`MemberExpression`)break}return!1}function walkFunctionParams(t,c){for(let u of t.params)for(let t of extractIdentifiers(u))c(t)}function walkBlockDeclarations(t,c){for(let u of t.body)if(u.type===`VariableDeclaration`){if(u.declare)continue;for(let t of u.declarations)for(let u of extractIdentifiers(t.id))c(u)}else if(u.type===`FunctionDeclaration`||u.type===`ClassDeclaration`){if(u.declare||!u.id)continue;c(u.id)}else isForStatement(u)&&walkForStatement(u,!0,c)}function isForStatement(t){return t.type===`ForOfStatement`||t.type===`ForInStatement`||t.type===`ForStatement`}function walkForStatement(t,c,u){let d=t.type===`ForStatement`?t.init:t.left;if(d&&d.type===`VariableDeclaration`&&(d.kind===`var`?c:!c))for(let t of d.declarations)for(let c of extractIdentifiers(t.id))u(c)}function extractIdentifiers(t,c=[]){switch(t.type){case`Identifier`:c.push(t);break;case`MemberExpression`:let u=t;for(;u.type===`MemberExpression`;)u=u.object;c.push(u);break;case`ObjectPattern`:for(let u of t.properties)u.type===`RestElement`?extractIdentifiers(u.argument,c):extractIdentifiers(u.value,c);break;case`ArrayPattern`:t.elements.forEach(t=>{t&&extractIdentifiers(t,c)});break;case`RestElement`:extractIdentifiers(t.argument,c);break;case`AssignmentPattern`:extractIdentifiers(t.left,c);break}return c}function unwrapTSNode(t){return TS_NODE_TYPES.includes(t.type)?unwrapTSNode(t.expression):t}function isCoreComponent(t){switch(t){case`Teleport`:case`teleport`:return TELEPORT;case`Suspense`:case`suspense`:return SUSPENSE;case`KeepAlive`:case`keep-alive`:return KEEP_ALIVE;case`BaseTransition`:case`base-transition`:return BASE_TRANSITION}}function advancePositionWithClone(t,c,u=c.length){return advancePositionWithMutation({offset:t.offset,line:t.line,column:t.column},c,u)}function advancePositionWithMutation(t,c,u=c.length){let d=0,m=-1;for(let t=0;t<u;t++)c.charCodeAt(t)===10&&(d++,m=t);return t.offset+=u,t.line+=d,t.column=m===-1?t.column+u:u-m,t}function assert(t,c){if(!t)throw Error(c||`unexpected compiler condition`)}function findDir(t,c,u=!1){for(let d=0;d<t.props.length;d++){let m=t.props[d];if(m.type===7&&(u||m.exp)&&(isString$1(c)?m.name===c:c.test(m.name)))return m}}function findProp(t,c,u=!1,d=!1){for(let m=0;m<t.props.length;m++){let g=t.props[m];if(g.type===6){if(u)continue;if(g.name===c&&(g.value||d))return g}else if(g.name===`bind`&&(g.exp||d)&&isStaticArgOf(g.arg,c))return g}}function isStaticArgOf(t,c){return!!(t&&isStaticExp(t)&&t.content===c)}function hasDynamicKeyVBind(t){return t.props.some(t=>t.type===7&&t.name===`bind`&&(!t.arg||t.arg.type!==4||!t.arg.isStatic))}function isText$1(t){return t.type===5||t.type===2}function isVSlot(t){return t.type===7&&t.name===`slot`}function isTemplateNode(t){return t.type===1&&t.tagType===3}function isSlotOutlet(t){return t.type===1&&t.tagType===2}function getUnnormalizedProps(t,c=[]){if(t&&!isString$1(t)&&t.type===14){let u=t.callee;if(!isString$1(u)&&propsHelperSet.has(u))return getUnnormalizedProps(t.arguments[0],c.concat(t))}return[t,c]}function injectProp(t,c,u){let d,m=t.type===13?t.props:t.arguments[2],g=[],b;if(m&&!isString$1(m)&&m.type===14){let t=getUnnormalizedProps(m);m=t[0],g=t[1],b=g[g.length-1]}if(m==null||isString$1(m))d=createObjectExpression([c]);else if(m.type===14){let t=m.arguments[0];!isString$1(t)&&t.type===15?hasProp(c,t)||t.properties.unshift(c):m.callee===TO_HANDLERS?d=createCallExpression(u.helper(MERGE_PROPS),[createObjectExpression([c]),m]):m.arguments.unshift(createObjectExpression([c])),!d&&(d=m)}else m.type===15?(hasProp(c,m)||m.properties.unshift(c),d=m):(d=createCallExpression(u.helper(MERGE_PROPS),[createObjectExpression([c]),m]),b&&b.callee===GUARD_REACTIVE_PROPS&&(b=g[g.length-2]));t.type===13?b?b.arguments[0]=d:t.props=d:b?b.arguments[0]=d:t.arguments[2]=d}function hasProp(t,c){let u=!1;if(t.key.type===4){let d=t.key.content;u=c.properties.some(t=>t.key.type===4&&t.key.content===d)}return u}function toValidAssetId(t,c){return`_${c}_${t.replace(/[^\w]/g,(c,u)=>c===`-`?`_`:t.charCodeAt(u).toString())}`}function hasScopeRef(t,c){if(!t||Object.keys(c).length===0)return!1;switch(t.type){case 1:for(let u=0;u<t.props.length;u++){let d=t.props[u];if(d.type===7&&(hasScopeRef(d.arg,c)||hasScopeRef(d.exp,c)))return!0}return t.children.some(t=>hasScopeRef(t,c));case 11:return hasScopeRef(t.source,c)?!0:t.children.some(t=>hasScopeRef(t,c));case 9:return t.branches.some(t=>hasScopeRef(t,c));case 10:return hasScopeRef(t.condition,c)?!0:t.children.some(t=>hasScopeRef(t,c));case 4:return!t.isStatic&&isSimpleIdentifier(t.content)&&!!c[t.content];case 8:return t.children.some(t=>isObject$1(t)&&hasScopeRef(t,c));case 5:case 12:return hasScopeRef(t.content,c);case 2:case 3:case 20:return!1;default:return process.env.NODE_ENV,!1}}function getMemoedVNodeCall(t){return t.type===14&&t.callee===WITH_MEMO?t.arguments[1].returns:t}function parseForExpression(t){let c=t.loc,u=t.content,d=u.match(forAliasRE);if(!d)return;let[,m,g]=d,createAliasExpression=(t,u,d=!1)=>{let m=c.start.offset+u;return createExp(t,!1,getLoc(m,m+t.length),0,d?1:0)},b={source:createAliasExpression(g.trim(),u.indexOf(g,m.length)),value:void 0,key:void 0,index:void 0,finalized:!1},S=m.trim().replace(stripParensRE,``).trim(),C=m.indexOf(S),w=S.match(forIteratorRE);if(w){S=S.replace(forIteratorRE,``).trim();let t=w[1].trim(),c;if(t&&(c=u.indexOf(t,C+S.length),b.key=createAliasExpression(t,c,!0)),w[2]){let d=w[2].trim();d&&(b.index=createAliasExpression(d,u.indexOf(d,b.key?c+t.length:C+S.length),!0))}}return S&&(b.value=createAliasExpression(S,C,!0)),b}function getSlice(t,c){return currentInput.slice(t,c)}function endOpenTag(t){tokenizer.inSFCRoot&&(currentOpenTag.innerLoc=getLoc(t+1,t+1)),addNode(currentOpenTag);let{tag:c,ns:u}=currentOpenTag;u===0&¤tOptions.isPreTag(c)&&inPre++,currentOptions.isVoidTag(c)?onCloseTag(currentOpenTag,t):(stack.unshift(currentOpenTag),(u===1||u===2)&&(tokenizer.inXML=!0)),currentOpenTag=null}function onText(t,c,u){{let c=stack[0]&&stack[0].tag;c!==`script`&&c!==`style`&&t.includes(`&`)&&(t=currentOptions.decodeEntities(t,!1))}let d=stack[0]||currentRoot,m=d.children[d.children.length-1];m&&m.type===2?(m.content+=t,setLocEnd(m.loc,u)):d.children.push({type:2,content:t,loc:getLoc(c,u)})}function onCloseTag(t,c,u=!1){u?setLocEnd(t.loc,backTrack(c,60)):setLocEnd(t.loc,lookAhead(c,62)+1),tokenizer.inSFCRoot&&(t.children.length?t.innerLoc.end=extend$2({},t.children[t.children.length-1].loc.end):t.innerLoc.end=extend$2({},t.innerLoc.start),t.innerLoc.source=getSlice(t.innerLoc.start.offset,t.innerLoc.end.offset));let{tag:d,ns:m,children:g}=t;if(inVPre||(d===`slot`?t.tagType=2:isFragmentTemplate(t)?t.tagType=3:isComponent(t)&&(t.tagType=1)),tokenizer.inRCDATA||(t.children=condenseWhitespace(g)),m===0&¤tOptions.isIgnoreNewlineTag(d)){let t=g[0];t&&t.type===2&&(t.content=t.content.replace(/^\r?\n/,``))}m===0&¤tOptions.isPreTag(d)&&inPre--,currentVPreBoundary===t&&(inVPre=tokenizer.inVPre=!1,currentVPreBoundary=null),tokenizer.inXML&&(stack[0]?stack[0].ns:currentOptions.ns)===0&&(tokenizer.inXML=!1);{let c=t.props;if(process.env.NODE_ENV!==`production`&&isCompatEnabled(`COMPILER_V_IF_V_FOR_PRECEDENCE`,currentOptions)){let u=!1,d=!1;for(let m=0;m<c.length;m++){let g=c[m];if(g.type===7&&(g.name===`if`?u=!0:g.name===`for`&&(d=!0)),u&&d){warnDeprecation(`COMPILER_V_IF_V_FOR_PRECEDENCE`,currentOptions,t.loc);break}}}if(!tokenizer.inSFCRoot&&isCompatEnabled(`COMPILER_NATIVE_TEMPLATE`,currentOptions)&&t.tag===`template`&&!isFragmentTemplate(t)){process.env.NODE_ENV!==`production`&&warnDeprecation(`COMPILER_NATIVE_TEMPLATE`,currentOptions,t.loc);let c=stack[0]||currentRoot,u=c.children.indexOf(t);c.children.splice(u,1,...t.children)}let u=c.find(t=>t.type===6&&t.name===`inline-template`);u&&checkCompatEnabled(`COMPILER_INLINE_TEMPLATE`,currentOptions,u.loc)&&t.children.length&&(u.value={type:2,content:getSlice(t.children[0].loc.start.offset,t.children[t.children.length-1].loc.end.offset),loc:u.loc})}}function lookAhead(t,c){let u=t;for(;currentInput.charCodeAt(u)!==c&&u<currentInput.length-1;)u++;return u}function backTrack(t,c){let u=t;for(;currentInput.charCodeAt(u)!==c&&u>=0;)u--;return u}function isFragmentTemplate({tag:t,props:c}){if(t===`template`){for(let t=0;t<c.length;t++)if(c[t].type===7&&specialTemplateDir.has(c[t].name))return!0}return!1}function isComponent({tag:t,props:c}){if(currentOptions.isCustomElement(t))return!1;if(t===`component`||isUpperCase(t.charCodeAt(0))||isCoreComponent(t)||currentOptions.isBuiltInComponent&¤tOptions.isBuiltInComponent(t)||currentOptions.isNativeTag&&!currentOptions.isNativeTag(t))return!0;for(let t=0;t<c.length;t++){let u=c[t];if(u.type===6){if(u.name===`is`&&u.value&&(u.value.content.startsWith(`vue:`)||checkCompatEnabled(`COMPILER_IS_ON_ELEMENT`,currentOptions,u.loc)))return!0}else if(u.name===`bind`&&isStaticArgOf(u.arg,`is`)&&checkCompatEnabled(`COMPILER_IS_ON_ELEMENT`,currentOptions,u.loc))return!0}return!1}function isUpperCase(t){return t>64&&t<91}function condenseWhitespace(t,c){let u=currentOptions.whitespace!==`preserve`,d=!1;for(let c=0;c<t.length;c++){let m=t[c];if(m.type===2)if(inPre)m.content=m.content.replace(windowsNewlineRE,`
|
|
462
462
|
`);else if(isAllWhitespace(m.content)){let g=t[c-1]&&t[c-1].type,b=t[c+1]&&t[c+1].type;!g||!b||u&&(g===3&&(b===3||b===1)||g===1&&(b===3||b===1&&hasNewlineChar(m.content)))?(d=!0,t[c]=null):m.content=` `}else u&&(m.content=condense(m.content))}return d?t.filter(Boolean):t}function isAllWhitespace(t){for(let c=0;c<t.length;c++)if(!isWhitespace(t.charCodeAt(c)))return!1;return!0}function hasNewlineChar(t){for(let c=0;c<t.length;c++){let u=t.charCodeAt(c);if(u===10||u===13)return!0}return!1}function condense(t){let c=``,u=!1;for(let d=0;d<t.length;d++)isWhitespace(t.charCodeAt(d))?u||(c+=` `,u=!0):(c+=t[d],u=!1);return c}function addNode(t){(stack[0]||currentRoot).children.push(t)}function getLoc(t,c){return{start:tokenizer.getPos(t),end:c==null?c:tokenizer.getPos(c),source:c==null?c:getSlice(t,c)}}function cloneLoc(t){return getLoc(t.start.offset,t.end.offset)}function setLocEnd(t,c){t.end=tokenizer.getPos(c),t.source=getSlice(t.start.offset,c)}function dirToAttr(t){let c={type:6,name:t.rawName,nameLoc:getLoc(t.loc.start.offset,t.loc.start.offset+t.rawName.length),value:void 0,loc:t.loc};if(t.exp){let u=t.exp.loc;u.end.offset<t.loc.end.offset&&(u.start.offset--,u.start.column--,u.end.offset++,u.end.column++),c.value={type:2,content:t.exp.content,loc:u}}return c}function createExp(t,c=!1,u,d=0,m=0){return createSimpleExpression(t,c,u,d)}function emitError(t,c,u){currentOptions.onError(createCompilerError(t,getLoc(c,c),void 0,u))}function reset(){tokenizer.reset(),currentOpenTag=null,currentProp=null,currentAttrValue=``,currentAttrStartIndex=-1,currentAttrEndIndex=-1,stack.length=0}function baseParse(t,c){if(reset(),currentInput=t,currentOptions=extend$2({},defaultParserOptions),c){let t;for(t in c)c[t]!=null&&(currentOptions[t]=c[t])}if(process.env.NODE_ENV!==`production`&&!currentOptions.decodeEntities)throw Error(`[@vue/compiler-core] decodeEntities option is required in browser builds.`);tokenizer.mode=currentOptions.parseMode===`html`?1:currentOptions.parseMode===`sfc`?2:0,tokenizer.inXML=currentOptions.ns===1||currentOptions.ns===2;let u=c&&c.delimiters;u&&(tokenizer.delimiterOpen=toCharCodes(u[0]),tokenizer.delimiterClose=toCharCodes(u[1]));let d=currentRoot=createRoot([],t);return tokenizer.parse(currentInput),d.loc=getLoc(0,t.length),d.children=condenseWhitespace(d.children),currentRoot=null,d}function cacheStatic(t,c){walk(t,void 0,c,isSingleElementRoot(t,t.children[0]))}function isSingleElementRoot(t,c){let{children:u}=t;return u.length===1&&c.type===1&&!isSlotOutlet(c)}function walk(t,c,u,d=!1,m=!1){let{children:g}=t,b=[];for(let c=0;c<g.length;c++){let S=g[c];if(S.type===1&&S.tagType===0){let t=d?0:getConstantType(S,u);if(t>0){if(t>=2){S.codegenNode.patchFlag=-1,b.push(S);continue}}else{let t=S.codegenNode;if(t.type===13){let c=t.patchFlag;if((c===void 0||c===512||c===1)&&getGeneratedPropsConstantType(S,u)>=2){let c=getNodeProps(S);c&&(t.props=u.hoist(c))}t.dynamicProps&&(t.dynamicProps=u.hoist(t.dynamicProps))}}}else if(S.type===12&&(d?0:getConstantType(S,u))>=2){b.push(S);continue}if(S.type===1){let c=S.tagType===1;c&&u.scopes.vSlot++,walk(S,t,u,!1,m),c&&u.scopes.vSlot--}else if(S.type===11)walk(S,t,u,S.children.length===1,!0);else if(S.type===9)for(let c=0;c<S.branches.length;c++)walk(S.branches[c],t,u,S.branches[c].children.length===1,m)}let S=!1;if(b.length===g.length&&t.type===1){if(t.tagType===0&&t.codegenNode&&t.codegenNode.type===13&&isArray$3(t.codegenNode.children))t.codegenNode.children=getCacheExpression(createArrayExpression(t.codegenNode.children)),S=!0;else if(t.tagType===1&&t.codegenNode&&t.codegenNode.type===13&&t.codegenNode.children&&!isArray$3(t.codegenNode.children)&&t.codegenNode.children.type===15){let c=getSlotNode(t.codegenNode,`default`);c&&(c.returns=getCacheExpression(createArrayExpression(c.returns)),S=!0)}else if(t.tagType===3&&c&&c.type===1&&c.tagType===1&&c.codegenNode&&c.codegenNode.type===13&&c.codegenNode.children&&!isArray$3(c.codegenNode.children)&&c.codegenNode.children.type===15){let u=findDir(t,`slot`,!0),d=u&&u.arg&&getSlotNode(c.codegenNode,u.arg);d&&(d.returns=getCacheExpression(createArrayExpression(d.returns)),S=!0)}}if(!S)for(let t of b)t.codegenNode=u.cache(t.codegenNode);function getCacheExpression(t){let c=u.cache(t);return m&&u.hmr&&(c.needArraySpread=!0),c}function getSlotNode(t,c){if(t.children&&!isArray$3(t.children)&&t.children.type===15){let u=t.children.properties.find(t=>t.key===c||t.key.content===c);return u&&u.value}}b.length&&u.transformHoist&&u.transformHoist(g,u,t)}function getConstantType(t,c){let{constantCache:u}=c;switch(t.type){case 1:if(t.tagType!==0)return 0;let d=u.get(t);if(d!==void 0)return d;let m=t.codegenNode;if(m.type!==13||m.isBlock&&t.tag!==`svg`&&t.tag!==`foreignObject`&&t.tag!==`math`)return 0;if(m.patchFlag===void 0){let d=3,g=getGeneratedPropsConstantType(t,c);if(g===0)return u.set(t,0),0;g<d&&(d=g);for(let m=0;m<t.children.length;m++){let g=getConstantType(t.children[m],c);if(g===0)return u.set(t,0),0;g<d&&(d=g)}if(d>1)for(let m=0;m<t.props.length;m++){let g=t.props[m];if(g.type===7&&g.name===`bind`&&g.exp){let m=getConstantType(g.exp,c);if(m===0)return u.set(t,0),0;m<d&&(d=m)}}if(m.isBlock){for(let c=0;c<t.props.length;c++)if(t.props[c].type===7)return u.set(t,0),0;c.removeHelper(OPEN_BLOCK),c.removeHelper(getVNodeBlockHelper(c.inSSR,m.isComponent)),m.isBlock=!1,c.helper(getVNodeHelper(c.inSSR,m.isComponent))}return u.set(t,d),d}else return u.set(t,0),0;case 2:case 3:return 3;case 9:case 11:case 10:return 0;case 5:case 12:return getConstantType(t.content,c);case 4:return t.constType;case 8:let g=3;for(let u=0;u<t.children.length;u++){let d=t.children[u];if(isString$1(d)||isSymbol(d))continue;let m=getConstantType(d,c);if(m===0)return 0;m<g&&(g=m)}return g;case 20:return 2;default:return process.env.NODE_ENV,0}}function getConstantTypeOfHelperCall(t,c){if(t.type===14&&!isString$1(t.callee)&&allowHoistedHelperSet.has(t.callee)){let u=t.arguments[0];if(u.type===4)return getConstantType(u,c);if(u.type===14)return getConstantTypeOfHelperCall(u,c)}return 0}function getGeneratedPropsConstantType(t,c){let u=3,d=getNodeProps(t);if(d&&d.type===15){let{properties:t}=d;for(let d=0;d<t.length;d++){let{key:m,value:g}=t[d],b=getConstantType(m,c);if(b===0)return b;b<u&&(u=b);let S;if(S=g.type===4?getConstantType(g,c):g.type===14?getConstantTypeOfHelperCall(g,c):0,S===0)return S;S<u&&(u=S)}}return u}function getNodeProps(t){let c=t.codegenNode;if(c.type===13)return c.props}function createTransformContext(t,{filename:c=``,prefixIdentifiers:u=!1,hoistStatic:d=!1,hmr:m=!1,cacheHandlers:g=!1,nodeTransforms:b=[],directiveTransforms:S={},transformHoist:C=null,isBuiltInComponent:w=NOOP,isCustomElement:T=NOOP,expressionPlugins:E=[],scopeId:D=null,slotted:O=!0,ssr:xr=!1,inSSR:Sr=!1,ssrCssVars:Cr=``,bindingMetadata:wr=EMPTY_OBJ,inline:Tr=!1,isTS:Er=!1,onError:Dr=defaultOnError,onWarn:Or=defaultOnWarn,compatConfig:kr}){let Ar=c.replace(/\?.*$/,``).match(/([^/\\]+)\.\w+$/),jr={filename:c,selfName:Ar&&capitalize(camelize(Ar[1])),prefixIdentifiers:u,hoistStatic:d,hmr:m,cacheHandlers:g,nodeTransforms:b,directiveTransforms:S,transformHoist:C,isBuiltInComponent:w,isCustomElement:T,expressionPlugins:E,scopeId:D,slotted:O,ssr:xr,inSSR:Sr,ssrCssVars:Cr,bindingMetadata:wr,inline:Tr,isTS:Er,onError:Dr,onWarn:Or,compatConfig:kr,root:t,helpers:new Map,components:new Set,directives:new Set,hoists:[],imports:[],cached:[],constantCache:new WeakMap,temps:0,identifiers:Object.create(null),scopes:{vFor:0,vSlot:0,vPre:0,vOnce:0},parent:null,grandParent:null,currentNode:t,childIndex:0,inVOnce:!1,helper(t){let c=jr.helpers.get(t)||0;return jr.helpers.set(t,c+1),t},removeHelper(t){let c=jr.helpers.get(t);if(c){let u=c-1;u?jr.helpers.set(t,u):jr.helpers.delete(t)}},helperString(t){return`_${helperNameMap[jr.helper(t)]}`},replaceNode(t){if(process.env.NODE_ENV!==`production`){if(!jr.currentNode)throw Error(`Node being replaced is already removed.`);if(!jr.parent)throw Error(`Cannot replace root node.`)}jr.parent.children[jr.childIndex]=jr.currentNode=t},removeNode(t){if(process.env.NODE_ENV!==`production`&&!jr.parent)throw Error(`Cannot remove root node.`);let c=jr.parent.children,u=t?c.indexOf(t):jr.currentNode?jr.childIndex:-1;if(process.env.NODE_ENV!==`production`&&u<0)throw Error(`node being removed is not a child of current parent`);!t||t===jr.currentNode?(jr.currentNode=null,jr.onNodeRemoved()):jr.childIndex>u&&(jr.childIndex--,jr.onNodeRemoved()),jr.parent.children.splice(u,1)},onNodeRemoved:NOOP,addIdentifiers(t){},removeIdentifiers(t){},hoist(t){isString$1(t)&&(t=createSimpleExpression(t)),jr.hoists.push(t);let c=createSimpleExpression(`_hoisted_${jr.hoists.length}`,!1,t.loc,2);return c.hoisted=t,c},cache(t,c=!1,u=!1){let d=createCacheExpression(jr.cached.length,t,c,u);return jr.cached.push(d),d}};return jr.filters=new Set,jr}function transform(t,c){let u=createTransformContext(t,c);traverseNode(t,u),c.hoistStatic&&cacheStatic(t,u),c.ssr||createRootCodegen(t,u),t.helpers=new Set([...u.helpers.keys()]),t.components=[...u.components],t.directives=[...u.directives],t.imports=u.imports,t.hoists=u.hoists,t.temps=u.temps,t.cached=u.cached,t.transformed=!0,t.filters=[...u.filters]}function createRootCodegen(t,c){let{helper:u}=c,{children:d}=t;if(d.length===1){let u=d[0];if(isSingleElementRoot(t,u)&&u.codegenNode){let d=u.codegenNode;d.type===13&&convertToBlock(d,c),t.codegenNode=d}else t.codegenNode=u}else if(d.length>1){let m=64;process.env.NODE_ENV!==`production`&&d.filter(t=>t.type!==3).length===1&&(m|=2048),t.codegenNode=createVNodeCall(c,u(FRAGMENT),void 0,t.children,m,void 0,void 0,!0,void 0,!1)}}function traverseChildren(t,c){let u=0,nodeRemoved=()=>{u--};for(;u<t.children.length;u++){let d=t.children[u];isString$1(d)||(c.grandParent=c.parent,c.parent=t,c.childIndex=u,c.onNodeRemoved=nodeRemoved,traverseNode(d,c))}}function traverseNode(t,c){c.currentNode=t;let{nodeTransforms:u}=c,d=[];for(let m=0;m<u.length;m++){let g=u[m](t,c);if(g&&(isArray$3(g)?d.push(...g):d.push(g)),c.currentNode)t=c.currentNode;else return}switch(t.type){case 3:c.ssr||c.helper(CREATE_COMMENT);break;case 5:c.ssr||c.helper(TO_DISPLAY_STRING);break;case 9:for(let u=0;u<t.branches.length;u++)traverseNode(t.branches[u],c);break;case 10:case 11:case 1:case 0:traverseChildren(t,c);break}c.currentNode=t;let m=d.length;for(;m--;)d[m]()}function createStructuralDirectiveTransform(t,c){let u=isString$1(t)?c=>c===t:c=>t.test(c);return(t,d)=>{if(t.type===1){let{props:m}=t;if(t.tagType===3&&m.some(isVSlot))return;let g=[];for(let b=0;b<m.length;b++){let S=m[b];if(S.type===7&&u(S.name)){m.splice(b,1),b--;let u=c(t,S,d);u&&g.push(u)}}return g}}}function createCodegenContext(t,{mode:c=`function`,prefixIdentifiers:u=c===`module`,sourceMap:d=!1,filename:m=`template.vue.html`,scopeId:g=null,optimizeImports:b=!1,runtimeGlobalName:S=`Vue`,runtimeModuleName:C=`vue`,ssrRuntimeModuleName:w=`vue/server-renderer`,ssr:T=!1,isTS:E=!1,inSSR:D=!1}){let O={mode:c,prefixIdentifiers:u,sourceMap:d,filename:m,scopeId:g,optimizeImports:b,runtimeGlobalName:S,runtimeModuleName:C,ssrRuntimeModuleName:w,ssr:T,isTS:E,inSSR:D,source:t.source,code:``,column:1,line:1,offset:0,indentLevel:0,pure:!1,map:void 0,helper(t){return`_${helperNameMap[t]}`},push(t,c=-2,u){O.code+=t},indent(){newline(++O.indentLevel)},deindent(t=!1){t?--O.indentLevel:newline(--O.indentLevel)},newline(){newline(O.indentLevel)}};function newline(t){O.push(`
|
|
463
463
|
`+` `.repeat(t),0)}return O}function generate(t,c={}){let u=createCodegenContext(t,c);c.onContextCreated&&c.onContextCreated(u);let{mode:d,push:m,prefixIdentifiers:g,indent:b,deindent:S,newline:C,scopeId:w,ssr:T}=u,E=Array.from(t.helpers),D=E.length>0,O=!g&&d!==`module`;if(genFunctionPreamble(t,u),m(`function ${T?`ssrRender`:`render`}(${(T?[`_ctx`,`_push`,`_parent`,`_attrs`]:[`_ctx`,`_cache`]).join(`, `)}) {`),b(),O&&(m(`with (_ctx) {`),b(),D&&(m(`const { ${E.map(aliasHelper).join(`, `)} } = _Vue
|