@vue-skuilder/standalone-ui 0.2.15 → 0.2.16
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-Czt6W7JQ.js → TagViewer-OsFeiohW.js} +2 -2
- package/dist/assets/{TagViewer-Czt6W7JQ.js.map → TagViewer-OsFeiohW.js.map} +1 -1
- package/dist/assets/common-ui.es-CCLeNYN4.js +1 -0
- package/dist/assets/{common-ui.es-ibXGK5ti.js → common-ui.es-DDvhbVBP.js} +4 -4
- package/dist/assets/{common-ui.es-ibXGK5ti.js.map → common-ui.es-DDvhbVBP.js.map} +1 -1
- package/dist/assets/{dist-DlSLFgY8.js → dist-CDEq0Y3a.js} +2 -2
- package/dist/assets/{dist-DlSLFgY8.js.map → dist-CDEq0Y3a.js.map} +1 -1
- package/dist/assets/{index-CKXq4U_A.js → index-CQnBgFOT.js} +5 -5
- package/dist/assets/{index-CKXq4U_A.js.map → index-CQnBgFOT.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist-lib/questions.cjs.js +1 -1
- package/dist-lib/questions.cjs.js.map +1 -1
- package/dist-lib/questions.mjs +4 -1
- package/dist-lib/questions.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/assets/common-ui.es-xI0w3GT-.js +0 -1
|
@@ -316,7 +316,7 @@ Examples:
|
|
|
316
316
|
Card: ${JSON.stringify(e.cardElo)})
|
|
317
317
|
`)}}else logger.warn(`[EloService] Partial ELO update (per-tag):
|
|
318
318
|
User ELO update: ${a?`SUCCESS`:`FAILED`}
|
|
319
|
-
Card ELO update: ${l?`SUCCESS`:`FAILED`}`),!a&&r[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,r[0].reason),!l&&r[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,r[1].reason)}}};init_core(),init_logger();var ResponseProcessor=class{constructor(e,t){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),this.srsService=e,this.eloService=t}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a).catch(this.logEloFailure(`correct per-tag`,s))}else{let n=.5+c/2;if(t.records.length===1)this.eloService.updateUserAndCardElo(n,o,s,r,a).catch(this.logEloFailure(`correct`,s));else{let e=Math.ceil(32/t.records.length);this.eloService.updateUserAndCardElo(n,o,s,r,a,e).catch(this.logEloFailure(`correct repeat-view`,s))}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)`);let{globalScore:t}=this.parsePerformance(e.performance);return{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:t,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`incorrect per-tag`,o)),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`incorrect`,o)),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`dismiss-failed per-tag`,o)):this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`dismiss-failed`,o)),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{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();function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:e,view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}},ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
|
|
319
|
+
Card ELO update: ${l?`SUCCESS`:`FAILED`}`),!a&&r[0].status===`rejected`&&logger.error(`[EloService] User ELO update error:`,r[0].reason),!l&&r[1].status===`rejected`&&logger.error(`[EloService] Card ELO update error:`,r[1].reason)}}};init_core(),init_logger();var ResponseProcessor=class{constructor(e,t){_defineProperty(this,`srsService`,void 0),_defineProperty(this,`eloService`,void 0),this.srsService=e,this.eloService=t}logEloFailure(e,t){return n=>logger.error(`[ResponseProcessor] ELO update failed (${e}) for ${t}:`,n)}parsePerformance(e){return typeof e==`number`?{globalScore:e,taggedPerformance:null}:isTaggedPerformance(e)?{globalScore:e._global,taggedPerformance:e}:(logger.warn(`[ResponseProcessor] Unexpected performance structure, using neutral score`,{performance:e}),{globalScore:.5,taggedPerformance:null})}async processResponse(e,t,n,r,a,o,s,c,l,u){if(!isQuestionRecord(e))return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,shouldClearFeedbackShadow:!0};try{let d=await t,p;return p=e.isCorrect?this.processCorrectResponse(e,d,n,r,a,o,s):this.processIncorrectResponse(e,d,r,a,o,s,c,l,u),e.deferAdvance&&p.shouldLoadNextCard&&(logger.info(`[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:`,{nextCardAction:p.nextCardAction}),p={...p,shouldLoadNextCard:!1,deferred:!0}),p}catch(e){throw logger.error(`[ResponseProcessor] Failed to load card history`,{e,cardId:s}),e}}processCorrectResponse(e,t,n,r,a,o,s){if(e.priorAttemps===0){a.card.tags.includes(`srs:skip`)||this.srsService.scheduleReview(t,n);let{globalScore:c,taggedPerformance:l}=this.parsePerformance(e.performance);if(l){let n=Object.keys(l).filter(e=>e!==`_global`),c=n.filter(e=>l[e]===null),u=n.filter(e=>l[e]!==null);logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}): scored=[${u.join(`, `)}] count-only=[${c.join(`, `)}]`),this.eloService.updateUserAndCardEloPerTag(l,o,s,r,a).catch(this.logEloFailure(`correct per-tag`,s))}else{let n=.5+c/2;if(t.records.length===1)this.eloService.updateUserAndCardElo(n,o,s,r,a).catch(this.logEloFailure(`correct`,s));else{let e=Math.ceil(32/t.records.length);this.eloService.updateUserAndCardElo(n,o,s,r,a,e).catch(this.logEloFailure(`correct repeat-view`,s))}logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${n.toFixed(3)}) for ${s} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)}return{nextCardAction:`dismiss-success`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:c,shouldClearFeedbackShadow:!0}}else{logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)`);let{globalScore:t}=this.parsePerformance(e.performance);return{nextCardAction:`marked-failed`,shouldLoadNextCard:!0,isCorrect:!0,performanceScore:t,shouldClearFeedbackShadow:!0}}}processIncorrectResponse(e,t,n,r,a,o,s,c,l){let{taggedPerformance:u}=this.parsePerformance(e.performance),d=!1;return e.priorAttemps===0?(u?(this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`incorrect per-tag`,o)),logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps}, tags=${Object.keys(u).length-1})`)):(this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`incorrect`,o)),logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`)),d=!0):logger.info(`[FirstContactElo] incorrect retry \u2014 no ELO update for ${o} (historyLen=${t.records.length}, priorAttemps=${e.priorAttemps})`),r.records.length>=s?l>=c?(d?logger.info(`[FirstContactElo] dismiss-failed \u2014 ELO already updated this response, skipping double penalty for ${o}`):(u?this.eloService.updateUserAndCardEloPerTag(u,a,o,n,r).catch(this.logEloFailure(`dismiss-failed per-tag`,o)):this.eloService.updateUserAndCardElo(0,a,o,n,r).catch(this.logEloFailure(`dismiss-failed`,o)),logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${o} (historyLen=${t.records.length}, sessionViews=${l})`)),{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();function parseAudioURIs(e){return typeof e==`string`?e.match(/https?:\/\/[^\s"'<>]+\.(wav|mp3|ogg|m4a|aac|webm)/gi)??[]:[]}function prefetchAudio(e){return new Promise(t=>{let n=new Audio;n.preload=`auto`;let cleanup=()=>{n.oncanplaythrough=null,n.onerror=null};n.oncanplaythrough=()=>{cleanup(),t()},n.onerror=()=>{cleanup(),logger.warn(`[CardHydrationService] Failed to prefetch audio: ${e}`),t()},n.src=e})}var CardHydrationService=class{constructor(e,t,n){_defineProperty(this,`hydratedCards`,new Map),_defineProperty(this,`hydrationInFlight`,new Set),_defineProperty(this,`hydrationInProgress`,!1),this.getViewComponent=e,this.getCourseDB=t,this.getItemsToHydrate=n}getHydratedCard(e){return this.hydratedCards.get(e)??null}hasHydratedCard(e){return this.hydratedCards.has(e)}removeCard(e){this.hydratedCards.delete(e)}async ensureHydratedCards(){this.fillHydratedCards()}async waitForCard(e){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);this.hydrationInProgress||this.fillHydratedCards();let t=1e4,n=25,r=0;for(;r<1e4;){if(this.hydratedCards.has(e))return this.hydratedCards.get(e);if(!this.hydrationInFlight.has(e)&&!this.hydrationInProgress)break;await new Promise(e=>setTimeout(e,25)),r+=25}return this.hydratedCards.get(e)??null}get hydratedCount(){return this.hydratedCards.size}getHydratedCardIds(){return Array.from(this.hydratedCards.keys())}async fillHydratedCards(){if(!this.hydrationInProgress){this.hydrationInProgress=!0;try{let e=this.getItemsToHydrate();for(let t of e)if(!(this.hydratedCards.has(t.cardID)||this.hydrationInFlight.has(t.cardID)))try{await this.hydrateCard(t)}catch(e){logger.error(`[CardHydrationService] Error hydrating card ${t.cardID}:`,e)}}finally{this.hydrationInProgress=!1}}}async hydrateCard(e){if(!(this.hydratedCards.has(e.cardID)||this.hydrationInFlight.has(e.cardID))){this.hydrationInFlight.add(e.cardID);try{let t=this.getCourseDB(e.courseID),[n,r]=await Promise.all([t.getCourseDoc(e.cardID),t.getAppliedTagsBatch([e.cardID])]);isCourseElo(n.elo)||(n.elo=toCourseElo(n.elo));let a=this.getViewComponent(n.id_view),o=await Promise.all(n.id_displayable_data.map(e=>t.getCourseDoc(e,{attachments:!0,binary:!0}))),s=[];o.forEach(e=>{e.data.forEach(e=>{s.push(...parseAudioURIs(e.data))})});let c=[...new Set(s)];c.length>0&&(logger.debug(`[CardHydrationService] Prefetching ${c.length} audio files for card ${e.cardID}`),await Promise.allSettled(c.map(prefetchAudio)));let l=o.map(displayableDataToViewData).reverse();this.hydratedCards.set(e.cardID,{item:{...e,elo:toCourseElo(n.elo).global.score},view:a,data:l,tags:r.get(e.cardID)??[]}),logger.debug(`[CardHydrationService] Hydrated card ${e.cardID}`)}finally{this.hydrationInFlight.delete(e.cardID)}}}},ItemQueue=class{constructor(){_defineProperty(this,`q`,[]),_defineProperty(this,`seenCardIds`,[]),_defineProperty(this,`_dequeueCount`,0)}get dequeueCount(){return this._dequeueCount}add(e,t){this.seenCardIds.find(e=>e===t)||(this.seenCardIds.push(t),this.q.push(e))}addAll(e,t){e.forEach(e=>this.add(e,t(e)))}get length(){return this.q.length}peek(e){return this.q[e]}dequeue(e){if(this.q.length!==0){this._dequeueCount++;let t=this.q.splice(0,1)[0];if(e){let n=e(t),r=this.seenCardIds.indexOf(n);r>-1&&this.seenCardIds.splice(r,1)}return t}else return null}replaceAll(e,t){this.q=[],this.seenCardIds=[];for(let n of e){let e=t(n);this.seenCardIds.includes(e)||(this.seenCardIds.push(e),this.q.push(n))}}mergeToFront(e,t,n){let r=0,a=[];for(let o of e){let e=t(o);if(!this.seenCardIds.includes(e))this.seenCardIds.push(e),a.push(o),r++;else if(n?.has(e)){let n=this.q.findIndex(n=>t(n)===e);n>=0&&a.push(...this.q.splice(n,1))}}return this.q.unshift(...a),r}get toString(){return`${typeof this.q[0]}:
|
|
320
320
|
`+this.q.map(e=>` ${e.courseID}+${e.cardID}: ${e.status}`).join(`
|
|
321
321
|
`)}};init_couch(),init_core(),init_recording(),init_Loggable(),init_types_legacy(),init_logger();var CouchDBToStaticPacker=class{constructor(e={}){_defineProperty(this,`config`,void 0),_defineProperty(this,`sourceDB`,null),this.config={chunkSize:1e3,includeAttachments:!0,...e}}async packCourse(e,t){logger.info(`Starting static pack for course: ${t}`),this.sourceDB=e;let n={version:`1.0.0`,courseId:t,courseName:``,courseConfig:null,lastUpdated:new Date().toISOString(),documentCount:0,chunks:[],indices:[],designDocs:[]},r=await this.extractCourseConfig(e);n.courseName=r.name,n.courseConfig=r,n.designDocs=await this.extractDesignDocs(e);let a=await this.extractDocumentsByType(e),o=new Map;this.config.includeAttachments&&await this.extractAllAttachments(a,o);let s=new Map;for(let[e,t]of Object.entries(a)){let r=this.createChunks(t,e);n.chunks.push(...r),n.documentCount+=t.length,this.prepareChunkData(r,t,s)}let c=new Map;return n.indices=await this.buildIndices(a,n.designDocs,c),{manifest:n,chunks:s,indices:c,attachments:o}}async packCourseToFiles(e,t,n,r){logger.info(`Packing course ${t} to files in ${n}`);let a=await this.packCourse(e,t),o=await this.writePackedDataToFiles(a,n,r);return{manifest:a.manifest,filesWritten:o,attachmentsFound:a.attachments?a.attachments.size:0}}async writePackedDataToFiles(e,t,n){let r=0;await n.ensureDir(t);let a=n.joinPath(t,`manifest.json`);await n.writeJson(a,e.manifest,{spaces:2}),r++,logger.info(`Wrote manifest: ${a}`);let o=n.joinPath(t,`chunks`),s=n.joinPath(t,`indices`);await n.ensureDir(o),await n.ensureDir(s);for(let[t,a]of e.chunks){let e=n.joinPath(o,`${t}.json`);await n.writeJson(e,a),r++}logger.info(`Wrote ${e.chunks.size} chunk files`);for(let[t,a]of e.indices){let e=n.joinPath(s,`${t}.json`);await n.writeJson(e,a,{spaces:2}),r++}if(logger.info(`Wrote ${e.indices.size} index files`),e.attachments&&e.attachments.size>0){for(let[a,o]of e.attachments){let e=n.joinPath(t,a),s=n.dirname(e);await n.ensureDir(s),await n.writeFile(e,o.buffer),r++}logger.info(`Wrote ${e.attachments.size} attachment files`)}return r}async extractCourseConfig(e){try{return await e.get(`CourseConfig`)}catch(e){throw logger.error(`Failed to extract course config:`,e),Error(`Course config not found`)}}async extractDesignDocs(e){return(await e.allDocs({startkey:`_design/`,endkey:`_design/`,include_docs:!0})).rows.map(e=>({_id:e.id,views:e.doc.views||{}}))}async extractDocumentsByType(e){let t=await e.allDocs({include_docs:!0}),n={};for(let e of t.rows){if(e.id.startsWith(`_`))continue;let t=e.doc;t.docType&&(n[t.docType]||(n[t.docType]=[]),n[t.docType].push(t))}return n}createChunks(e,t){let n=[],r=e.sort((e,t)=>e._id.localeCompare(t._id));for(let e=0;e<r.length;e+=this.config.chunkSize){let a=r.slice(e,e+this.config.chunkSize),o=`${t}-${String(Math.floor(e/this.config.chunkSize)).padStart(4,`0`)}`;n.push({id:o,docType:t,startKey:a[0]._id,endKey:a[a.length-1]._id,documentCount:a.length,path:`chunks/${o}.json`})}return n}prepareChunkData(e,t,n){let r=t.sort((e,t)=>e._id.localeCompare(t._id));for(let t of e){let e=r.filter(e=>e._id>=t.startKey&&e._id<=t.endKey).map(e=>{let t={...e};return delete t._rev,this.config.includeAttachments&&t._attachments?t._attachments=this.transformAttachmentStubs(t._attachments,t._id):this.config.includeAttachments||delete t._attachments,t});n.set(t.id,e)}}async buildIndices(e,t,n){let r=[];if(e.CARD){let t=await this.buildEloIndex(e.CARD,n);r.push(t)}if(e.TAG){let t=await this.buildTagIndex(e.TAG,n);r.push(t)}for(let e of t)for(let[t,a]of Object.entries(e.views))if(a.map){logger.info(`Processing view: ${e._id}/${t}`);let a=await this.buildViewIndex(t,e,n);a?(r.push(a),logger.info(`Successfully built index: ${a.name}`)):logger.warn(`Skipped view index: ${e._id}/${t}`)}return r}async buildEloIndex(e,t){let n=[];for(let t of e)t.elo?.global?.score&&n.push({elo:t.elo.global.score,cardId:t._id});n.sort((e,t)=>e.elo-t.elo);let r={},a=50;for(let e of n){let t=Math.floor(e.elo/50)*50;r[t]||(r[t]=[]),r[t].push(e.cardId)}return t.set(`elo`,{sorted:n,buckets:r,stats:{min:n[0]?.elo||0,max:n[n.length-1]?.elo||0,count:n.length}}),{name:`elo`,type:`btree`,path:`indices/elo.json`}}async buildTagIndex(e,t){let n={};for(let t of e)n[t.name]={cardIds:t.taggedCards,snippet:t.snippet,count:t.taggedCards.length};let r={};for(let t of e)for(let e of t.taggedCards)r[e]||(r[e]=[]),r[e].push(t.name);return t.set(`tags`,{byTag:n,byCard:r}),{name:`tags`,type:`hash`,path:`indices/tags.json`}}async buildViewIndex(e,t,n){if(!this.sourceDB)return logger.error(`Source database not available for view querying`),null;try{let r=`${t._id.replace(`_design/`,``)}/${e}`;logger.info(`Querying CouchDB view: ${r}`);let a=await this.sourceDB.query(r,{include_docs:!1});if(!a.rows||a.rows.length===0)return logger.warn(`View ${r} returned no results`),null;logger.info(`Successfully queried view ${r}: ${a.rows.length} results`);let o=this.formatViewResults(e,a.rows,t),s=`view-${t._id.replace(`_design/`,``)}-${e}`;return n.set(s,o),{name:s,type:`view`,path:`indices/${s}.json`}}catch(n){return logger.error(`Failed to query view ${t._id}/${e}:`,n),null}}formatViewResults(e,t,n){let r={type:`couchdb-view`,viewName:e,designDoc:n._id,results:t,metadata:{resultCount:t.length,generatedAt:new Date().toISOString()}};switch(e){case`elo`:return this.formatEloViewIndex(t,r);case`getTags`:return this.formatTagsViewIndex(t,r);case`cardsByInexperience`:return this.formatInexperienceViewIndex(t,r);default:return this.formatGenericViewIndex(t,r)}}formatEloViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{min:n[0]?.key||0,max:n[n.length-1]?.key||0,count:n.length}}}formatTagsViewIndex(e,t){let n={};for(let t of e){let e=t.key;typeof e==`string`&&(n[e]||(n[e]=[]),n[e].push(t.id))}return{...t,byTag:n,tagCount:Object.keys(n).length}}formatInexperienceViewIndex(e,t){let n=e.sort((e,t)=>typeof e.key==`number`&&typeof t.key==`number`?e.key-t.key:0);return{...t,sorted:n,stats:{minInexperience:n[0]?.key||0,maxInexperience:n[n.length-1]?.key||0,count:n.length}}}formatGenericViewIndex(e,t){return{...t}}async extractAllAttachments(e,t){logger.info(`Extracting attachments...`);let n=[];for(let t of Object.values(e))n.push(...t);let r=n.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);if(r.length===0){logger.info(`No attachments found`);return}logger.info(`Found ${r.length} documents with attachments`);let a=r.map(e=>this.extractDocumentAttachments(e,t));await Promise.all(a),logger.info(`Extracted ${t.size} attachment files`)}async extractDocumentAttachments(e,t){if(!e._attachments||!this.sourceDB)return;let n=e._id;for(let[r,a]of Object.entries(e._attachments))try{let e=await this.sourceDB.getAttachment(n,r),o;if(e instanceof ArrayBuffer)o=Buffer.from(e);else if(Buffer.isBuffer(e))o=e;else{let t=e;o=Buffer.from(await t.arrayBuffer())}let s=`${r}${this.getFileExtension(a.content_type)}`,c=`attachments/${n}/${s}`;t.set(c,{docId:n,attachmentName:r,filename:s,path:c,contentType:a.content_type,length:a.length||o.length,digest:a.digest,buffer:o}),logger.debug(`Extracted attachment: ${c}`)}catch(e){throw logger.error(`Failed to extract attachment ${n}/${r}:`,e),Error(`Failed to extract attachment ${n}/${r}: ${e}`)}}transformAttachmentStubs(e,t){let n={};for(let[r,a]of Object.entries(e))n[r]={path:`attachments/${t}/${`${r}${this.getFileExtension(a.content_type)}`}`,content_type:a.content_type,length:a.length,digest:a.digest,stub:!1};return n}getFileExtension(e){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`}[e]||``}};init_logger();var DEFAULT_MIGRATION_OPTIONS={chunkBatchSize:100,validateRoundTrip:!1,cleanupOnFailure:!0,timeout:3e5};init_logger();var FileSystemError=class extends Error{constructor(e,t,n,r){super(e),this.operation=t,this.filePath=n,this.cause=r,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{}async function validateStaticCourse(e,t){let n={valid:!0,manifestExists:!1,chunksExist:!1,attachmentsExist:!1,errors:[],warnings:[]};try{if(t){if(!(await t.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n}else if(!nodeFS2)return n.errors.push(`File system access not available - validation skipped`),n.valid=!1,n;else if(!(await nodeFS2.promises.stat(e)).isDirectory())return n.errors.push(`Path is not a directory: ${e}`),n.valid=!1,n;let r=`${e}/manifest.json`;try{if(t)if(r=t.joinPath(e,`manifest.json`),await t.exists(r)){n.manifestExists=!0;let e=await t.readFile(r),a=JSON.parse(e);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}else n.errors.push(`Manifest not found: ${r}`),n.valid=!1;else{r=`${e}/manifest.json`,await nodeFS2.promises.access(r),n.manifestExists=!0;let t=await nodeFS2.promises.readFile(r,`utf8`),a=JSON.parse(t);n.courseId=a.courseId,n.courseName=a.courseName,(!a.version||!a.courseId||!a.chunks||!Array.isArray(a.chunks))&&(n.errors.push(`Invalid manifest structure`),n.valid=!1)}}catch(e){let t=e instanceof FileSystemError?e.message:`Manifest not found or invalid: ${r}`;n.errors.push(t),n.valid=!1}let a=`${e}/chunks`;try{t?(a=t.joinPath(e,`chunks`),await t.exists(a)?(await t.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1):(n.errors.push(`Chunks directory not found: ${a}`),n.valid=!1)):(a=`${e}/chunks`,(await nodeFS2.promises.stat(a)).isDirectory()?n.chunksExist=!0:(n.errors.push(`Chunks path is not a directory: ${a}`),n.valid=!1))}catch(e){let t=e instanceof FileSystemError?e.message:`Chunks directory not found: ${a}`;n.errors.push(t),n.valid=!1}let o;try{t?(o=t.joinPath(e,`attachments`),await t.exists(o)?(await t.stat(o)).isDirectory()&&(n.attachmentsExist=!0):n.warnings.push(`Attachments directory not found: ${o} (this is OK if course has no attachments)`)):(o=`${e}/attachments`,(await nodeFS2.promises.stat(o)).isDirectory()&&(n.attachmentsExist=!0))}catch(t){o=o||`${e}/attachments`;let r=t instanceof FileSystemError?t.message:`Attachments directory not found: ${o} (this is OK if course has no attachments)`;n.warnings.push(r)}}catch(e){n.errors.push(`Failed to validate static course: ${e instanceof Error?e.message:String(e)}`),n.valid=!1}return n}async function validateMigration(e,t,n){let r={valid:!0,documentCountMatch:!1,attachmentIntegrity:!1,viewFunctionality:!1,issues:[]};try{logger.info(`Starting migration validation...`),r.documentCountMatch=compareDocumentCounts(t,await getActualDocumentCounts(e),r.issues),await validateCourseConfig(e,n,r.issues),r.viewFunctionality=await validateViews(e,n,r.issues),r.attachmentIntegrity=await validateAttachmentIntegrity(e,r.issues),r.valid=r.documentCountMatch&&r.viewFunctionality&&r.attachmentIntegrity,logger.info(`Migration validation completed. Valid: ${r.valid}`),r.issues.length>0&&(logger.info(`Validation issues: ${r.issues.length}`),r.issues.forEach(e=>{e.type===`error`?logger.error(`${e.category}: ${e.message}`):logger.warn(`${e.category}: ${e.message}`)}))}catch(e){r.valid=!1,r.issues.push({type:`error`,category:`metadata`,message:`Validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function getActualDocumentCounts(e){let t={};try{let n=await e.allDocs({include_docs:!0});for(let e of n.rows){if(e.id.startsWith(`_design/`)){t._design=(t._design||0)+1;continue}let n=e.doc;n&&n.docType?t[n.docType]=(t[n.docType]||0)+1:t.unknown=(t.unknown||0)+1}}catch(e){logger.error(`Failed to get actual document counts:`,e)}return t}function compareDocumentCounts(e,t,n){let r=!0;for(let[a,o]of Object.entries(e)){let e=t[a]||0;e!==o&&(r=!1,n.push({type:`error`,category:`documents`,message:`Document count mismatch for ${a}: expected ${o}, got ${e}`}))}for(let[r,a]of Object.entries(t))!e[r]&&r!==`_design`&&n.push({type:`warning`,category:`documents`,message:`Unexpected document type found: ${r} (${a} documents)`});return r}async function validateCourseConfig(e,t,n){try{let r=await e.get(`CourseConfig`);if(!r){n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found after migration`});return}r.courseID||n.push({type:`warning`,category:`course_config`,message:`CourseConfig document missing courseID field`}),r.courseID!==t.courseId&&n.push({type:`warning`,category:`course_config`,message:`CourseConfig courseID mismatch: expected ${t.courseId}, got ${r.courseID}`}),logger.debug(`CourseConfig document validation passed`)}catch(e){e.status===404?n.push({type:`error`,category:`course_config`,message:`CourseConfig document not found in database`}):n.push({type:`error`,category:`course_config`,message:`Failed to validate CourseConfig document: ${e instanceof Error?e.message:String(e)}`})}}async function validateViews(e,t,n){let r=!0;try{for(let a of t.designDocs)try{if(!await e.get(a._id)){r=!1,n.push({type:`error`,category:`views`,message:`Design document not found: ${a._id}`});continue}for(let t of Object.keys(a.views))try{let n=`${a._id}/${t}`;await e.query(n,{limit:1})}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View not accessible: ${a._id}/${t} - ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`Failed to validate design document ${a._id}: ${e}`})}}catch(e){r=!1,n.push({type:`error`,category:`views`,message:`View validation failed: ${e instanceof Error?e.message:String(e)}`})}return r}async function validateAttachmentIntegrity(e,t){let n=!0;try{let r=await e.allDocs({include_docs:!0,limit:10}),a=0,o=0;for(let s of r.rows){let r=s.doc;if(r&&r._attachments)for(let[s,c]of Object.entries(r._attachments)){a++;try{await e.getAttachment(r._id,s)&&o++}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment not accessible: ${r._id}/${s} - ${e}`})}}}a===0?t.push({type:`warning`,category:`attachments`,message:`No attachments found in sampled documents`}):logger.info(`Validated ${o}/${a} sampled attachments`)}catch(e){n=!1,t.push({type:`error`,category:`attachments`,message:`Attachment validation failed: ${e instanceof Error?e.message:String(e)}`})}return n}var 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{}var StaticToCouchDBMigrator=class{constructor(e={},t){_defineProperty(this,`options`,void 0),_defineProperty(this,`progressCallback`,void 0),_defineProperty(this,`fs`,void 0),this.options={...DEFAULT_MIGRATION_OPTIONS,...e},this.fs=t}setProgressCallback(e){this.progressCallback=e}async migrateCourse(e,t){let n=Date.now(),r={success:!1,documentsRestored:0,attachmentsRestored:0,designDocsRestored:0,courseConfigRestored:0,errors:[],warnings:[],migrationTime:0};try{logger.info(`Starting migration from ${e} to CouchDB`),this.reportProgress(`manifest`,0,1,`Validating static course...`);let a=await validateStaticCourse(e,this.fs);if(!a.valid)throw r.errors.push(...a.errors),Error(`Static course validation failed: ${a.errors.join(`, `)}`);r.warnings.push(...a.warnings),this.reportProgress(`manifest`,1,1,`Loading course manifest...`);let o=await this.loadManifest(e);logger.info(`Loaded manifest for course: ${o.courseId} (${o.courseName})`),this.reportProgress(`design_docs`,0,o.designDocs.length,`Restoring design documents...`);let s=await this.restoreDesignDocuments(o.designDocs,t);r.designDocsRestored=s.restored,r.errors.push(...s.errors),r.warnings.push(...s.warnings),this.reportProgress(`course_config`,0,1,`Restoring CourseConfig document...`);let c=await this.restoreCourseConfig(o,t);r.courseConfigRestored=c.restored,r.errors.push(...c.errors),r.warnings.push(...c.warnings),this.reportProgress(`course_config`,1,1,`CourseConfig document restored`);let l=this.calculateExpectedCounts(o);this.reportProgress(`documents`,0,o.documentCount,`Aggregating documents from chunks...`);let u=await this.aggregateDocuments(e,o),d=u.filter(e=>e._id!==`CourseConfig`);u.length!==d.length&&r.warnings.push(`Filtered out ${u.length-d.length} CourseConfig document(s) from chunks to prevent conflicts`),this.reportProgress(`documents`,d.length,o.documentCount,`Uploading documents to CouchDB...`);let p=await this.uploadDocuments(d,t);r.documentsRestored=p.restored,r.errors.push(...p.errors),r.warnings.push(...p.warnings);let m=u.filter(e=>e._attachments&&Object.keys(e._attachments).length>0);this.reportProgress(`attachments`,0,m.length,`Uploading attachments...`);let g=await this.uploadAttachments(e,m,t);if(r.attachmentsRestored=g.restored,r.errors.push(...g.errors),r.warnings.push(...g.warnings),this.options.validateRoundTrip){this.reportProgress(`validation`,0,1,`Validating migration...`);let e=await validateMigration(t,l,o);e.valid||(r.warnings.push(`Migration validation found issues`),e.issues.forEach(e=>{e.type===`error`?r.errors.push(`Validation: ${e.message}`):r.warnings.push(`Validation: ${e.message}`)})),this.reportProgress(`validation`,1,1,`Migration validation completed`)}r.success=r.errors.length===0,r.migrationTime=Date.now()-n,logger.info(`Migration completed in ${r.migrationTime}ms`),logger.info(`Documents restored: ${r.documentsRestored}`),logger.info(`Attachments restored: ${r.attachmentsRestored}`),logger.info(`Design docs restored: ${r.designDocsRestored}`),logger.info(`CourseConfig restored: ${r.courseConfigRestored}`),r.errors.length>0&&logger.error(`Migration completed with ${r.errors.length} errors`),r.warnings.length>0&&logger.warn(`Migration completed with ${r.warnings.length} warnings`)}catch(e){r.success=!1,r.migrationTime=Date.now()-n;let a=e instanceof Error?e.message:String(e);if(r.errors.push(`Migration failed: ${a}`),logger.error(`Migration failed:`,e),this.options.cleanupOnFailure)try{await this.cleanupFailedMigration(t)}catch(e){logger.error(`Failed to cleanup after migration failure:`,e),r.warnings.push(`Failed to cleanup after migration failure`)}}return r}async loadManifest(e){try{let t,n;if(this.fs)n=this.fs.joinPath(e,`manifest.json`),t=await this.fs.readFile(n);else if(n=nodeFS3&&nodePath?nodePath.join(e,`manifest.json`):`${e}/manifest.json`,nodeFS3&&this.isLocalPath(e))t=await nodeFS3.promises.readFile(n,`utf8`);else{let e=await fetch(n);if(!e.ok)throw Error(`Failed to fetch manifest: ${e.status} ${e.statusText}`);t=await e.text()}let r=JSON.parse(t);if(!r.version||!r.courseId||!r.chunks)throw Error(`Invalid manifest structure`);return r}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load manifest: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async restoreDesignDocuments(e,t){let n={restored:0,errors:[],warnings:[]};for(let r=0;r<e.length;r++){let a=e[r];this.reportProgress(`design_docs`,r,e.length,`Restoring ${a._id}...`);try{let e;try{e=await t.get(a._id)}catch{}let r={_id:a._id,views:a.views};e?(r._rev=e._rev,logger.debug(`Updating existing design document: ${a._id}`)):logger.debug(`Creating new design document: ${a._id}`),await t.put(r),n.restored++}catch(e){let t=`Failed to restore design document ${a._id}: ${e instanceof Error?e.message:String(e)}`;n.errors.push(t),logger.error(t)}}return this.reportProgress(`design_docs`,e.length,e.length,`Restored ${n.restored} design documents`),n}async aggregateDocuments(e,t){let n=[],r=new Map;for(let a=0;a<t.chunks.length;a++){let o=t.chunks[a];this.reportProgress(`documents`,n.length,t.documentCount,`Loading chunk ${o.id}...`);try{let t=await this.loadChunk(e,o);for(let e of t){if(!e._id){logger.warn(`Document without _id found in chunk ${o.id}, skipping`);continue}r.has(e._id)&&logger.warn(`Duplicate document ID found: ${e._id}, using latest version`),r.set(e._id,e)}}catch(e){throw Error(`Failed to load chunk ${o.id}: ${e instanceof Error?e.message:String(e)}`)}}return n.push(...r.values()),logger.info(`Aggregated ${n.length} unique documents from ${t.chunks.length} chunks`),n}async loadChunk(e,t){try{let n,r;if(this.fs)r=this.fs.joinPath(e,t.path),n=await this.fs.readFile(r);else if(r=nodeFS3&&nodePath?nodePath.join(e,t.path):`${e}/${t.path}`,nodeFS3&&this.isLocalPath(e))n=await nodeFS3.promises.readFile(r,`utf8`);else{let e=await fetch(r);if(!e.ok)throw Error(`Failed to fetch chunk: ${e.status} ${e.statusText}`);n=await e.text()}let a=JSON.parse(n);if(!Array.isArray(a))throw Error(`Chunk file does not contain an array of documents`);return a}catch(e){let t=e instanceof FileSystemError?e.message:`Failed to load chunk: ${e instanceof Error?e.message:String(e)}`;throw Error(t)}}async uploadDocuments(e,t){let n={restored:0,errors:[],warnings:[]},r=this.options.chunkBatchSize;for(let a=0;a<e.length;a+=r){let o=e.slice(a,a+r);this.reportProgress(`documents`,a,e.length,`Uploading batch ${Math.floor(a/r)+1}...`);try{let e=o.map(e=>{let t={...e};return delete t._rev,delete t._attachments,t}),r=await t.bulkDocs(e);for(let e=0;e<r.length;e++){let t=r[e],a=o[e];if(`error`in t){let e=`Failed to upload document ${a._id}: ${t.error} - ${t.reason}`;n.errors.push(e),logger.error(e)}else n.restored++}}catch(e){let t;t=e instanceof Error||e&&typeof e==`object`&&`message`in e?`Failed to upload document batch starting at index ${a}: ${e.message}`:`Failed to upload document batch starting at index ${a}: ${JSON.stringify(e)}`,n.errors.push(t),logger.error(t)}}return this.reportProgress(`documents`,e.length,e.length,`Uploaded ${n.restored} documents`),n}async uploadAttachments(e,t,n){let r={restored:0,errors:[],warnings:[]},a=0;for(let o of t)if(this.reportProgress(`attachments`,a,t.length,`Processing attachments for ${o._id}...`),a++,o._attachments)for(let[t,a]of Object.entries(o._attachments))try{let s=await this.uploadSingleAttachment(e,o._id,t,a,n);s.success?r.restored++:r.errors.push(s.error||`Unknown attachment upload error`)}catch(e){let n=`Failed to upload attachment ${o._id}/${t}: ${e instanceof Error?e.message:String(e)}`;r.errors.push(n),logger.error(n)}return this.reportProgress(`attachments`,t.length,t.length,`Uploaded ${r.restored} attachments`),r}async uploadSingleAttachment(e,t,n,r,a){let o={success:!1,attachmentName:n,docId:t};try{if(!r.path)return o.error=`Attachment metadata missing file path`,o;let s,c;if(this.fs)c=this.fs.joinPath(e,r.path),s=await this.fs.readBinary(c);else if(c=nodeFS3&&nodePath?nodePath.join(e,r.path):`${e}/${r.path}`,nodeFS3&&this.isLocalPath(e))s=await nodeFS3.promises.readFile(c);else{let e=await fetch(c);if(!e.ok)return o.error=`Failed to fetch attachment: ${e.status} ${e.statusText}`,o;s=await e.arrayBuffer()}let l=await a.get(t);await a.putAttachment(t,n,l._rev,s,r.content_type),o.success=!0}catch(e){o.error=e instanceof Error?e.message:String(e)}return o}async restoreCourseConfig(e,t){let n={restored:0,errors:[],warnings:[]};try{if(!e.courseConfig)return n.warnings.push(`No courseConfig found in manifest, skipping CourseConfig document creation`),n;let r={_id:`CourseConfig`,...e.courseConfig,courseID:e.courseId};delete r._rev,await t.put(r),n.restored=1,logger.info(`CourseConfig document created for course: ${e.courseId}`)}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);n.errors.push(`Failed to restore CourseConfig: ${t}`),logger.error(`CourseConfig restoration failed:`,e)}return n}calculateExpectedCounts(e){let t={};for(let n of e.chunks)t[n.docType]=(t[n.docType]||0)+n.documentCount;return e.designDocs.length>0&&(t._design=e.designDocs.length),t}async cleanupFailedMigration(e){logger.info(`Cleaning up failed migration...`);try{let t=(await e.allDocs()).rows.map(e=>({_id:e.id,_rev:e.value.rev,_deleted:!0}));t.length>0&&(await e.bulkDocs(t),logger.info(`Cleaned up ${t.length} documents from failed migration`))}catch(e){throw logger.error(`Failed to cleanup documents:`,e),e}}reportProgress(e,t,n,r){this.progressCallback&&this.progressCallback({phase:e,current:t,total:n,message:r})}isLocalPath(e){return!e.startsWith(`http://`)&&!e.startsWith(`https://`)}};init_dataDirectory(),init_navigators(),init_Pipeline();var QuotaRoundRobinMixer=class{mix(e,t){if(e.length===0)return[];let n=Math.ceil(t/e.length),r=e.map(e=>[...e.weighted].sort((e,t)=>t.score-e.score).slice(0,n));for(let e=r.length-1;e>0;e--){let t=Math.floor(Math.random()*(e+1));[r[e],r[t]]=[r[t],r[e]]}let a=[],o=0,s=Array(r.length).fill(0);for(;a.length<t&&o<r.length;){o=0;for(let e=0;e<r.length&&!(a.length>=t);e++)s[e]<r[e].length?(a.push(r[e][s[e]]),s[e]++):o++}return a}};init_logger(),init_navigators();var MAX_RUNS2=10,runHistory2=[];function buildSourceSummary(e,t,n){let r=e.weighted.map(e=>e.score),a=e.weighted.filter(e=>getCardOrigin(e)===`review`).length,o=e.weighted.filter(e=>getCardOrigin(e)===`new`).length;return{sourceIndex:e.sourceIndex,sourceId:t,sourceName:n,totalCards:e.weighted.length,reviewCount:a,newCount:o,topScore:r.length>0?Math.max(...r):0,bottomScore:r.length>0?Math.min(...r):0,scoreRange:r.length>0?[Math.min(...r),Math.max(...r)]:[0,0],avgScore:r.length>0?r.reduce((e,t)=>e+t,0)/r.length:0}}function buildSourceBreakdown(e,t,n){let r=n.filter(t=>t.courseId===e),a=r.filter(e=>e.selected);return{sourceId:e,sourceName:t,reviewsProvided:r.filter(e=>e.origin===`review`).length,newProvided:r.filter(e=>e.origin===`new`).length,reviewsSelected:a.filter(e=>e.origin===`review`).length,newSelected:a.filter(e=>e.origin===`new`).length,totalSelected:a.length,selectionRate:r.length>0?a.length/r.length*100:0}}function captureMixerRun(e,t,n,r,a,o,s){let c=t.map((e,t)=>buildSourceSummary(e,n[t]||`source-${t}`,r[t])),l=new Set(s.map(e=>e.cardId)),u=new Map;t.forEach(e=>{let t=[...e.weighted].sort((e,t)=>t.score-e.score),r=new Map;t.forEach((e,t)=>{r.set(e.cardId,t+1)}),u.set(n[e.sourceIndex]||`source-${e.sourceIndex}`,r)});let d=new Map;s.forEach((e,t)=>{d.set(e.cardId,t+1)});let p=new Map;t.forEach(e=>{e.weighted.forEach(e=>{p.set(e.cardId,e)})});let m=Array.from(p.values()).map(e=>({cardId:e.cardId,courseId:e.courseId,origin:getCardOrigin(e),score:e.score,sourceIndex:t.findIndex(t=>t.weighted.some(t=>t.cardId===e.cardId)),selected:l.has(e.cardId),rankInSource:u.get(e.courseId)?.get(e.cardId),rankInMix:d.get(e.cardId)})),g=Array.from(new Set(n.filter(e=>e))).map((e,t)=>buildSourceBreakdown(e,r[t],m)),_={runId:`mix-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date,mixerType:e,requestedLimit:a,quotaPerSource:o,sourceSummaries:c,cards:m,finalCount:s.length,reviewsSelected:s.filter(e=>getCardOrigin(e)===`review`).length,newSelected:s.filter(e=>getCardOrigin(e)===`new`).length,sourceBreakdowns:g};runHistory2.unshift(_),runHistory2.length>MAX_RUNS2&&runHistory2.pop()}function printMixerSummary(e){console.group(`\u{1F3A8} Mixer Run: ${e.mixerType}`),logger.info(`Run ID: ${e.runId}`),logger.info(`Time: ${e.timestamp.toISOString()}`),logger.info(`Config: limit=${e.requestedLimit}${e.quotaPerSource?`, quota/source=${e.quotaPerSource}`:``}`),console.group(`\u{1F4E5} Input: ${e.sourceSummaries.length} sources`);for(let t of e.sourceSummaries)logger.info(` ${t.sourceName||t.sourceId}: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}], avg: ${t.avgScore.toFixed(2)}`);console.groupEnd(),console.group(`\u{1F4E4} Output: ${e.finalCount} cards selected (${e.reviewsSelected} reviews, ${e.newSelected} new)`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(` ${e}: ${t.totalSelected} selected (${t.reviewsSelected} reviews, ${t.newSelected} new) - ${t.selectionRate.toFixed(1)}% selection rate`)}console.groupEnd(),console.groupEnd()}var mixerDebugAPI={get runs(){return[...runHistory2]},showRun(e=0){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let t;if(typeof e==`number`){if(t=runHistory2[e],!t){logger.info(`[Mixer Debug] No run found at index ${e}. History length: ${runHistory2.length}`);return}}else if(t=runHistory2.find(t=>t.runId.endsWith(e)),!t){logger.info(`[Mixer Debug] No run found matching ID '${e}'.`);return}printMixerSummary(t)},showLastMix(){this.showRun(0)},explainSourceBalance(){if(runHistory2.length===0){logger.info(`[Mixer Debug] No runs captured yet.`);return}let e=runHistory2[0];console.group(`⚖️ Source Balance Analysis`),logger.info(`Mixer: ${e.mixerType}`),logger.info(`Requested limit: ${e.requestedLimit}`),e.quotaPerSource&&logger.info(`Quota per source: ${e.quotaPerSource}`),console.group(`Input Distribution:`);for(let t of e.sourceSummaries){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Provided: ${t.totalCards} cards (${t.reviewCount} reviews, ${t.newCount} new)`),logger.info(` Score range: [${t.scoreRange[0].toFixed(2)}, ${t.scoreRange[1].toFixed(2)}]`)}console.groupEnd(),console.group(`Selection Results:`);for(let t of e.sourceBreakdowns){let e=t.sourceName||t.sourceId;logger.info(`${e}:`),logger.info(` Selected: ${t.totalSelected}/${t.reviewsProvided+t.newProvided} (${t.selectionRate.toFixed(1)}%)`),logger.info(` Reviews: ${t.reviewsSelected}/${t.reviewsProvided}`),logger.info(` New: ${t.newSelected}/${t.newProvided}`),t.reviewsProvided>0&&t.reviewsSelected===0&&logger.info(` ⚠️ Had reviews but none selected!`),t.totalSelected===0&&t.reviewsProvided+t.newProvided>0&&logger.info(` ⚠️ Had cards but none selected!`)}console.groupEnd();let t=e.sourceBreakdowns.map(e=>e.selectionRate),n=t.reduce((e,t)=>e+t,0)/t.length,r=Math.max(...t.map(e=>Math.abs(e-n)));r>20&&(logger.info(`
|
|
322
322
|
\u26A0\uFE0F Significant imbalance detected (max deviation: ${r.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 e=runHistory2[0];console.group(`📊 Score Distribution Comparison`),console.table(e.sourceSummaries.map(e=>({source:e.sourceName||e.sourceId,cards:e.totalCards,min:e.bottomScore.toFixed(3),max:e.topScore.toFixed(3),avg:e.avgScore.toFixed(3),range:(e.topScore-e.bottomScore).toFixed(3)})));let t=e.sourceSummaries.map(e=>e.topScore-e.bottomScore),n=e.sourceSummaries.map(e=>e.avgScore),r=Math.max(...t)-Math.min(...t),a=Math.max(...n)-Math.min(...n);(r>.3||a>.2)&&(logger.info(`
|
|
@@ -374,4 +374,4 @@ Example:
|
|
|
374
374
|
`,b=g.map(e=>{let t=getCardOrigin(e),n=Number.isFinite(e.score)?e.score.toFixed(2):`+INF`;return y+=`${t===`review`?`Review`:`New`}: ${e.courseId}::${e.cardId} (score: ${n})
|
|
375
375
|
`,this._buildSupplyItem(e,t)});if(n){let e=this.supplyQ.mergeToFront(b,e=>e.cardID,_);y+=`Additive merge: ${e} cards added to front of supplyQ
|
|
376
376
|
`}else if(t)this.supplyQ.replaceAll(b,e=>e.cardID);else for(let e of b)this.supplyQ.add(e,e.cardID);return this.log(y),v}_buildSupplyItem(e,t=getCardOrigin(e)){let n={cardID:e.cardId,courseID:e.courseId,contentSourceType:`course`,contentSourceID:e.courseId,score:e.score};return t===`review`?{...n,status:`review`,reviewID:e.reviewID}:{...n,status:`new`}}_getItemsToHydrate(){let e=[],t=3,n=2;for(let t=0;t<Math.min(3,this.supplyQ.length);t++)e.push(this.supplyQ.peek(t));for(let t=0;t<Math.min(2,this.failedQ.length);t++)e.push(this.failedQ.peek(t));return e}_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 e=this.supplyQ.length>0?this.supplyQ.peek(0):null;return this._minCardsGuarantee>0&&e?e:this.failedQ.length>0&&this._shouldInterleaveFailed(e!==null)?this.failedQ.peek(0):e||(this.failedQ.length>0?this.failedQ.peek(0):(this.log(`No more cards available for the session!`),null))}_shouldInterleaveFailed(e){return this.failedQ.length===0?!1:!e||this._secondsRemaining-this.estimateCleanupTime()<=_SessionController.FAILED_ENDGAME_SLACK_SECONDS?!0:this._supplyDrawsSinceFailed>=_SessionController.FAILED_INTERLEAVE_EVERY}async nextCard(e=`dismiss-success`){if(this.dismissCurrentCard(e),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(),null;let t=3,n=250,r=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 ${r+1}/3).`),await this._replanUncoalesced({label:`wedge-breaker`}),this.supplyQ.length===0&&this.failedQ.length===0){if(r++,r>=3){this.log(`[WedgeBreaker] Pipeline returned no content 3 consecutive times. Giving up; session will end.`);break}await new Promise(e=>setTimeout(e,250))}else r=0;let a=20;for(let e=0;e<20;e++){let e=this._selectNextItemToHydrate();if(!e)return this._currentCard=null,endSessionTracking(),null;let t=this.hydrationService.getHydratedCard(e.cardID);if(t||(t=await this.hydrationService.waitForCard(e.cardID)),this.removeItemFromQueue(e),t){await this.hydrationService.ensureHydratedCards(),this._currentCard=t;let n=e.status===`review`||e.status===`failed-review`?`review`:e.status===`new`||e.status===`failed-new`?`new`:`failed`,r=e.status.startsWith(`failed`)?`failedQ`:`supplyQ`;return recordCardPresentation(e.cardID,e.courseID,this.courseNameCache.get(e.courseID),n,r,e.score),snapshotQueues(this.supplyQ.length,this.failedQ.length),t}this.log(`Skipping card ${e.cardID}: hydration failed, trying next`),isReview(e)&&this.srsService.removeReview(e.reviewID)}return this.log(`Exhausted 20 skip attempts finding a hydratable card`),this._currentCard=null,endSessionTracking(),null}async submitResponse(e,t,n,r,a,o,s,c,l){let u={...r.item},d=await this.services.response.processResponse(e,t,u,n,r,a,o,s,c,l);return await this._notifyOutcomeObservers(e,r,d),d}dismissCurrentCard(e=`dismiss-success`){if(this._currentCard)if(e===`dismiss-success`)this.hydrationService.removeCard(this._currentCard.item.cardID);else if(e===`marked-failed`){let e;e=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(e,e.cardID),this._supplyDrawsSinceFailed=0}else (e===`dismiss-error`||e===`dismiss-failed`)&&this.hydrationService.removeCard(this._currentCard.item.cardID)}removeItemFromQueue(e){this._clearDurableRequirement(e.cardID),this._servedCardIds.add(e.cardID),this.failedQ.peek(0)?.cardID===e.cardID?(this.failedQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed=0):this.supplyQ.peek(0)?.cardID===e.cardID&&(this.supplyQ.dequeue(e=>e.cardID),this._supplyDrawsSinceFailed++,this._wellIndicatedRemaining>0&&this._wellIndicatedRemaining--)}_clearDurableRequirement(e){let t=this._sessionHints?.requireCards;if(!t||t.length===0)return;let n=t.filter(t=>t!==e);n.length!==t.length&&(this._sessionHints={...this._sessionHints,requireCards:n.length>0?n:void 0},this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${e}`))}async endSession(){if(!this._sessionRecord||this._sessionRecord.length===0)return;let e=this._sessionRecord.flatMap(e=>e.records).filter(e=>e.userAnswer!==void 0);if(e.length===0)return;let t=null,n=[];for(let e of this.sources)if(e.getOrchestrationContext){try{t=await e.getOrchestrationContext(),e.getStrategyIds&&n.push(...e.getStrategyIds())}catch(e){logger.warn(`[SessionController] Failed to get orchestration context: ${e}`)}if(t)break}if(!t){logger.debug(`[SessionController] No orchestration context available, skipping outcome recording`);return}let r=new Date().toISOString(),a=new Date(this.startTime).toISOString();await recordUserOutcome(t,a,r,e,n)}},_defineProperty(_SessionController2,`MIN_WELL_INDICATED`,5),_defineProperty(_SessionController2,`WELL_INDICATED_SCORE`,.1),_defineProperty(_SessionController2,`DEPLETION_PREFETCH_THRESHOLD`,3),_defineProperty(_SessionController2,`FAILED_INTERLEAVE_EVERY`,4),_defineProperty(_SessionController2,`FAILED_ENDGAME_SLACK_SECONDS`,20),_SessionController2);init_TagFilteredContentSource(),init_factory(),init_userDBHelpers();export{getDataLayer as a,isDataShapeRegistered as c,processCustomQuestionsData as d,registerCustomQuestionTypes as f,getCardHistoryID as i,isDataShapeSchemaAvailable as l,SessionController as n,getStudySource as o,removeCustomQuestionTypes as p,dist_exports as r,initializeDataLayer as s,GuestUsername as t,isQuestionTypeRegistered as u};
|
|
377
|
-
//# sourceMappingURL=dist-
|
|
377
|
+
//# sourceMappingURL=dist-CDEq0Y3a.js.map
|