-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
3821 lines (3671 loc) · 139 KB
/
Copy pathmain.js
File metadata and controls
3821 lines (3671 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => CourseForgePlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian9 = require("obsidian");
// src/settings.ts
var PROVIDER_OPTIONS = {
openai: "OpenAI",
gemini: "Google Gemini",
groq: "Groq (Free & Fast)",
huggingface: "Hugging Face",
custom: "Custom / Local AI"
};
var PROVIDER_INFO = {
openai: {
description: "GPT-4 and other OpenAI models",
keyPlaceholder: "sk-...",
keyUrl: "https://platform.openai.com/api-keys"
},
gemini: {
description: "Google's Gemini models (free tier available)",
keyPlaceholder: "AIza...",
keyUrl: "https://aistudio.google.com/apikey"
},
groq: {
description: "Fast inference with Llama, Mixtral (free tier)",
keyPlaceholder: "gsk_...",
keyUrl: "https://console.groq.com/keys"
},
huggingface: {
description: "Open-source models via Hugging Face",
keyPlaceholder: "hf_...",
keyUrl: "https://huggingface.co/settings/tokens"
},
custom: {
description: "Your own AI server (OpenAI-compatible API)",
keyPlaceholder: "Optional API key"
}
};
var PROVIDER_MODELS = {
openai: [
{ id: "gpt-4.1", label: "GPT-4.1 (flagship)" },
{ id: "gpt-4.1-mini", label: "GPT-4.1 mini (fast, efficient)" },
{ id: "gpt-4.1-nano", label: "GPT-4.1 nano (fastest, cheapest)" },
{ id: "gpt-4o", label: "GPT-4o" },
{ id: "gpt-4o-mini", label: "GPT-4o mini" }
],
gemini: [
{ id: "gemini-3-pro-preview", label: "Gemini 3 Pro (preview)" },
{ id: "gemini-3-flash-preview", label: "Gemini 3 Flash (preview)" },
{ id: "gemini-2.5-pro", label: "Gemini 2.5 Pro" },
{ id: "gemini-2.5-flash", label: "Gemini 2.5 Flash" },
{ id: "gemini-2.5-flash-lite", label: "Gemini 2.5 Flash-Lite" },
{ id: "gemini-2.0-flash", label: "Gemini 2.0 Flash" },
{ id: "gemini-2.0-flash-lite", label: "Gemini 2.0 Flash-Lite" }
],
groq: [
{ id: "llama-3.3-70b-versatile", label: "Llama 3.3 70B Versatile (recommended)" },
{ id: "llama-3.1-8b-instant", label: "Llama 3.1 8B Instant (fast)" },
{ id: "llama-3.2-90b-vision-preview", label: "Llama 3.2 90B Vision" },
{ id: "mixtral-8x7b-32768", label: "Mixtral 8x7B (32K context)" },
{ id: "gemma2-9b-it", label: "Gemma 2 9B" }
],
huggingface: [
{ id: "Qwen/Qwen2.5-7B-Instruct", label: "Qwen 2.5 7B Instruct" },
{ id: "Qwen/Qwen2.5-14B-Instruct", label: "Qwen 2.5 14B Instruct" },
{ id: "Qwen/Qwen2.5-32B-Instruct", label: "Qwen 2.5 32B Instruct" },
{ id: "google/gemma-2-9b-it", label: "Gemma 2 9B IT" },
{ id: "mistralai/Mistral-7B-Instruct-v0.2", label: "Mistral 7B Instruct v0.2" },
{ id: "meta-llama/Llama-3.2-3B-Instruct", label: "Llama 3.2 3B Instruct" },
{ id: "HuggingFaceH4/zephyr-7b-beta", label: "Zephyr 7B Beta" }
],
custom: []
// User enters model name manually
};
var DEFAULT_SETTINGS = {
apiKey: "",
model: "",
provider: "groq",
providers: {
openai: { apiKey: "", model: "gpt-4.1-mini" },
gemini: { apiKey: "", model: "gemini-2.5-flash" },
groq: { apiKey: "", model: "llama-3.3-70b-versatile" },
huggingface: { apiKey: "", model: "Qwen/Qwen2.5-7B-Instruct" },
custom: { apiKey: "", model: "", endpoint: "http://localhost:11434/v1", customModel: "" }
},
courseFolder: ""
};
function getActiveApiKey(settings) {
return settings.providers[settings.provider]?.apiKey || settings.apiKey || "";
}
function getActiveModel(settings) {
const config = settings.providers[settings.provider];
if (settings.provider === "custom") {
return config?.customModel || "";
}
return config?.model || settings.model || "";
}
// src/settingsTab.ts
var import_obsidian2 = require("obsidian");
// src/generate/provider.ts
var import_obsidian = require("obsidian");
function createOpenAIProvider(apiKey, model) {
return {
async complete(prompt, options) {
if (!apiKey)
throw new Error("OpenAI API key not set. Add it in CourseForge settings.");
const response = await (0, import_obsidian.requestUrl)({
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model || "gpt-4.1-mini",
messages: [{ role: "user", content: prompt }],
max_tokens: options?.maxTokens ?? 4096,
temperature: options?.temperature ?? 0.3
}),
throw: false
});
if (response.status >= 400) {
let errMsg = `OpenAI API error (HTTP ${response.status})`;
try {
const errData = JSON.parse(response.text);
if (errData?.error?.message)
errMsg = errData.error.message;
} catch {
}
throw new Error(errMsg);
}
const data = JSON.parse(response.text);
const content = data?.choices?.[0]?.message?.content;
if (content == null)
throw new Error("Empty or invalid response from OpenAI");
return content.trim();
}
};
}
function createGeminiProvider(apiKey, model) {
return {
async complete(prompt, options) {
if (!apiKey)
throw new Error("Google AI API key not set. Add it in CourseForge settings.");
const modelId = model || "gemini-2.5-flash";
const response = await (0, import_obsidian.requestUrl)({
url: `https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent?key=${encodeURIComponent(apiKey)}`,
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
maxOutputTokens: options?.maxTokens ?? 8192,
temperature: options?.temperature ?? 0.3
},
safetySettings: [
{ category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
]
}),
throw: false
});
if (response.status >= 400) {
let errMsg = `Gemini API error (HTTP ${response.status})`;
try {
const errData = JSON.parse(response.text);
if (errData?.error?.message) {
errMsg = errData.error.message;
if (errMsg.toLowerCase().includes("leaked")) {
errMsg = "API key reported as leaked. Generate a new key at aistudio.google.com";
} else if (errMsg.toLowerCase().includes("quota")) {
errMsg = "API quota exceeded. Try again later or check your Google AI Studio billing.";
} else if (errMsg.toLowerCase().includes("not found") || response.status === 404) {
errMsg = `Model "${modelId}" not found. Try a different model in settings (e.g., gemini-2.0-flash).`;
}
}
} catch {
}
throw new Error(errMsg);
}
let data;
try {
data = JSON.parse(response.text);
} catch {
throw new Error("Failed to parse Gemini response. The API may be experiencing issues.");
}
if (data.promptFeedback?.blockReason) {
throw new Error(`Gemini blocked the prompt: ${data.promptFeedback.blockReason}. Try rephrasing or using a different URL.`);
}
if (!data.candidates || data.candidates.length === 0) {
throw new Error("Gemini returned no response. The content may have been filtered or the model couldn't process it.");
}
const candidate = data.candidates[0];
if (candidate.finishReason === "SAFETY") {
throw new Error("Gemini blocked the response due to safety filters. Try a different course URL.");
}
if (candidate.finishReason === "RECITATION") {
throw new Error("Gemini blocked the response due to recitation policy. Try a different course URL.");
}
const text = candidate.content?.parts?.[0]?.text;
if (text == null || text.trim() === "") {
const reason = candidate.finishReason || "unknown";
throw new Error(`Gemini returned empty content (reason: ${reason}). The model may have had trouble processing this content.`);
}
return text.trim();
}
};
}
function createCustomProvider(endpoint, apiKey, model) {
return {
async complete(prompt, options) {
if (!endpoint)
throw new Error("Custom endpoint URL not set. Add it in CourseForge settings.");
if (!model)
throw new Error("Custom model name not set. Add it in CourseForge settings.");
let url = endpoint.replace(/\/+$/, "");
if (!url.endsWith("/chat/completions")) {
url = url + "/chat/completions";
}
const headers = { "Content-Type": "application/json" };
if (apiKey) {
headers["Authorization"] = `Bearer ${apiKey}`;
}
const response = await (0, import_obsidian.requestUrl)({
url,
method: "POST",
headers,
body: JSON.stringify({
model,
messages: [{ role: "user", content: prompt }],
max_tokens: options?.maxTokens ?? 8192,
temperature: options?.temperature ?? 0.3,
stream: false
}),
throw: false
});
if (response.status >= 400) {
let errMsg = `Custom AI error (HTTP ${response.status})`;
try {
const errData = JSON.parse(response.text);
if (typeof errData?.error === "string") {
errMsg = errData.error;
} else if (errData?.error?.message) {
errMsg = errData.error.message;
}
} catch {
}
throw new Error(errMsg);
}
const data = JSON.parse(response.text);
const content = data?.choices?.[0]?.message?.content || data?.response || data?.content;
if (content == null)
throw new Error("Empty or invalid response from custom AI server");
return String(content).trim();
}
};
}
function createGroqProvider(apiKey, model) {
return {
async complete(prompt, options) {
if (!apiKey)
throw new Error("Groq API key not set. Add it in CourseForge settings.");
const modelId = model || "llama-3.3-70b-versatile";
const response = await (0, import_obsidian.requestUrl)({
url: "https://api.groq.com/openai/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify({
model: modelId,
messages: [{ role: "user", content: prompt }],
max_tokens: options?.maxTokens ?? 8192,
temperature: options?.temperature ?? 0.3
}),
throw: false
});
if (response.status >= 400) {
let errMsg = `Groq API error (HTTP ${response.status})`;
try {
const errData = JSON.parse(response.text);
if (errData?.error?.message) {
errMsg = errData.error.message;
if (errMsg.toLowerCase().includes("rate limit")) {
errMsg = "Groq rate limit reached. Wait a moment and try again (free tier: ~30 requests/min).";
} else if (errMsg.toLowerCase().includes("invalid api key")) {
errMsg = "Invalid Groq API key. Get one at console.groq.com";
}
}
} catch {
}
throw new Error(errMsg);
}
const data = JSON.parse(response.text);
const content = data?.choices?.[0]?.message?.content;
if (content == null)
throw new Error("Empty or invalid response from Groq");
return content.trim();
}
};
}
function createHuggingFaceProvider(apiKey, model) {
return {
async complete(prompt, options) {
if (!apiKey)
throw new Error("Hugging Face API key not set. Add it in CourseForge settings.");
const response = await (0, import_obsidian.requestUrl)({
url: `https://api-inference.huggingface.co/models/${model || "Qwen/Qwen2.5-7B-Instruct"}`,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify({
inputs: prompt,
parameters: {
max_new_tokens: options?.maxTokens ?? 4096,
temperature: options?.temperature ?? 0.3,
return_full_text: false
}
}),
throw: false
});
if (response.status >= 400) {
let errMsg = `Hugging Face API error (HTTP ${response.status})`;
try {
const errData = JSON.parse(response.text);
if (errData?.error)
errMsg = errData.error;
} catch {
}
throw new Error(errMsg);
}
const data = JSON.parse(response.text);
const generated = Array.isArray(data) ? data[0] : data;
const text = generated?.generated_text ?? "";
if (!text)
throw new Error("Empty or invalid response from Hugging Face");
return String(text).trim();
}
};
}
function getProvider(provider, apiKey, model, endpoint) {
switch (provider) {
case "openai":
return createOpenAIProvider(apiKey, model);
case "gemini":
return createGeminiProvider(apiKey, model);
case "groq":
return createGroqProvider(apiKey, model);
case "huggingface":
return createHuggingFaceProvider(apiKey, model);
case "custom":
return createCustomProvider(endpoint || "", apiKey, model);
default:
throw new Error(`Unknown provider: ${provider}`);
}
}
// src/settingsTab.ts
var CourseForgeSettingTab = class extends import_obsidian2.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.hasUnsavedChanges = false;
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.addClass("courseforge-settings");
const header = containerEl.createDiv({ cls: "courseforge-settings-header" });
header.createEl("h2", { text: "CourseForge Settings" });
header.createEl("p", { text: "Configure your AI provider for course generation.", cls: "setting-item-description" });
this.renderProviderSelector(containerEl);
this.renderActiveProviderConfig(containerEl);
this.renderSaveButton(containerEl);
this.renderOtherSettings(containerEl);
}
renderProviderSelector(containerEl) {
const section = containerEl.createDiv({ cls: "courseforge-provider-section" });
section.createEl("h3", { text: "AI Provider" });
const grid = section.createDiv({ cls: "courseforge-provider-grid" });
const providers = Object.keys(PROVIDER_OPTIONS);
for (const id of providers) {
const isActive = this.plugin.settings.provider === id;
const config = this.plugin.settings.providers[id];
const hasKey = !!(config?.apiKey || id === "custom" && config?.endpoint);
const info = PROVIDER_INFO[id];
const card = grid.createDiv({
cls: `courseforge-provider-card ${isActive ? "active" : ""} ${hasKey ? "configured" : ""}`
});
const cardHeader = card.createDiv({ cls: "courseforge-provider-card-header" });
cardHeader.createEl("span", { text: PROVIDER_OPTIONS[id], cls: "courseforge-provider-name" });
if (hasKey) {
cardHeader.createEl("span", { text: "\u2713", cls: "courseforge-provider-check" });
}
card.createEl("p", { text: info.description, cls: "courseforge-provider-desc" });
if (isActive) {
card.createEl("span", { text: "Active", cls: "courseforge-provider-badge" });
}
card.onclick = () => {
this.plugin.settings.provider = id;
this.hasUnsavedChanges = true;
this.display();
};
}
}
renderActiveProviderConfig(containerEl) {
const provider = this.plugin.settings.provider;
const config = this.plugin.settings.providers[provider];
const info = PROVIDER_INFO[provider];
const models = PROVIDER_MODELS[provider];
const section = containerEl.createDiv({ cls: "courseforge-config-section" });
section.createEl("h3", { text: `${PROVIDER_OPTIONS[provider]} Configuration` });
if (provider === "custom") {
new import_obsidian2.Setting(section).setName("Endpoint URL").setDesc("Your AI server's API endpoint (OpenAI-compatible)").addText((text) => {
text.setPlaceholder("http://localhost:11434/v1").setValue(config.endpoint || "").onChange((value) => {
this.plugin.settings.providers[provider].endpoint = value;
this.hasUnsavedChanges = true;
});
text.inputEl.style.width = "300px";
});
new import_obsidian2.Setting(section).setName("Model Name").setDesc("The model to use (e.g., llama3, mistral, codellama)").addText((text) => {
text.setPlaceholder("llama3").setValue(config.customModel || "").onChange((value) => {
this.plugin.settings.providers[provider].customModel = value;
this.hasUnsavedChanges = true;
});
text.inputEl.style.width = "200px";
});
}
const keyDesc = info.keyUrl ? `Get your API key from ${info.keyUrl}` : "API key (optional for local servers)";
const keySetting = new import_obsidian2.Setting(section).setName("API Key").setDesc(keyDesc);
if (info.keyUrl) {
keySetting.descEl.createEl("a", {
text: "Get API Key \u2192",
href: info.keyUrl,
cls: "courseforge-key-link"
});
}
keySetting.addText((text) => {
text.setPlaceholder(info.keyPlaceholder).setValue(config.apiKey || "").onChange((value) => {
this.plugin.settings.providers[provider].apiKey = value;
this.hasUnsavedChanges = true;
});
text.inputEl.type = "password";
text.inputEl.style.width = "280px";
});
keySetting.addButton((btn) => {
btn.setButtonText("Show").onClick(() => {
const input = keySetting.controlEl.querySelector("input");
if (input) {
const isPassword = input.type === "password";
input.type = isPassword ? "text" : "password";
btn.setButtonText(isPassword ? "Hide" : "Show");
}
});
});
if (provider !== "custom" && models.length > 0) {
new import_obsidian2.Setting(section).setName("Model").setDesc("Select the model to use").addDropdown((dropdown) => {
models.forEach((m) => dropdown.addOption(m.id, m.label));
dropdown.setValue(config.model || models[0].id);
dropdown.onChange((value) => {
this.plugin.settings.providers[provider].model = value;
this.hasUnsavedChanges = true;
});
});
}
new import_obsidian2.Setting(section).setName("Test Connection").setDesc("Verify your configuration works").addButton((btn) => {
btn.setButtonText("Test").onClick(async () => {
btn.setButtonText("Testing...");
btn.setDisabled(true);
try {
const apiKey = this.plugin.settings.providers[provider].apiKey;
const model = provider === "custom" ? this.plugin.settings.providers[provider].customModel || "" : this.plugin.settings.providers[provider].model;
const endpoint = this.plugin.settings.providers[provider].endpoint;
const llm = getProvider(provider, apiKey, model, endpoint);
const response = await llm.complete("Say 'Connection successful!' and nothing else.", { maxTokens: 50 });
if (response) {
new import_obsidian2.Notice(`\u2713 ${PROVIDER_OPTIONS[provider]}: Connection successful!`);
}
} catch (e) {
new import_obsidian2.Notice(`\u2717 ${PROVIDER_OPTIONS[provider]}: ${e.message}`, 8e3);
} finally {
btn.setButtonText("Test");
btn.setDisabled(false);
}
});
});
}
renderSaveButton(containerEl) {
const saveSection = containerEl.createDiv({ cls: "courseforge-save-section" });
const saveBtn = saveSection.createEl("button", {
text: "Save Settings",
cls: "courseforge-save-btn mod-cta"
});
const statusEl = saveSection.createEl("span", { cls: "courseforge-save-status" });
saveBtn.onclick = async () => {
await this.plugin.saveSettings();
this.hasUnsavedChanges = false;
statusEl.textContent = "\u2713 Saved!";
statusEl.addClass("success");
new import_obsidian2.Notice("Settings saved!");
setTimeout(() => {
statusEl.textContent = "";
statusEl.removeClass("success");
}, 2e3);
};
}
renderOtherSettings(containerEl) {
const section = containerEl.createDiv({ cls: "courseforge-other-section" });
section.createEl("h3", { text: "Other Settings" });
new import_obsidian2.Setting(section).setName("Default Course Folder").setDesc("Where new courses will be created in your vault").addText(
(text) => text.setPlaceholder("Courses").setValue(this.plugin.settings.courseFolder).onChange((value) => {
this.plugin.settings.courseFolder = value;
this.hasUnsavedChanges = true;
})
);
}
};
// src/commands/createCourse.ts
var import_obsidian4 = require("obsidian");
// src/ingest/fetcher.ts
var import_obsidian3 = require("obsidian");
var USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
async function fetchUrl(url) {
let origin = "";
try {
const u = new URL(url);
origin = u.origin;
} catch {
}
const response = await (0, import_obsidian3.requestUrl)({
url,
method: "GET",
headers: {
"User-Agent": USER_AGENT,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
...origin ? { "Referer": origin + "/" } : {}
},
throw: true
});
return response.text;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// src/ingest/parser.ts
var TAG_RE = /<[^>]+>/g;
var TITLE_RE = /<title[^>]*>([\s\S]*?)<\/title>/i;
var H1_RE = /<h1[^>]*>([\s\S]*?)<\/h1>/i;
function stripTags(html) {
return html.replace(TAG_RE, " ").replace(/\s+/g, " ").trim();
}
function extractTitleFromHtml(html) {
const titleMatch = html.match(TITLE_RE);
if (titleMatch)
return stripTags(titleMatch[1]).trim();
const h1Match = html.match(H1_RE);
if (h1Match)
return stripTags(h1Match[1]).trim();
return "Untitled";
}
function parseHtml(html) {
const title = extractTitleFromHtml(html);
const text = stripTags(html);
return { title, text };
}
function parseMarkdown(md) {
const firstLine = md.trim().split("\n")[0] || "";
const headingMatch = firstLine.match(/^#+\s+(.+)$/);
const title = headingMatch ? headingMatch[1].trim() : "Untitled";
return { title, text: md.trim() };
}
function parseContent(raw, isHtml = true) {
return isHtml ? parseHtml(raw) : parseMarkdown(raw);
}
// src/ingest/hash.ts
function contentHash(text) {
let h = 5381;
for (let i = 0; i < text.length; i++) {
h = (h << 5) + h + text.charCodeAt(i);
}
return Math.abs(h).toString(36);
}
// src/chunking/chunker.ts
var MAX_CHARS = 1200;
var MD_HEADING = /^(#{1,6})\s+(.+)$/gm;
var HTML_HEADING = /<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi;
function extractSectionsByMarkdownHeadings(text) {
const matches = [];
let match;
const re = new RegExp(MD_HEADING.source, "gm");
while ((match = re.exec(text)) !== null) {
matches.push({
level: match[1].length,
title: match[2].trim(),
start: match.index
});
}
const result = matches.map((m, i) => ({
...m,
end: i + 1 < matches.length ? matches[i + 1].start : text.length
}));
if (result.length === 0) {
result.push({ level: 0, title: "Content", start: 0, end: text.length });
}
return result;
}
function extractSectionsByHtmlHeadings(text) {
const matches = [];
let match;
const re = new RegExp(HTML_HEADING.source, "gi");
while ((match = re.exec(text)) !== null) {
matches.push({
level: parseInt(match[1], 10),
title: match[2].replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(),
start: match.index
});
}
const result = matches.map((m, i) => ({
...m,
end: i + 1 < matches.length ? matches[i + 1].start : text.length
}));
if (result.length === 0) {
result.push({ level: 0, title: "Content", start: 0, end: text.length });
}
return result;
}
function buildHeadingPath(sections, index) {
const stack = [];
for (let i = 0; i <= index; i++) {
const s = sections[i];
while (stack.length > 0 && stack[stack.length - 1].level >= s.level)
stack.pop();
stack.push(s);
}
return stack.map((s) => s.title).join(" > ");
}
function chunkText(text, sourceId) {
const hasMarkdownHeadings = /^#{1,6}\s+/m.test(text);
const sections = hasMarkdownHeadings ? extractSectionsByMarkdownHeadings(text) : extractSectionsByHtmlHeadings(text);
const chunks = [];
const sectionTexts = [];
for (let i = 0; i < sections.length; i++) {
const s = sections[i];
const nextStart = s.end;
const segment = text.slice(s.start, nextStart).trim();
if (!segment)
continue;
const path = buildHeadingPath(
sections.map((x) => ({ level: x.level, title: x.title })),
i
);
sectionTexts.push({ path, text: segment, start: s.start, end: nextStart });
}
if (sectionTexts.length === 0) {
const seg = text.trim();
if (seg) {
sectionTexts.push({ path: "Content", text: seg, start: 0, end: text.length });
}
}
for (let i = 0; i < sectionTexts.length; i++) {
const { path, text: segment, start, end } = sectionTexts[i];
if (segment.length <= MAX_CHARS) {
chunks.push({
chunkId: `${sourceId}_${i}`,
sourceId,
headingPath: path,
text: segment,
startIdx: start,
endIdx: end,
tokensApprox: Math.ceil(segment.length / 4)
});
} else {
let offset = 0;
let subIndex = 0;
while (offset < segment.length) {
const sliceEnd = Math.min(offset + MAX_CHARS, segment.length);
let slice = segment.slice(offset, sliceEnd);
const lastSpace = slice.lastIndexOf(" ");
if (sliceEnd < segment.length && lastSpace > MAX_CHARS / 2) {
slice = segment.slice(offset, offset + lastSpace + 1);
offset += lastSpace + 1;
} else {
offset = sliceEnd;
}
const sliceStartIdx = start + (offset - slice.length);
const sliceEndIdx = start + offset;
chunks.push({
chunkId: `${sourceId}_${i}_${subIndex}`,
sourceId,
headingPath: path,
text: slice,
startIdx: sliceStartIdx,
endIdx: sliceEndIdx,
tokensApprox: Math.ceil(slice.length / 4)
});
subIndex++;
}
}
}
return chunks;
}
// src/ingest/linkDiscovery.ts
var HREF_RE = /<a[^>]+href\s*=\s*["']([^"']+)["']/gi;
var SKIP_PATHS = /\/?(login|signin|signout|logout|register|signup|search|cart|checkout|account|profile|settings|privacy|terms|javascript|#)/i;
var SKIP_EXT = /\.(pdf|zip|exe|dmg|png|jpg|jpeg|gif|svg|css|js)(\?|$)/i;
var MAX_LINKS = 60;
function resolveUrl(href, baseUrl) {
try {
const u = new URL(href.trim(), baseUrl);
if (u.protocol !== "http:" && u.protocol !== "https:")
return null;
u.hash = "";
return u.href;
} catch {
return null;
}
}
function extractLinksFromHtml(html, baseUrl) {
const base = new URL(baseUrl);
const seen = /* @__PURE__ */ new Set();
const out = [];
let m;
HREF_RE.lastIndex = 0;
while ((m = HREF_RE.exec(html)) !== null) {
const href = m[1].trim();
if (!href || href.startsWith("#") || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:") || href.startsWith("data:"))
continue;
const absolute = resolveUrl(href, baseUrl);
if (!absolute)
continue;
try {
const u = new URL(absolute);
if (u.hostname !== base.hostname)
continue;
if (SKIP_PATHS.test(u.pathname) || SKIP_EXT.test(u.pathname))
continue;
} catch {
continue;
}
const key = absolute.split("?")[0];
if (seen.has(key))
continue;
seen.add(key);
out.push(absolute);
if (out.length >= MAX_LINKS)
break;
}
return out;
}
var CONTENT_PATH = /\/?(learn|modules|training|certifications|docs|courses|en-us|content)/i;
function scoreUrl(url) {
try {
const u = new URL(url);
return CONTENT_PATH.test(u.pathname) ? 1 : 0;
} catch {
return 0;
}
}
function discoverCourseUrls(seedUrl, html) {
const links = extractLinksFromHtml(html, seedUrl);
const seed = new URL(seedUrl);
seed.hash = "";
const seedKey = seed.href.split("?")[0];
const seen = /* @__PURE__ */ new Set([seedKey]);
const candidates = [];
for (const url of links) {
const key = url.split("?")[0];
if (seen.has(key))
continue;
seen.add(key);
candidates.push(url);
}
candidates.sort((a, b) => scoreUrl(b) - scoreUrl(a));
const result = [seedUrl];
for (const url of candidates) {
result.push(url);
if (result.length >= MAX_LINKS)
break;
}
return result;
}
// src/state/courseRegistry.ts
var REGISTRY_DIR = ".courseforge";
var REGISTRY_FILE = ".courseforge/courses.json";
function joinPath(...parts) {
return parts.filter(Boolean).join("/").replace(/\/+$/g, "").replace(/\/+/g, "/");
}
async function listCourses(vault) {
let raw;
try {
raw = await vault.adapter.read(REGISTRY_FILE);
} catch {
return [];
}
let data;
try {
data = JSON.parse(raw);
} catch {
return [];
}
const entries = data.courses ?? [];
const valid = [];
for (const e of entries) {
const sourcesPath = joinPath(e.path, "Sources", "sources.json");
const exists = await vault.adapter.exists(sourcesPath).catch(() => false);
if (exists)
valid.push(e);
}
return valid;
}
async function registerCourse(vault, courseRoot, title) {
const normalizedPath = courseRoot.replace(/\/+$/, "");
let data = { courses: [] };
try {
const raw = await vault.adapter.read(REGISTRY_FILE);
data = JSON.parse(raw);
if (!Array.isArray(data.courses))
data.courses = [];
} catch {
data = { courses: [] };
}
const existing = data.courses.findIndex((c) => c.path === normalizedPath);
const entry = { path: normalizedPath, title: title || "Course" };
if (existing >= 0) {
data.courses[existing] = entry;
} else {
data.courses.push(entry);
}
await vault.adapter.mkdir(REGISTRY_DIR).catch(() => {
});
await vault.adapter.write(REGISTRY_FILE, JSON.stringify(data, null, 2));
}
// src/commands/createCourse.ts
var DEFAULT_DASHBOARD = `---
course:
---
# Dashboard
- [ ] Complete syllabus
- [ ] Track lesson completion below
`;
var DEFAULT_SYLLABUS = `# Syllabus
Modules will appear here after generation.
`;
var LESSON_TEMPLATE = `# {{title}}
## Overview
## Key points
## Summary
Citations:
`;
var ACTIVITY_TEMPLATE = `# {{title}} - Activities
## Activity 1
## Activity 2
## Activity 3
Citations:
`;
var QUIZ_TEMPLATE = `# Quiz - {{title}}
## Questions
1.
2.
## Answer key
1.
2.
## Explanations
(Cite chunks where needed)
`;
function joinPath2(...parts) {
return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
}
var INVALID_PATH_CHARS = /[*"\\/:<>|?]/g;
function sanitizePathSegment(segment) {
const s = (segment ?? "").trim().replace(INVALID_PATH_CHARS, " ").replace(/\s+/g, " ").trim();
return s.slice(0, 120) || "Untitled";
}
function sanitizeCourseRoot(input) {
const trimmed = (input ?? "").trim();
if (!trimmed)
return "CourseForge/Untitled";
const segments = trimmed.split(/[/\\]+/).map(sanitizePathSegment).filter(Boolean);
if (segments.length === 0)
return "CourseForge/Untitled";
const base = segments[0] === "CourseForge" ? segments : ["CourseForge", ...segments];
return base.join("/");
}
function sourceIdFromUrl(url, index) {
try {
const u = new URL(url);
const host = u.hostname.replace(/\./g, "_");
const path = u.pathname.replace(/\//g, "_").replace(/^_|_$/g, "") || "page";
return `src_${host}_${path}_${index}`.slice(0, 80);
} catch {
return `src_${index}`;
}
}
function normalizeUrlForKey(url) {
try {
const u = new URL(url);
u.hash = "";
u.search = "";
let p = u.pathname.replace(/\/+$/, "") || "/";
return u.origin + p;
} catch {
return url;
}
}
async function addSourcesToCourse(app, courseRoot, urls, options) {
const vault = app.vault;
const normalizedRoot = sanitizeCourseRoot(courseRoot).replace(/\/+$/, "");
const sourcesPath = joinPath2(normalizedRoot, "Sources");
const sourcesJsonPath = joinPath2(sourcesPath, "sources.json");
let raw;
try {
raw = await vault.adapter.read(sourcesJsonPath);
} catch {
throw new Error("Course not found. Run 'Create course from URLs' first.");
}
const sourcesData = JSON.parse(raw);
const preloaded = options?.preloadedHtml ?? {};
const errors = [];
const newSourcesWithText = [];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
const key = normalizeUrlForKey(url);
const cached = preloaded[key] ?? preloaded[url];
try {
if (i > 0)
await delay(1e3);
const html = cached ?? await fetchUrl(url);
const { title, text } = parseContent(html, true);
const hash = contentHash(text);
const id = sourceIdFromUrl(url, sourcesData.sources.length + newSourcesWithText.length);
sourcesData.sources.push({
id,
url,
fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
title,
contentHash: hash
});
newSourcesWithText.push({ id, text });
} catch (e) {
errors.push(`${url}: ${e.message}`);
}
}
await vault.adapter.write(sourcesJsonPath, JSON.stringify(sourcesData, null, 2));
const chunksPath = joinPath2(sourcesPath, "chunks.jsonl");