@vue-skuilder/db 0.2.35 → 0.2.36
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/CLAUDE.md +15 -4
- package/build.entries.mjs +12 -0
- package/dist/_virtual/_rolldown/runtime.mjs +8 -0
- package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
- package/dist/core/UserDBDebugger.mjs +285 -0
- package/dist/core/UserDBDebugger.mjs.map +1 -0
- package/dist/core/bulkImport/cardProcessor.mjs +106 -0
- package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
- package/dist/core/{index.js → index.cjs} +6438 -7784
- package/dist/core/index.cjs.map +1 -0
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.mjs +20 -11368
- package/dist/core/interfaces/contentSource.mjs +20 -0
- package/dist/core/interfaces/contentSource.mjs.map +1 -0
- package/dist/core/navigators/Pipeline.mjs +723 -0
- package/dist/core/navigators/Pipeline.mjs.map +1 -0
- package/dist/core/navigators/PipelineAssembler.mjs +86 -0
- package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
- package/dist/core/navigators/PipelineDebugger.mjs +771 -0
- package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
- package/dist/core/navigators/SrsDebugger.mjs +34 -0
- package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
- package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
- package/dist/core/navigators/defaults.mjs +96 -0
- package/dist/core/navigators/defaults.mjs.map +1 -0
- package/dist/core/navigators/diversityRerank.mjs +85 -0
- package/dist/core/navigators/diversityRerank.mjs.map +1 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
- package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
- package/dist/core/navigators/filters/eloDistance.mjs +244 -0
- package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
- package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
- package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
- package/dist/core/navigators/filters/relativePriority.mjs +135 -0
- package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
- package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
- package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
- package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
- package/dist/core/navigators/generators/elo.mjs +77 -0
- package/dist/core/navigators/generators/elo.mjs.map +1 -0
- package/dist/core/navigators/generators/prescribed.mjs +676 -0
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
- package/dist/core/navigators/generators/srs.mjs +158 -0
- package/dist/core/navigators/generators/srs.mjs.map +1 -0
- package/dist/core/navigators/index.mjs +345 -0
- package/dist/core/navigators/index.mjs.map +1 -0
- package/dist/core/navigators/pipelinePlan.mjs +109 -0
- package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
- package/dist/core/navigators/regulators.mjs +128 -0
- package/dist/core/navigators/regulators.mjs.map +1 -0
- package/dist/core/orchestration/gradient.mjs +101 -0
- package/dist/core/orchestration/gradient.mjs.map +1 -0
- package/dist/core/orchestration/index.mjs +115 -0
- package/dist/core/orchestration/index.mjs.map +1 -0
- package/dist/core/orchestration/learning.mjs +140 -0
- package/dist/core/orchestration/learning.mjs.map +1 -0
- package/dist/core/orchestration/recording.mjs +64 -0
- package/dist/core/orchestration/recording.mjs.map +1 -0
- package/dist/core/orchestration/signal.mjs +40 -0
- package/dist/core/orchestration/signal.mjs.map +1 -0
- package/dist/core/types/contentNavigationStrategy.mjs +10 -0
- package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
- package/dist/core/types/hydration.mjs +13 -0
- package/dist/core/types/hydration.mjs.map +1 -0
- package/dist/core/types/strategyState.mjs +16 -0
- package/dist/core/types/strategyState.mjs.map +1 -0
- package/dist/core/types/studySession.mjs +14 -0
- package/dist/core/types/studySession.mjs.map +1 -0
- package/dist/core/types/types-legacy.mjs +44 -0
- package/dist/core/types/types-legacy.mjs.map +1 -0
- package/dist/core/util/index.mjs +31 -0
- package/dist/core/util/index.mjs.map +1 -0
- package/dist/core/versionStamps.mjs +46 -0
- package/dist/core/versionStamps.mjs.map +1 -0
- package/dist/courseConfigRegistration.mjs +306 -0
- package/dist/courseConfigRegistration.mjs.map +1 -0
- package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
- package/dist/diagnostics/dataset.mjs +118 -0
- package/dist/diagnostics/dataset.mjs.map +1 -0
- package/dist/diagnostics/derive.mjs +318 -0
- package/dist/diagnostics/derive.mjs.map +1 -0
- package/dist/diagnostics/{index.js → index.cjs} +1 -1
- package/dist/diagnostics/index.d.ts +3 -3
- package/dist/diagnostics/index.mjs +7 -1042
- package/dist/diagnostics/loader.mjs +151 -0
- package/dist/diagnostics/loader.mjs.map +1 -0
- package/dist/diagnostics/pipeline.mjs +161 -0
- package/dist/diagnostics/pipeline.mjs.map +1 -0
- package/dist/diagnostics/tagElo.mjs +177 -0
- package/dist/diagnostics/tagElo.mjs.map +1 -0
- package/dist/diagnostics/text.mjs +174 -0
- package/dist/diagnostics/text.mjs.map +1 -0
- package/dist/factory.mjs +70 -0
- package/dist/factory.mjs.map +1 -0
- package/dist/impl/common/BaseUserDB.mjs +1103 -0
- package/dist/impl/common/BaseUserDB.mjs.map +1 -0
- package/dist/impl/common/userDBHelpers.mjs +49 -0
- package/dist/impl/common/userDBHelpers.mjs.map +1 -0
- package/dist/impl/common/userDBKeys.mjs +45 -0
- package/dist/impl/common/userDBKeys.mjs.map +1 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
- package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
- package/dist/impl/couch/CourseSyncService.mjs +242 -0
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
- package/dist/impl/couch/adminDB.mjs +61 -0
- package/dist/impl/couch/adminDB.mjs.map +1 -0
- package/dist/impl/couch/auth.mjs +33 -0
- package/dist/impl/couch/auth.mjs.map +1 -0
- package/dist/impl/couch/classroomDB.mjs +227 -0
- package/dist/impl/couch/classroomDB.mjs.map +1 -0
- package/dist/impl/couch/clientCache.mjs +15 -0
- package/dist/impl/couch/clientCache.mjs.map +1 -0
- package/dist/impl/couch/courseAPI.mjs +183 -0
- package/dist/impl/couch/courseAPI.mjs.map +1 -0
- package/dist/impl/couch/courseDB.mjs +729 -0
- package/dist/impl/couch/courseDB.mjs.map +1 -0
- package/dist/impl/couch/courseLookupDB.mjs +94 -0
- package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
- package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
- package/dist/impl/couch/index.cjs.map +1 -0
- package/dist/impl/couch/index.d.ts +12 -5
- package/dist/impl/couch/index.mjs +134 -12146
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/couch/pouchdb-setup.mjs +15 -0
- package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
- package/dist/impl/couch/updateQueue.mjs +101 -0
- package/dist/impl/couch/updateQueue.mjs.map +1 -0
- package/dist/impl/couch/user-course-relDB.mjs +55 -0
- package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
- package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
- package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
- package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
- package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
- package/dist/impl/static/courseDB.mjs +368 -0
- package/dist/impl/static/courseDB.mjs.map +1 -0
- package/dist/impl/static/coursesDB.mjs +38 -0
- package/dist/impl/static/coursesDB.mjs.map +1 -0
- package/dist/impl/static/{index.js → index.cjs} +2461 -5992
- package/dist/impl/static/index.cjs.map +1 -0
- package/dist/impl/static/index.d.ts +4 -4
- package/dist/impl/static/index.mjs +6 -10741
- package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
- package/dist/{index.js → index.cjs} +14070 -14239
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +12 -23
- package/dist/index.mjs +38 -16937
- package/dist/pouch/{index.js → index.cjs} +5 -1
- package/dist/pouch/index.cjs.map +1 -0
- package/dist/pouch/index.mjs +2 -19
- package/dist/study/ItemQueue.mjs +95 -0
- package/dist/study/ItemQueue.mjs.map +1 -0
- package/dist/study/MixerDebugger.mjs +303 -0
- package/dist/study/MixerDebugger.mjs.map +1 -0
- package/dist/study/SessionController.mjs +1187 -0
- package/dist/study/SessionController.mjs.map +1 -0
- package/dist/study/SessionDebugger.mjs +271 -0
- package/dist/study/SessionDebugger.mjs.map +1 -0
- package/dist/study/SessionOverlay.mjs +407 -0
- package/dist/study/SessionOverlay.mjs.map +1 -0
- package/dist/study/SourceMixer.mjs +45 -0
- package/dist/study/SourceMixer.mjs.map +1 -0
- package/dist/study/SpacedRepetition.mjs +108 -0
- package/dist/study/SpacedRepetition.mjs.map +1 -0
- package/dist/study/TagFilteredContentSource.mjs +136 -0
- package/dist/study/TagFilteredContentSource.mjs.map +1 -0
- package/dist/study/services/CardHydrationService.mjs +172 -0
- package/dist/study/services/CardHydrationService.mjs.map +1 -0
- package/dist/study/services/EloService.mjs +217 -0
- package/dist/study/services/EloService.mjs.map +1 -0
- package/dist/study/services/ResponseProcessor.mjs +190 -0
- package/dist/study/services/ResponseProcessor.mjs.map +1 -0
- package/dist/study/services/SrsService.mjs +49 -0
- package/dist/study/services/SrsService.mjs.map +1 -0
- package/dist/study/services/tagRecent.mjs +65 -0
- package/dist/study/services/tagRecent.mjs.map +1 -0
- package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
- package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
- package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
- package/dist/util/Loggable.mjs +14 -0
- package/dist/util/Loggable.mjs.map +1 -0
- package/dist/util/dataDirectory.mjs +47 -0
- package/dist/util/dataDirectory.mjs.map +1 -0
- package/dist/util/logger.mjs +86 -0
- package/dist/util/logger.mjs.map +1 -0
- package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
- package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
- package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
- package/dist/util/migrator/types.mjs +11 -0
- package/dist/util/migrator/types.mjs.map +1 -0
- package/dist/util/migrator/validation.mjs +334 -0
- package/dist/util/migrator/validation.mjs.map +1 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
- package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
- package/dist/util/packer/{index.js → index.cjs} +73 -9
- package/dist/util/packer/index.cjs.map +1 -0
- package/dist/util/packer/index.d.ts +3 -3
- package/dist/util/packer/index.mjs +2 -537
- package/eslint.config.mjs +9 -1
- package/package.json +25 -13
- package/rolldown.config.mjs +44 -0
- package/src/core/UserDBDebugger.ts +47 -46
- package/src/core/navigators/Pipeline.ts +10 -10
- package/src/core/navigators/PipelineDebugger.ts +55 -55
- package/src/core/navigators/filters/eloDistance.ts +1 -1
- package/src/core/navigators/generators/elo.ts +5 -1
- package/src/core/navigators/index.ts +9 -3
- package/src/factory.ts +10 -1
- package/src/impl/common/BaseUserDB.ts +1 -3
- package/src/impl/common/index.ts +2 -0
- package/src/impl/common/userDBHelpers.ts +4 -58
- package/src/impl/common/userDBKeys.ts +64 -0
- package/src/impl/couch/courseDB.ts +15 -3
- package/src/impl/couch/index.ts +2 -18
- package/src/impl/couch/pouchdb-setup.ts +8 -0
- package/src/index.ts +1 -1
- package/src/study/MixerDebugger.ts +46 -46
- package/src/study/SessionDebugger.ts +20 -20
- package/src/study/SessionOverlay.ts +4 -4
- package/src/util/logger.ts +112 -13
- package/tests/core/navigators/eloGenerator.test.ts +36 -0
- package/tsup.config.ts +24 -21
- package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
- package/dist/classroomDB-DLTtLZct.d.cts +0 -86
- package/dist/contentSource-FQZcZopC.d.cts +0 -2007
- package/dist/core/index.d.cts +0 -521
- package/dist/core/index.js.map +0 -1
- package/dist/core/index.mjs.map +0 -1
- package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
- package/dist/diagnostics/index.d.cts +0 -561
- package/dist/diagnostics/index.mjs.map +0 -1
- package/dist/impl/couch/index.d.cts +0 -620
- package/dist/impl/couch/index.js.map +0 -1
- package/dist/impl/static/index.d.cts +0 -232
- package/dist/impl/static/index.js.map +0 -1
- package/dist/impl/static/index.mjs.map +0 -1
- package/dist/index-BIum9Ue2.d.cts +0 -137
- package/dist/index.d.cts +0 -1663
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/pouch/index.d.cts +0 -1
- package/dist/pouch/index.js.map +0 -1
- package/dist/pouch/index.mjs.map +0 -1
- package/dist/types-BcWVH4ww.d.cts +0 -58
- package/dist/types-legacy-DdVjg81H.d.ts +0 -168
- package/dist/util/packer/index.d.cts +0 -5
- package/dist/util/packer/index.js.map +0 -1
- package/dist/util/packer/index.mjs.map +0 -1
- package/src/study/getCardDataShape.ts +0 -34
- /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { logger } from "../logger.mjs";
|
|
3
|
+
import { DocType } from "../../core/types/types-legacy.mjs";
|
|
4
|
+
//#region src/util/packer/CouchDBToStaticPacker.ts
|
|
5
|
+
var CouchDBToStaticPacker = class {
|
|
6
|
+
config;
|
|
7
|
+
sourceDB = null;
|
|
8
|
+
constructor(config = {}) {
|
|
9
|
+
this.config = {
|
|
10
|
+
chunkSize: 1e3,
|
|
11
|
+
includeAttachments: true,
|
|
12
|
+
...config
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Pack a CouchDB course database into static data structures
|
|
17
|
+
*/
|
|
18
|
+
async packCourse(sourceDB, courseId) {
|
|
19
|
+
logger.info(`Starting static pack for course: ${courseId}`);
|
|
20
|
+
this.sourceDB = sourceDB;
|
|
21
|
+
const manifest = {
|
|
22
|
+
version: "1.0.0",
|
|
23
|
+
courseId,
|
|
24
|
+
courseName: "",
|
|
25
|
+
courseConfig: null,
|
|
26
|
+
lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
|
|
27
|
+
documentCount: 0,
|
|
28
|
+
chunks: [],
|
|
29
|
+
indices: [],
|
|
30
|
+
designDocs: []
|
|
31
|
+
};
|
|
32
|
+
const courseConfig = await this.extractCourseConfig(sourceDB);
|
|
33
|
+
manifest.courseName = courseConfig.name;
|
|
34
|
+
manifest.courseConfig = courseConfig;
|
|
35
|
+
manifest.designDocs = await this.extractDesignDocs(sourceDB);
|
|
36
|
+
const docsByType = await this.extractDocumentsByType(sourceDB);
|
|
37
|
+
const attachments = /* @__PURE__ */ new Map();
|
|
38
|
+
if (this.config.includeAttachments) await this.extractAllAttachments(docsByType, attachments);
|
|
39
|
+
const chunks = /* @__PURE__ */ new Map();
|
|
40
|
+
for (const [docType, docs] of Object.entries(docsByType)) {
|
|
41
|
+
const chunkMetadata = this.createChunks(docs, docType);
|
|
42
|
+
manifest.chunks.push(...chunkMetadata);
|
|
43
|
+
manifest.documentCount += docs.length;
|
|
44
|
+
this.prepareChunkData(chunkMetadata, docs, chunks);
|
|
45
|
+
}
|
|
46
|
+
const indices = /* @__PURE__ */ new Map();
|
|
47
|
+
manifest.indices = await this.buildIndices(docsByType, manifest.designDocs, indices);
|
|
48
|
+
return {
|
|
49
|
+
manifest,
|
|
50
|
+
chunks,
|
|
51
|
+
indices,
|
|
52
|
+
attachments
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Pack a CouchDB course database and write the static files to disk
|
|
57
|
+
*/
|
|
58
|
+
async packCourseToFiles(sourceDB, courseId, outputDir, fsAdapter) {
|
|
59
|
+
logger.info(`Packing course ${courseId} to files in ${outputDir}`);
|
|
60
|
+
const packedData = await this.packCourse(sourceDB, courseId);
|
|
61
|
+
const filesWritten = await this.writePackedDataToFiles(packedData, outputDir, fsAdapter);
|
|
62
|
+
return {
|
|
63
|
+
manifest: packedData.manifest,
|
|
64
|
+
filesWritten,
|
|
65
|
+
attachmentsFound: packedData.attachments ? packedData.attachments.size : 0
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Write packed course data to files using FileSystemAdapter
|
|
70
|
+
*/
|
|
71
|
+
async writePackedDataToFiles(packedData, outputDir, fsAdapter) {
|
|
72
|
+
let totalFiles = 0;
|
|
73
|
+
await fsAdapter.ensureDir(outputDir);
|
|
74
|
+
const manifestPath = fsAdapter.joinPath(outputDir, "manifest.json");
|
|
75
|
+
await fsAdapter.writeJson(manifestPath, packedData.manifest, { spaces: 2 });
|
|
76
|
+
totalFiles++;
|
|
77
|
+
logger.info(`Wrote manifest: ${manifestPath}`);
|
|
78
|
+
const chunksDir = fsAdapter.joinPath(outputDir, "chunks");
|
|
79
|
+
const indicesDir = fsAdapter.joinPath(outputDir, "indices");
|
|
80
|
+
await fsAdapter.ensureDir(chunksDir);
|
|
81
|
+
await fsAdapter.ensureDir(indicesDir);
|
|
82
|
+
for (const [chunkId, chunkData] of packedData.chunks) {
|
|
83
|
+
const chunkPath = fsAdapter.joinPath(chunksDir, `${chunkId}.json`);
|
|
84
|
+
await fsAdapter.writeJson(chunkPath, chunkData);
|
|
85
|
+
totalFiles++;
|
|
86
|
+
}
|
|
87
|
+
logger.info(`Wrote ${packedData.chunks.size} chunk files`);
|
|
88
|
+
for (const [indexName, indexData] of packedData.indices) {
|
|
89
|
+
const indexPath = fsAdapter.joinPath(indicesDir, `${indexName}.json`);
|
|
90
|
+
await fsAdapter.writeJson(indexPath, indexData, { spaces: 2 });
|
|
91
|
+
totalFiles++;
|
|
92
|
+
}
|
|
93
|
+
logger.info(`Wrote ${packedData.indices.size} index files`);
|
|
94
|
+
if (packedData.attachments && packedData.attachments.size > 0) {
|
|
95
|
+
for (const [attachmentPath, attachmentData] of packedData.attachments) {
|
|
96
|
+
const fullAttachmentPath = fsAdapter.joinPath(outputDir, attachmentPath);
|
|
97
|
+
const attachmentDir = fsAdapter.dirname(fullAttachmentPath);
|
|
98
|
+
await fsAdapter.ensureDir(attachmentDir);
|
|
99
|
+
await fsAdapter.writeFile(fullAttachmentPath, attachmentData.buffer);
|
|
100
|
+
totalFiles++;
|
|
101
|
+
}
|
|
102
|
+
logger.info(`Wrote ${packedData.attachments.size} attachment files`);
|
|
103
|
+
}
|
|
104
|
+
return totalFiles;
|
|
105
|
+
}
|
|
106
|
+
async extractCourseConfig(db) {
|
|
107
|
+
try {
|
|
108
|
+
return await db.get("CourseConfig");
|
|
109
|
+
} catch (error) {
|
|
110
|
+
logger.error("Failed to extract course config:", error);
|
|
111
|
+
throw new Error("Course config not found");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async extractDesignDocs(db) {
|
|
115
|
+
return (await db.allDocs({
|
|
116
|
+
startkey: "_design/",
|
|
117
|
+
endkey: "_design/",
|
|
118
|
+
include_docs: true
|
|
119
|
+
})).rows.map((row) => ({
|
|
120
|
+
_id: row.id,
|
|
121
|
+
views: row.doc.views || {}
|
|
122
|
+
}));
|
|
123
|
+
}
|
|
124
|
+
async extractDocumentsByType(db) {
|
|
125
|
+
const allDocs = await db.allDocs({ include_docs: true });
|
|
126
|
+
const docsByType = {};
|
|
127
|
+
for (const row of allDocs.rows) {
|
|
128
|
+
if (row.id.startsWith("_")) continue;
|
|
129
|
+
const doc = row.doc;
|
|
130
|
+
if (doc.docType) {
|
|
131
|
+
if (!docsByType[doc.docType]) docsByType[doc.docType] = [];
|
|
132
|
+
docsByType[doc.docType].push(doc);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return docsByType;
|
|
136
|
+
}
|
|
137
|
+
createChunks(docs, docType) {
|
|
138
|
+
const chunks = [];
|
|
139
|
+
const sortedDocs = docs.sort((a, b) => a._id.localeCompare(b._id));
|
|
140
|
+
for (let i = 0; i < sortedDocs.length; i += this.config.chunkSize) {
|
|
141
|
+
const chunk = sortedDocs.slice(i, i + this.config.chunkSize);
|
|
142
|
+
const chunkId = `${docType}-${String(Math.floor(i / this.config.chunkSize)).padStart(4, "0")}`;
|
|
143
|
+
chunks.push({
|
|
144
|
+
id: chunkId,
|
|
145
|
+
docType,
|
|
146
|
+
startKey: chunk[0]._id,
|
|
147
|
+
endKey: chunk[chunk.length - 1]._id,
|
|
148
|
+
documentCount: chunk.length,
|
|
149
|
+
path: `chunks/${chunkId}.json`
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return chunks;
|
|
153
|
+
}
|
|
154
|
+
prepareChunkData(chunkMetadata, docs, chunks) {
|
|
155
|
+
const sortedDocs = docs.sort((a, b) => a._id.localeCompare(b._id));
|
|
156
|
+
for (const chunk of chunkMetadata) {
|
|
157
|
+
const cleanedDocs = sortedDocs.filter((doc) => doc._id >= chunk.startKey && doc._id <= chunk.endKey).map((doc) => {
|
|
158
|
+
const cleaned = { ...doc };
|
|
159
|
+
delete cleaned._rev;
|
|
160
|
+
if (this.config.includeAttachments && cleaned._attachments) cleaned._attachments = this.transformAttachmentStubs(cleaned._attachments, cleaned._id);
|
|
161
|
+
else if (!this.config.includeAttachments) delete cleaned._attachments;
|
|
162
|
+
return cleaned;
|
|
163
|
+
});
|
|
164
|
+
chunks.set(chunk.id, cleanedDocs);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async buildIndices(docsByType, designDocs, indices) {
|
|
168
|
+
const indexMetadata = [];
|
|
169
|
+
if (docsByType[DocType.CARD]) {
|
|
170
|
+
const eloIndexMeta = await this.buildEloIndex(docsByType[DocType.CARD], indices);
|
|
171
|
+
indexMetadata.push(eloIndexMeta);
|
|
172
|
+
}
|
|
173
|
+
if (docsByType[DocType.TAG]) {
|
|
174
|
+
const tagIndexMeta = await this.buildTagIndex(docsByType[DocType.TAG], indices);
|
|
175
|
+
indexMetadata.push(tagIndexMeta);
|
|
176
|
+
}
|
|
177
|
+
for (const designDoc of designDocs) for (const [viewName, viewDef] of Object.entries(designDoc.views)) if (viewDef.map) {
|
|
178
|
+
logger.info(`Processing view: ${designDoc._id}/${viewName}`);
|
|
179
|
+
const indexMeta = await this.buildViewIndex(viewName, designDoc, indices);
|
|
180
|
+
if (indexMeta) {
|
|
181
|
+
indexMetadata.push(indexMeta);
|
|
182
|
+
logger.info(`Successfully built index: ${indexMeta.name}`);
|
|
183
|
+
} else logger.warn(`Skipped view index: ${designDoc._id}/${viewName}`);
|
|
184
|
+
}
|
|
185
|
+
return indexMetadata;
|
|
186
|
+
}
|
|
187
|
+
async buildEloIndex(cards, indices) {
|
|
188
|
+
const eloIndex = [];
|
|
189
|
+
for (const card of cards) if (card.elo?.global?.score) eloIndex.push({
|
|
190
|
+
elo: card.elo.global.score,
|
|
191
|
+
cardId: card._id
|
|
192
|
+
});
|
|
193
|
+
eloIndex.sort((a, b) => a.elo - b.elo);
|
|
194
|
+
const buckets = {};
|
|
195
|
+
const bucketSize = 50;
|
|
196
|
+
for (const entry of eloIndex) {
|
|
197
|
+
const bucket = Math.floor(entry.elo / bucketSize) * bucketSize;
|
|
198
|
+
if (!buckets[bucket]) buckets[bucket] = [];
|
|
199
|
+
buckets[bucket].push(entry.cardId);
|
|
200
|
+
}
|
|
201
|
+
indices.set("elo", {
|
|
202
|
+
sorted: eloIndex,
|
|
203
|
+
buckets,
|
|
204
|
+
stats: {
|
|
205
|
+
min: eloIndex[0]?.elo || 0,
|
|
206
|
+
max: eloIndex[eloIndex.length - 1]?.elo || 0,
|
|
207
|
+
count: eloIndex.length
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
return {
|
|
211
|
+
name: "elo",
|
|
212
|
+
type: "btree",
|
|
213
|
+
path: "indices/elo.json"
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
async buildTagIndex(tags, indices) {
|
|
217
|
+
const tagIndex = {};
|
|
218
|
+
for (const tag of tags) tagIndex[tag.name] = {
|
|
219
|
+
cardIds: tag.taggedCards,
|
|
220
|
+
snippet: tag.snippet,
|
|
221
|
+
count: tag.taggedCards.length
|
|
222
|
+
};
|
|
223
|
+
const cardToTags = {};
|
|
224
|
+
for (const tag of tags) for (const cardId of tag.taggedCards) {
|
|
225
|
+
if (!cardToTags[cardId]) cardToTags[cardId] = [];
|
|
226
|
+
cardToTags[cardId].push(tag.name);
|
|
227
|
+
}
|
|
228
|
+
indices.set("tags", {
|
|
229
|
+
byTag: tagIndex,
|
|
230
|
+
byCard: cardToTags
|
|
231
|
+
});
|
|
232
|
+
return {
|
|
233
|
+
name: "tags",
|
|
234
|
+
type: "hash",
|
|
235
|
+
path: "indices/tags.json"
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Build view index by querying CouchDB views directly instead of parsing map functions
|
|
240
|
+
*/
|
|
241
|
+
async buildViewIndex(viewName, designDoc, indices) {
|
|
242
|
+
if (!this.sourceDB) {
|
|
243
|
+
logger.error("Source database not available for view querying");
|
|
244
|
+
return null;
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
const viewPath = `${designDoc._id.replace("_design/", "")}/${viewName}`;
|
|
248
|
+
logger.info(`Querying CouchDB view: ${viewPath}`);
|
|
249
|
+
const viewResults = await this.sourceDB.query(viewPath, { include_docs: false });
|
|
250
|
+
if (!viewResults.rows || viewResults.rows.length === 0) {
|
|
251
|
+
logger.warn(`View ${viewPath} returned no results`);
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
logger.info(`Successfully queried view ${viewPath}: ${viewResults.rows.length} results`);
|
|
255
|
+
const formattedResults = this.formatViewResults(viewName, viewResults.rows, designDoc);
|
|
256
|
+
const indexName = `view-${designDoc._id.replace("_design/", "")}-${viewName}`;
|
|
257
|
+
indices.set(indexName, formattedResults);
|
|
258
|
+
return {
|
|
259
|
+
name: indexName,
|
|
260
|
+
type: "view",
|
|
261
|
+
path: `indices/${indexName}.json`
|
|
262
|
+
};
|
|
263
|
+
} catch (error) {
|
|
264
|
+
logger.error(`Failed to query view ${designDoc._id}/${viewName}:`, error);
|
|
265
|
+
return null;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Format CouchDB view results for static consumption
|
|
270
|
+
*/
|
|
271
|
+
formatViewResults(viewName, viewRows, designDoc) {
|
|
272
|
+
const baseResult = {
|
|
273
|
+
type: "couchdb-view",
|
|
274
|
+
viewName,
|
|
275
|
+
designDoc: designDoc._id,
|
|
276
|
+
results: viewRows,
|
|
277
|
+
metadata: {
|
|
278
|
+
resultCount: viewRows.length,
|
|
279
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
switch (viewName) {
|
|
283
|
+
case "elo": return this.formatEloViewIndex(viewRows, baseResult);
|
|
284
|
+
case "getTags": return this.formatTagsViewIndex(viewRows, baseResult);
|
|
285
|
+
case "cardsByInexperience": return this.formatInexperienceViewIndex(viewRows, baseResult);
|
|
286
|
+
default: return this.formatGenericViewIndex(viewRows, baseResult);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Format ELO view results - convert to sorted array format
|
|
291
|
+
*/
|
|
292
|
+
formatEloViewIndex(viewRows, baseResult) {
|
|
293
|
+
const sortedResults = viewRows.sort((a, b) => {
|
|
294
|
+
if (typeof a.key === "number" && typeof b.key === "number") return a.key - b.key;
|
|
295
|
+
return 0;
|
|
296
|
+
});
|
|
297
|
+
return {
|
|
298
|
+
...baseResult,
|
|
299
|
+
sorted: sortedResults,
|
|
300
|
+
stats: {
|
|
301
|
+
min: sortedResults[0]?.key || 0,
|
|
302
|
+
max: sortedResults[sortedResults.length - 1]?.key || 0,
|
|
303
|
+
count: sortedResults.length
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Format tags view results - convert to tag mapping format
|
|
309
|
+
*/
|
|
310
|
+
formatTagsViewIndex(viewRows, baseResult) {
|
|
311
|
+
const tagMap = {};
|
|
312
|
+
for (const row of viewRows) {
|
|
313
|
+
const tagName = row.key;
|
|
314
|
+
if (typeof tagName === "string") {
|
|
315
|
+
if (!tagMap[tagName]) tagMap[tagName] = [];
|
|
316
|
+
tagMap[tagName].push(row.id);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
...baseResult,
|
|
321
|
+
byTag: tagMap,
|
|
322
|
+
tagCount: Object.keys(tagMap).length
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Format inexperience view results - convert to experience-based format
|
|
327
|
+
*/
|
|
328
|
+
formatInexperienceViewIndex(viewRows, baseResult) {
|
|
329
|
+
const sortedResults = viewRows.sort((a, b) => {
|
|
330
|
+
if (typeof a.key === "number" && typeof b.key === "number") return a.key - b.key;
|
|
331
|
+
return 0;
|
|
332
|
+
});
|
|
333
|
+
return {
|
|
334
|
+
...baseResult,
|
|
335
|
+
sorted: sortedResults,
|
|
336
|
+
stats: {
|
|
337
|
+
minInexperience: sortedResults[0]?.key || 0,
|
|
338
|
+
maxInexperience: sortedResults[sortedResults.length - 1]?.key || 0,
|
|
339
|
+
count: sortedResults.length
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Format generic view results - fallback for unknown views
|
|
345
|
+
*/
|
|
346
|
+
formatGenericViewIndex(_viewRows, baseResult) {
|
|
347
|
+
return { ...baseResult };
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Extract all attachments from documents and download binary data
|
|
351
|
+
*/
|
|
352
|
+
async extractAllAttachments(docsByType, attachments) {
|
|
353
|
+
logger.info("Extracting attachments...");
|
|
354
|
+
const allDocs = [];
|
|
355
|
+
for (const docs of Object.values(docsByType)) allDocs.push(...docs);
|
|
356
|
+
const docsWithAttachments = allDocs.filter((doc) => doc._attachments && Object.keys(doc._attachments).length > 0);
|
|
357
|
+
if (docsWithAttachments.length === 0) {
|
|
358
|
+
logger.info("No attachments found");
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
logger.info(`Found ${docsWithAttachments.length} documents with attachments`);
|
|
362
|
+
const extractionPromises = docsWithAttachments.map((doc) => this.extractDocumentAttachments(doc, attachments));
|
|
363
|
+
await Promise.all(extractionPromises);
|
|
364
|
+
logger.info(`Extracted ${attachments.size} attachment files`);
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Extract attachments for a single document
|
|
368
|
+
*/
|
|
369
|
+
async extractDocumentAttachments(doc, attachments) {
|
|
370
|
+
if (!doc._attachments || !this.sourceDB) return;
|
|
371
|
+
const docId = doc._id;
|
|
372
|
+
for (const [attachmentName, metadata] of Object.entries(doc._attachments)) try {
|
|
373
|
+
const attachmentResponse = await this.sourceDB.getAttachment(docId, attachmentName);
|
|
374
|
+
let buffer;
|
|
375
|
+
if (attachmentResponse instanceof ArrayBuffer) buffer = Buffer.from(attachmentResponse);
|
|
376
|
+
else if (Buffer.isBuffer(attachmentResponse)) buffer = attachmentResponse;
|
|
377
|
+
else {
|
|
378
|
+
const blob = attachmentResponse;
|
|
379
|
+
buffer = Buffer.from(await blob.arrayBuffer());
|
|
380
|
+
}
|
|
381
|
+
const filename = `${attachmentName}${this.getFileExtension(metadata.content_type)}`;
|
|
382
|
+
const attachmentPath = `attachments/${docId}/${filename}`;
|
|
383
|
+
attachments.set(attachmentPath, {
|
|
384
|
+
docId,
|
|
385
|
+
attachmentName,
|
|
386
|
+
filename,
|
|
387
|
+
path: attachmentPath,
|
|
388
|
+
contentType: metadata.content_type,
|
|
389
|
+
length: metadata.length || buffer.length,
|
|
390
|
+
digest: metadata.digest,
|
|
391
|
+
buffer
|
|
392
|
+
});
|
|
393
|
+
logger.debug(`Extracted attachment: ${attachmentPath}`);
|
|
394
|
+
} catch (error) {
|
|
395
|
+
logger.error(`Failed to extract attachment ${docId}/${attachmentName}:`, error);
|
|
396
|
+
throw new Error(`Failed to extract attachment ${docId}/${attachmentName}: ${error}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Transform attachment stubs to include file paths
|
|
401
|
+
*/
|
|
402
|
+
transformAttachmentStubs(attachments, docId) {
|
|
403
|
+
const transformed = {};
|
|
404
|
+
for (const [attachmentName, metadata] of Object.entries(attachments)) transformed[attachmentName] = {
|
|
405
|
+
path: `attachments/${docId}/${`${attachmentName}${this.getFileExtension(metadata.content_type)}`}`,
|
|
406
|
+
content_type: metadata.content_type,
|
|
407
|
+
length: metadata.length,
|
|
408
|
+
digest: metadata.digest,
|
|
409
|
+
stub: false
|
|
410
|
+
};
|
|
411
|
+
return transformed;
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Get file extension from content type
|
|
415
|
+
*/
|
|
416
|
+
getFileExtension(contentType) {
|
|
417
|
+
return {
|
|
418
|
+
"image/jpeg": ".jpg",
|
|
419
|
+
"image/jpg": ".jpg",
|
|
420
|
+
"image/png": ".png",
|
|
421
|
+
"image/gif": ".gif",
|
|
422
|
+
"image/webp": ".webp",
|
|
423
|
+
"audio/mpeg": ".mp3",
|
|
424
|
+
"audio/mp3": ".mp3",
|
|
425
|
+
"audio/wav": ".wav",
|
|
426
|
+
"audio/ogg": ".ogg",
|
|
427
|
+
"video/mp4": ".mp4",
|
|
428
|
+
"video/webm": ".webm",
|
|
429
|
+
"application/pdf": ".pdf",
|
|
430
|
+
"text/plain": ".txt",
|
|
431
|
+
"application/json": ".json"
|
|
432
|
+
}[contentType] || "";
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
//#endregion
|
|
436
|
+
export { CouchDBToStaticPacker };
|
|
437
|
+
|
|
438
|
+
//# sourceMappingURL=CouchDBToStaticPacker.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CouchDBToStaticPacker.mjs","names":[],"sources":["../../../src/util/packer/CouchDBToStaticPacker.ts"],"sourcesContent":["// packages/db/src/util/packer/CouchDBToStaticPacker.ts\n\nimport { CardData, DocType, Tag } from '../../core/types/types-legacy';\nimport { logger } from '../logger';\n// CourseConfig interface - simplified for packer use\n\nimport { CourseConfig } from '@vue-skuilder/common';\nimport {\n ChunkMetadata,\n DesignDocument,\n IndexMetadata,\n PackedCourseData,\n PackerConfig,\n StaticCourseManifest,\n AttachmentData,\n} from './types';\nimport { FileSystemAdapter } from '../migrator/FileSystemAdapter';\n\nexport class CouchDBToStaticPacker {\n private config: PackerConfig;\n private sourceDB: PouchDB.Database | null = null;\n\n constructor(config: Partial<PackerConfig> = {}) {\n this.config = {\n chunkSize: 1000,\n includeAttachments: true,\n ...config,\n };\n }\n\n /**\n * Pack a CouchDB course database into static data structures\n */\n async packCourse(sourceDB: PouchDB.Database, courseId: string): Promise<PackedCourseData> {\n logger.info(`Starting static pack for course: ${courseId}`);\n this.sourceDB = sourceDB;\n\n const manifest: StaticCourseManifest = {\n version: '1.0.0',\n courseId,\n courseName: '',\n courseConfig: null,\n lastUpdated: new Date().toISOString(),\n documentCount: 0,\n chunks: [],\n indices: [],\n designDocs: [],\n };\n\n // 1. Extract course config\n const courseConfig = await this.extractCourseConfig(sourceDB);\n manifest.courseName = courseConfig.name;\n manifest.courseConfig = courseConfig;\n\n // 2. Extract and process design documents\n manifest.designDocs = await this.extractDesignDocs(sourceDB);\n\n // 3. Extract all documents by type and create chunks\n const docsByType = await this.extractDocumentsByType(sourceDB);\n\n // 4. Extract attachments if enabled\n const attachments = new Map<string, AttachmentData>();\n if (this.config.includeAttachments) {\n await this.extractAllAttachments(docsByType, attachments);\n }\n\n // 5. Create chunks and prepare chunk data\n const chunks = new Map<string, any[]>();\n for (const [docType, docs] of Object.entries(docsByType)) {\n const chunkMetadata = this.createChunks(docs, docType as DocType);\n manifest.chunks.push(...chunkMetadata);\n manifest.documentCount += docs.length;\n\n // Prepare chunk data\n this.prepareChunkData(chunkMetadata, docs, chunks);\n }\n\n // 6. Build indices\n const indices = new Map<string, any>();\n manifest.indices = await this.buildIndices(docsByType, manifest.designDocs, indices);\n\n return {\n manifest,\n chunks,\n indices,\n attachments,\n };\n }\n\n /**\n * Pack a CouchDB course database and write the static files to disk\n */\n async packCourseToFiles(\n sourceDB: PouchDB.Database, \n courseId: string, \n outputDir: string, \n fsAdapter: FileSystemAdapter\n ): Promise<{ \n manifest: StaticCourseManifest; \n filesWritten: number; \n attachmentsFound: number; \n }> {\n logger.info(`Packing course ${courseId} to files in ${outputDir}`);\n \n // First, pack the course data\n const packedData = await this.packCourse(sourceDB, courseId);\n \n // Write the files using the FileSystemAdapter\n const filesWritten = await this.writePackedDataToFiles(packedData, outputDir, fsAdapter);\n \n return {\n manifest: packedData.manifest,\n filesWritten,\n attachmentsFound: packedData.attachments ? packedData.attachments.size : 0,\n };\n }\n\n /**\n * Write packed course data to files using FileSystemAdapter\n */\n private async writePackedDataToFiles(\n packedData: PackedCourseData,\n outputDir: string,\n fsAdapter: FileSystemAdapter\n ): Promise<number> {\n let totalFiles = 0;\n \n // Ensure output directory exists\n await fsAdapter.ensureDir(outputDir);\n \n // Write manifest\n const manifestPath = fsAdapter.joinPath(outputDir, 'manifest.json');\n await fsAdapter.writeJson(manifestPath, packedData.manifest, { spaces: 2 });\n totalFiles++;\n logger.info(`Wrote manifest: ${manifestPath}`);\n \n // Create subdirectories\n const chunksDir = fsAdapter.joinPath(outputDir, 'chunks');\n const indicesDir = fsAdapter.joinPath(outputDir, 'indices');\n await fsAdapter.ensureDir(chunksDir);\n await fsAdapter.ensureDir(indicesDir);\n \n // Write chunks\n for (const [chunkId, chunkData] of packedData.chunks) {\n const chunkPath = fsAdapter.joinPath(chunksDir, `${chunkId}.json`);\n await fsAdapter.writeJson(chunkPath, chunkData);\n totalFiles++;\n }\n logger.info(`Wrote ${packedData.chunks.size} chunk files`);\n \n // Write indices\n for (const [indexName, indexData] of packedData.indices) {\n const indexPath = fsAdapter.joinPath(indicesDir, `${indexName}.json`);\n await fsAdapter.writeJson(indexPath, indexData, { spaces: 2 });\n totalFiles++;\n }\n logger.info(`Wrote ${packedData.indices.size} index files`);\n \n // Write attachments\n if (packedData.attachments && packedData.attachments.size > 0) {\n for (const [attachmentPath, attachmentData] of packedData.attachments) {\n const fullAttachmentPath = fsAdapter.joinPath(outputDir, attachmentPath);\n \n // Ensure attachment directory exists\n const attachmentDir = fsAdapter.dirname(fullAttachmentPath);\n await fsAdapter.ensureDir(attachmentDir);\n \n // Write binary file\n await fsAdapter.writeFile(fullAttachmentPath, attachmentData.buffer);\n totalFiles++;\n }\n logger.info(`Wrote ${packedData.attachments.size} attachment files`);\n }\n \n return totalFiles;\n }\n\n private async extractCourseConfig(db: PouchDB.Database): Promise<CourseConfig> {\n try {\n return await db.get<CourseConfig>('CourseConfig');\n } catch (error) {\n logger.error('Failed to extract course config:', error);\n throw new Error('Course config not found');\n }\n }\n\n private async extractDesignDocs(db: PouchDB.Database): Promise<DesignDocument[]> {\n const result = await db.allDocs({\n startkey: '_design/',\n endkey: '_design/\\ufff0',\n include_docs: true,\n });\n\n return result.rows.map((row) => ({\n _id: row.id,\n views: (row.doc as any).views || {},\n }));\n }\n\n private async extractDocumentsByType(db: PouchDB.Database): Promise<Record<DocType, any[]>> {\n const allDocs = await db.allDocs({ include_docs: true });\n const docsByType: Record<string, any[]> = {};\n\n for (const row of allDocs.rows) {\n if (row.id.startsWith('_')) continue; // Skip design docs\n\n const doc = row.doc as any;\n if (doc.docType) {\n if (!docsByType[doc.docType]) {\n docsByType[doc.docType] = [];\n }\n docsByType[doc.docType].push(doc);\n }\n }\n\n return docsByType as Record<DocType, any[]>;\n }\n\n private createChunks(docs: any[], docType: DocType): ChunkMetadata[] {\n const chunks: ChunkMetadata[] = [];\n const sortedDocs = docs.sort((a, b) => a._id.localeCompare(b._id));\n\n for (let i = 0; i < sortedDocs.length; i += this.config.chunkSize) {\n const chunk = sortedDocs.slice(i, i + this.config.chunkSize);\n const chunkId = `${docType}-${String(Math.floor(i / this.config.chunkSize)).padStart(4, '0')}`;\n\n chunks.push({\n id: chunkId,\n docType,\n startKey: chunk[0]._id,\n endKey: chunk[chunk.length - 1]._id,\n documentCount: chunk.length,\n path: `chunks/${chunkId}.json`,\n });\n }\n\n return chunks;\n }\n\n private prepareChunkData(\n chunkMetadata: ChunkMetadata[],\n docs: any[],\n chunks: Map<string, any[]>\n ): void {\n const sortedDocs = docs.sort((a, b) => a._id.localeCompare(b._id));\n\n for (const chunk of chunkMetadata) {\n const chunkDocs = sortedDocs.filter(\n (doc) => doc._id >= chunk.startKey && doc._id <= chunk.endKey\n );\n\n // Clean documents for storage\n const cleanedDocs = chunkDocs.map((doc) => {\n const cleaned = { ...doc };\n delete cleaned._rev; // Remove revision info\n \n if (this.config.includeAttachments && cleaned._attachments) {\n // Transform attachment stubs to file paths\n cleaned._attachments = this.transformAttachmentStubs(cleaned._attachments, cleaned._id);\n } else if (!this.config.includeAttachments) {\n delete cleaned._attachments;\n }\n \n return cleaned;\n });\n\n chunks.set(chunk.id, cleanedDocs);\n }\n }\n\n private async buildIndices(\n docsByType: Record<DocType, any[]>,\n designDocs: DesignDocument[],\n indices: Map<string, any>\n ): Promise<IndexMetadata[]> {\n const indexMetadata: IndexMetadata[] = [];\n\n // Build ELO index\n if (docsByType[DocType.CARD]) {\n const eloIndexMeta = await this.buildEloIndex(\n docsByType[DocType.CARD] as CardData[],\n indices\n );\n indexMetadata.push(eloIndexMeta);\n }\n\n // Build tag indices\n if (docsByType[DocType.TAG]) {\n const tagIndexMeta = await this.buildTagIndex(docsByType[DocType.TAG] as Tag[], indices);\n indexMetadata.push(tagIndexMeta);\n }\n\n // Build indices from design documents using CouchDB view queries\n for (const designDoc of designDocs) {\n for (const [viewName, viewDef] of Object.entries(designDoc.views)) {\n if (viewDef.map) {\n logger.info(`Processing view: ${designDoc._id}/${viewName}`);\n const indexMeta = await this.buildViewIndex(viewName, designDoc, indices);\n if (indexMeta) {\n indexMetadata.push(indexMeta);\n logger.info(`Successfully built index: ${indexMeta.name}`);\n } else {\n logger.warn(`Skipped view index: ${designDoc._id}/${viewName}`);\n }\n }\n }\n }\n\n return indexMetadata;\n }\n\n private async buildEloIndex(\n cards: CardData[],\n indices: Map<string, any>\n ): Promise<IndexMetadata> {\n // Build a B-tree like structure for ELO queries\n const eloIndex: Array<{ elo: number; cardId: string }> = [];\n\n for (const card of cards) {\n if (card.elo?.global?.score) {\n eloIndex.push({\n elo: card.elo.global.score,\n cardId: (card as any)._id,\n });\n }\n }\n\n // Sort by ELO for efficient range queries\n eloIndex.sort((a, b) => a.elo - b.elo);\n\n // Create buckets for faster lookup\n const buckets: Record<number, string[]> = {};\n const bucketSize = 50; // ELO points per bucket\n\n for (const entry of eloIndex) {\n const bucket = Math.floor(entry.elo / bucketSize) * bucketSize;\n if (!buckets[bucket]) buckets[bucket] = [];\n buckets[bucket].push(entry.cardId);\n }\n\n // Store the index data\n indices.set('elo', {\n sorted: eloIndex,\n buckets: buckets,\n stats: {\n min: eloIndex[0]?.elo || 0,\n max: eloIndex[eloIndex.length - 1]?.elo || 0,\n count: eloIndex.length,\n },\n });\n\n return {\n name: 'elo',\n type: 'btree',\n path: 'indices/elo.json',\n };\n }\n\n private async buildTagIndex(tags: Tag[], indices: Map<string, any>): Promise<IndexMetadata> {\n // Build inverted index for tags\n const tagIndex: Record<\n string,\n {\n cardIds: string[];\n snippet: string;\n count: number;\n }\n > = {};\n\n for (const tag of tags) {\n tagIndex[tag.name] = {\n cardIds: tag.taggedCards,\n snippet: tag.snippet,\n count: tag.taggedCards.length,\n };\n }\n\n // Also build a reverse index (card -> tags)\n const cardToTags: Record<string, string[]> = {};\n for (const tag of tags) {\n for (const cardId of tag.taggedCards) {\n if (!cardToTags[cardId]) cardToTags[cardId] = [];\n cardToTags[cardId].push(tag.name);\n }\n }\n\n indices.set('tags', {\n byTag: tagIndex,\n byCard: cardToTags,\n });\n\n return {\n name: 'tags',\n type: 'hash',\n path: 'indices/tags.json',\n };\n }\n\n /**\n * Build view index by querying CouchDB views directly instead of parsing map functions\n */\n private async buildViewIndex(\n viewName: string,\n designDoc: DesignDocument,\n indices: Map<string, any>\n ): Promise<IndexMetadata | null> {\n if (!this.sourceDB) {\n logger.error('Source database not available for view querying');\n return null;\n }\n\n try {\n const designDocId = designDoc._id; // e.g., \"_design/elo\"\n const designDocName = designDocId.replace('_design/', ''); // Extract just \"elo\"\n const viewPath = `${designDocName}/${viewName}`;\n \n logger.info(`Querying CouchDB view: ${viewPath}`);\n \n // Query the view directly from CouchDB using PouchDB format: \"designDocName/viewName\"\n const viewResults = await this.sourceDB.query(viewPath, {\n include_docs: false,\n });\n\n if (!viewResults.rows || viewResults.rows.length === 0) {\n logger.warn(`View ${viewPath} returned no results`);\n return null;\n }\n\n logger.info(`Successfully queried view ${viewPath}: ${viewResults.rows.length} results`);\n\n // Format the results for static consumption\n const formattedResults = this.formatViewResults(viewName, viewResults.rows, designDoc);\n \n const indexName = `view-${designDoc._id.replace('_design/', '')}-${viewName}`;\n indices.set(indexName, formattedResults);\n\n return {\n name: indexName,\n type: 'view',\n path: `indices/${indexName}.json`,\n };\n } catch (error) {\n logger.error(`Failed to query view ${designDoc._id}/${viewName}:`, error);\n // Return null to gracefully skip this view rather than failing the entire pack\n return null;\n }\n }\n\n /**\n * Format CouchDB view results for static consumption\n */\n private formatViewResults(\n viewName: string,\n viewRows: Array<{ key: any; value: any; id: string }>,\n designDoc: DesignDocument\n ): any {\n const baseResult = {\n type: 'couchdb-view',\n viewName,\n designDoc: designDoc._id,\n results: viewRows,\n metadata: {\n resultCount: viewRows.length,\n generatedAt: new Date().toISOString(),\n },\n };\n\n // Apply view-specific formatting\n switch (viewName) {\n case 'elo':\n return this.formatEloViewIndex(viewRows, baseResult);\n case 'getTags':\n return this.formatTagsViewIndex(viewRows, baseResult);\n case 'cardsByInexperience':\n return this.formatInexperienceViewIndex(viewRows, baseResult);\n default:\n return this.formatGenericViewIndex(viewRows, baseResult);\n }\n }\n\n /**\n * Format ELO view results - convert to sorted array format\n */\n private formatEloViewIndex(\n viewRows: Array<{ key: any; value: any; id: string }>,\n baseResult: any\n ): any {\n // Sort by ELO score (key) for efficient range queries\n const sortedResults = viewRows.sort((a, b) => {\n if (typeof a.key === 'number' && typeof b.key === 'number') {\n return a.key - b.key;\n }\n return 0;\n });\n\n return {\n ...baseResult,\n sorted: sortedResults,\n stats: {\n min: sortedResults[0]?.key || 0,\n max: sortedResults[sortedResults.length - 1]?.key || 0,\n count: sortedResults.length,\n },\n };\n }\n\n /**\n * Format tags view results - convert to tag mapping format\n */\n private formatTagsViewIndex(\n viewRows: Array<{ key: any; value: any; id: string }>,\n baseResult: any\n ): any {\n // Group by tag name (key)\n const tagMap: Record<string, string[]> = {};\n \n for (const row of viewRows) {\n const tagName = row.key;\n if (typeof tagName === 'string') {\n if (!tagMap[tagName]) {\n tagMap[tagName] = [];\n }\n tagMap[tagName].push(row.id);\n }\n }\n\n return {\n ...baseResult,\n byTag: tagMap,\n tagCount: Object.keys(tagMap).length,\n };\n }\n\n /**\n * Format inexperience view results - convert to experience-based format\n */\n private formatInexperienceViewIndex(\n viewRows: Array<{ key: any; value: any; id: string }>,\n baseResult: any\n ): any {\n // Sort by inexperience level (key) - lower numbers = less experience\n const sortedResults = viewRows.sort((a, b) => {\n if (typeof a.key === 'number' && typeof b.key === 'number') {\n return a.key - b.key;\n }\n return 0;\n });\n\n return {\n ...baseResult,\n sorted: sortedResults,\n stats: {\n minInexperience: sortedResults[0]?.key || 0,\n maxInexperience: sortedResults[sortedResults.length - 1]?.key || 0,\n count: sortedResults.length,\n },\n };\n }\n\n /**\n * Format generic view results - fallback for unknown views\n */\n private formatGenericViewIndex(\n _viewRows: Array<{ key: any; value: any; id: string }>,\n baseResult: any\n ): any {\n return {\n ...baseResult,\n // Keep results as-is for unknown view types\n };\n }\n\n /**\n * Extract all attachments from documents and download binary data\n */\n private async extractAllAttachments(\n docsByType: Record<DocType, any[]>,\n attachments: Map<string, AttachmentData>\n ): Promise<void> {\n logger.info('Extracting attachments...');\n \n const allDocs: any[] = [];\n for (const docs of Object.values(docsByType)) {\n allDocs.push(...docs);\n }\n\n const docsWithAttachments = allDocs.filter(doc => doc._attachments && Object.keys(doc._attachments).length > 0);\n \n if (docsWithAttachments.length === 0) {\n logger.info('No attachments found');\n return;\n }\n\n logger.info(`Found ${docsWithAttachments.length} documents with attachments`);\n\n // Process attachments concurrently\n const extractionPromises = docsWithAttachments.map(doc => \n this.extractDocumentAttachments(doc, attachments)\n );\n\n await Promise.all(extractionPromises);\n \n logger.info(`Extracted ${attachments.size} attachment files`);\n }\n\n /**\n * Extract attachments for a single document\n */\n private async extractDocumentAttachments(\n doc: any,\n attachments: Map<string, AttachmentData>\n ): Promise<void> {\n if (!doc._attachments || !this.sourceDB) {\n return;\n }\n\n const docId = doc._id;\n \n for (const [attachmentName, metadata] of Object.entries(doc._attachments as Record<string, any>)) {\n try {\n // Download attachment binary data\n const attachmentResponse = await this.sourceDB.getAttachment(docId, attachmentName);\n \n // Convert to buffer\n let buffer: Buffer;\n if (attachmentResponse instanceof ArrayBuffer) {\n buffer = Buffer.from(attachmentResponse);\n } else if (Buffer.isBuffer(attachmentResponse)) {\n buffer = attachmentResponse;\n } else {\n // For browser environments, the response might be a Blob\n const blob = attachmentResponse as Blob;\n buffer = Buffer.from(await blob.arrayBuffer());\n }\n\n // Generate filename with proper extension\n const extension = this.getFileExtension(metadata.content_type);\n const filename = `${attachmentName}${extension}`;\n const attachmentPath = `attachments/${docId}/${filename}`;\n \n // Store attachment data\n attachments.set(attachmentPath, {\n docId,\n attachmentName,\n filename,\n path: attachmentPath,\n contentType: metadata.content_type,\n length: metadata.length || buffer.length,\n digest: metadata.digest,\n buffer,\n });\n\n logger.debug(`Extracted attachment: ${attachmentPath}`);\n } catch (error) {\n logger.error(`Failed to extract attachment ${docId}/${attachmentName}:`, error);\n throw new Error(`Failed to extract attachment ${docId}/${attachmentName}: ${error}`);\n }\n }\n }\n\n /**\n * Transform attachment stubs to include file paths\n */\n private transformAttachmentStubs(\n attachments: Record<string, any>,\n docId: string\n ): Record<string, any> {\n const transformed: Record<string, any> = {};\n \n for (const [attachmentName, metadata] of Object.entries(attachments)) {\n const extension = this.getFileExtension(metadata.content_type);\n const filename = `${attachmentName}${extension}`;\n const attachmentPath = `attachments/${docId}/${filename}`;\n \n transformed[attachmentName] = {\n path: attachmentPath,\n content_type: metadata.content_type,\n length: metadata.length,\n digest: metadata.digest,\n stub: false, // No longer a stub - we have the actual file\n };\n }\n \n return transformed;\n }\n\n /**\n * Get file extension from content type\n */\n private getFileExtension(contentType: string): string {\n const extensionMap: Record<string, string> = {\n 'image/jpeg': '.jpg',\n 'image/jpg': '.jpg', \n 'image/png': '.png',\n 'image/gif': '.gif',\n 'image/webp': '.webp',\n 'audio/mpeg': '.mp3',\n 'audio/mp3': '.mp3',\n 'audio/wav': '.wav',\n 'audio/ogg': '.ogg',\n 'video/mp4': '.mp4',\n 'video/webm': '.webm',\n 'application/pdf': '.pdf',\n 'text/plain': '.txt',\n 'application/json': '.json',\n };\n \n return extensionMap[contentType] || '';\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,wBAAb,MAAmC;CACjC;CACA,WAA4C;CAE5C,YAAY,SAAgC,EAAE,EAAE;AAC9C,OAAK,SAAS;GACZ,WAAW;GACX,oBAAoB;GACpB,GAAG;GACJ;;;;;CAMH,MAAM,WAAW,UAA4B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b,cAAc;GACd,mBAAmB;GACnB,cAAc;GACd,oBAAoB;GACrB,CAEmB,gBAAgB"}
|
|
@@ -25,13 +25,53 @@ __export(packer_exports, {
|
|
|
25
25
|
module.exports = __toCommonJS(packer_exports);
|
|
26
26
|
|
|
27
27
|
// src/util/logger.ts
|
|
28
|
-
var
|
|
28
|
+
var LEVELS = { debug: 0, info: 1, warn: 2, error: 3, silent: 4 };
|
|
29
|
+
var STORAGE_KEY = "sk.logLevel";
|
|
30
|
+
var isBrowser = typeof window !== "undefined";
|
|
31
|
+
function isLevel(v) {
|
|
32
|
+
return typeof v === "string" && v in LEVELS;
|
|
33
|
+
}
|
|
34
|
+
function initialLevel() {
|
|
35
|
+
if (isBrowser) {
|
|
36
|
+
try {
|
|
37
|
+
const stored = window.localStorage?.getItem(STORAGE_KEY);
|
|
38
|
+
if (isLevel(stored)) return stored;
|
|
39
|
+
} catch {
|
|
40
|
+
}
|
|
41
|
+
return "warn";
|
|
42
|
+
}
|
|
43
|
+
if (typeof process !== "undefined") {
|
|
44
|
+
const env = process.env.SK_LOG_LEVEL;
|
|
45
|
+
if (isLevel(env)) return env;
|
|
46
|
+
if (process.env.NODE_ENV === "development") return "debug";
|
|
47
|
+
}
|
|
48
|
+
return "info";
|
|
49
|
+
}
|
|
50
|
+
var shared = globalThis.__skuilderDbLog ??= {
|
|
51
|
+
level: initialLevel()
|
|
52
|
+
};
|
|
53
|
+
function getLogLevel() {
|
|
54
|
+
return shared.level;
|
|
55
|
+
}
|
|
56
|
+
function setLogLevel(level, persist = true) {
|
|
57
|
+
if (!isLevel(level)) {
|
|
58
|
+
console.warn(`[DB] Unknown log level '${level}'. Use one of: ${Object.keys(LEVELS).join(", ")}`);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
shared.level = level;
|
|
62
|
+
if (isBrowser && persist) {
|
|
63
|
+
try {
|
|
64
|
+
window.localStorage?.setItem(STORAGE_KEY, level);
|
|
65
|
+
} catch {
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
29
69
|
var logger = {
|
|
30
70
|
/**
|
|
31
|
-
* Debug-level logging
|
|
71
|
+
* Debug-level logging
|
|
32
72
|
*/
|
|
33
73
|
debug: (message, ...args) => {
|
|
34
|
-
if (
|
|
74
|
+
if (LEVELS[shared.level] <= LEVELS.debug) {
|
|
35
75
|
console.debug(`[DB:DEBUG] ${message}`, ...args);
|
|
36
76
|
}
|
|
37
77
|
},
|
|
@@ -39,29 +79,53 @@ var logger = {
|
|
|
39
79
|
* Info-level logging - general information
|
|
40
80
|
*/
|
|
41
81
|
info: (message, ...args) => {
|
|
42
|
-
|
|
82
|
+
if (LEVELS[shared.level] <= LEVELS.info) {
|
|
83
|
+
console.info(`[DB:INFO] ${message}`, ...args);
|
|
84
|
+
}
|
|
43
85
|
},
|
|
44
86
|
/**
|
|
45
87
|
* Warning-level logging - potential issues
|
|
46
88
|
*/
|
|
47
89
|
warn: (message, ...args) => {
|
|
48
|
-
|
|
90
|
+
if (LEVELS[shared.level] <= LEVELS.warn) {
|
|
91
|
+
console.warn(`[DB:WARN] ${message}`, ...args);
|
|
92
|
+
}
|
|
49
93
|
},
|
|
50
94
|
/**
|
|
51
95
|
* Error-level logging - serious problems
|
|
52
96
|
*/
|
|
53
97
|
error: (message, ...args) => {
|
|
54
|
-
|
|
98
|
+
if (LEVELS[shared.level] <= LEVELS.error) {
|
|
99
|
+
console.error(`[DB:ERROR] ${message}`, ...args);
|
|
100
|
+
}
|
|
55
101
|
},
|
|
56
102
|
/**
|
|
57
|
-
* Log function for backward compatibility with existing log() usage
|
|
103
|
+
* Log function for backward compatibility with existing log() usage.
|
|
104
|
+
* Debug level.
|
|
58
105
|
*/
|
|
59
106
|
log: (message, ...args) => {
|
|
60
|
-
if (
|
|
107
|
+
if (LEVELS[shared.level] <= LEVELS.debug) {
|
|
61
108
|
console.log(`[DB:LOG] ${message}`, ...args);
|
|
62
109
|
}
|
|
110
|
+
},
|
|
111
|
+
/**
|
|
112
|
+
* Ungated output for interactive console tools (`window.skuilder.*`). The
|
|
113
|
+
* user asked for it, so it prints regardless of level.
|
|
114
|
+
*/
|
|
115
|
+
print: (message, ...args) => {
|
|
116
|
+
console.log(message, ...args);
|
|
63
117
|
}
|
|
64
118
|
};
|
|
119
|
+
function mountLogLevelControl() {
|
|
120
|
+
if (!isBrowser) return;
|
|
121
|
+
const win = window;
|
|
122
|
+
win.skuilder = win.skuilder || {};
|
|
123
|
+
win.skuilder.logLevel = (level) => {
|
|
124
|
+
if (level !== void 0) setLogLevel(level);
|
|
125
|
+
return getLogLevel();
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
mountLogLevelControl();
|
|
65
129
|
|
|
66
130
|
// src/util/packer/CouchDBToStaticPacker.ts
|
|
67
131
|
var CouchDBToStaticPacker = class {
|
|
@@ -561,4 +625,4 @@ var CouchDBToStaticPacker = class {
|
|
|
561
625
|
0 && (module.exports = {
|
|
562
626
|
CouchDBToStaticPacker
|
|
563
627
|
});
|
|
564
|
-
//# sourceMappingURL=index.
|
|
628
|
+
//# sourceMappingURL=index.cjs.map
|