forked from joshuahamsa/Obsidian-Biblehub-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
939 lines (927 loc) · 34.4 KB
/
main.js
File metadata and controls
939 lines (927 loc) · 34.4 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toModule = (module2) => {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
// src/main.ts
__export(exports, {
default: () => BibleHubLexiconImporter
});
var import_obsidian6 = __toModule(require("obsidian"));
// src/settings.ts
var import_obsidian = __toModule(require("obsidian"));
var DEFAULT_RECIPE = {
id: "word-study-web:v1",
includeSections: [
"lexical_summary",
"strongs_definition",
"helps",
"thayers",
"forms_transliterations",
"englishmans_concordance",
"topical_lexicon"
],
followEdges: ["see_also", "related_strongs"],
linkTypes: ["strongs", "scripture"],
linkGreekHebrew: true,
lemmaAliasMode: "primary",
maxDepth: 2,
maxNodes: 100,
rateLimitMs: 1e3,
skipExisting: true,
rootFolder: "Lexicon/Strongs",
scriptureRootFolder: "Scripture",
noteTitlePattern: "{{strong}} \u2014 {{lemma}} ({{transliteration}})"
};
var DEFAULT_SETTINGS = {
recipe: DEFAULT_RECIPE
};
var SettingsTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
new import_obsidian.Setting(containerEl).setName("Root folder").setDesc("Where Strong's notes are created/updated.").addText((t) => t.setValue(this.plugin.settings.recipe.rootFolder).onChange(async (v) => {
this.plugin.settings.recipe.rootFolder = v.trim() || "Lexicon/Strongs";
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Scripture folder").setDesc("Where scripture notes are created/updated.").addText((t) => t.setValue(this.plugin.settings.recipe.scriptureRootFolder).onChange(async (v) => {
this.plugin.settings.recipe.scriptureRootFolder = v.trim() || "Scripture";
await this.plugin.saveSettings();
}));
const sectionLabels = {
lexical_summary: "Lexical Summary",
strongs_definition: "Strong's Definition",
helps: "HELPS Word-studies",
thayers: "Thayer's Lexicon",
forms_transliterations: "Forms & Transliterations",
englishmans_concordance: "Englishman's Concordance",
concordance: "Concordance",
topical_lexicon: "Topical Lexicon"
};
const linkLabels = {
strongs: "Strong's number links",
scripture: "Scripture reference links"
};
new import_obsidian.Setting(containerEl).setName("Include sections").setDesc("Choose which sections to include in generated notes.");
for (const key of Object.keys(sectionLabels)) {
new import_obsidian.Setting(containerEl).setName(sectionLabels[key]).addToggle((tg) => tg.setValue(this.plugin.settings.recipe.includeSections.includes(key)).onChange(async (v) => {
const set = new Set(this.plugin.settings.recipe.includeSections);
v ? set.add(key) : set.delete(key);
this.plugin.settings.recipe.includeSections = Array.from(set);
await this.plugin.saveSettings();
}));
}
new import_obsidian.Setting(containerEl).setName("Link types").setDesc("Choose which link types to generate.");
for (const key of Object.keys(linkLabels)) {
new import_obsidian.Setting(containerEl).setName(linkLabels[key]).addToggle((tg) => tg.setValue(this.plugin.settings.recipe.linkTypes.includes(key)).onChange(async (v) => {
const set = new Set(this.plugin.settings.recipe.linkTypes);
v ? set.add(key) : set.delete(key);
this.plugin.settings.recipe.linkTypes = Array.from(set);
await this.plugin.saveSettings();
}));
}
new import_obsidian.Setting(containerEl).setName("Auto-link Greek/Hebrew terms").setDesc("Link Greek/Hebrew tokens to Strong's notes (creates placeholders if missing). Turn off Skip existing if you want alias updates.").addToggle((tg) => tg.setValue(this.plugin.settings.recipe.linkGreekHebrew).onChange(async (v) => {
this.plugin.settings.recipe.linkGreekHebrew = v;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Lemma aliases").setDesc("Choose alias behavior for lemmas when auto-linking.").addDropdown((dd) => dd.addOption("primary", "Primary lemma only").addOption("all", "All lemmas found in note").setValue(this.plugin.settings.recipe.lemmaAliasMode).onChange(async (v) => {
this.plugin.settings.recipe.lemmaAliasMode = v;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Max depth").setDesc("Crawl depth for typed edges (BFS).").addSlider((s) => s.setLimits(0, 5, 1).setValue(this.plugin.settings.recipe.maxDepth).setDynamicTooltip().onChange(async (v) => {
this.plugin.settings.recipe.maxDepth = v;
await this.plugin.saveSettings();
}));
new import_obsidian.Setting(containerEl).setName("Max nodes").setDesc("Maximum nodes created/updated in a single run.").addText((t) => t.setValue(String(this.plugin.settings.recipe.maxNodes)).onChange(async (v) => {
const n = parseInt(v, 10);
if (!Number.isNaN(n)) {
this.plugin.settings.recipe.maxNodes = Math.max(1, n);
await this.plugin.saveSettings();
}
}));
new import_obsidian.Setting(containerEl).setName("Rate limit (ms)").setDesc("Delay between requests to be polite to BibleHub.").addText((t) => t.setValue(String(this.plugin.settings.recipe.rateLimitMs)).onChange(async (v) => {
const n = parseInt(v, 10);
if (!Number.isNaN(n)) {
this.plugin.settings.recipe.rateLimitMs = Math.max(0, n);
await this.plugin.saveSettings();
}
}));
new import_obsidian.Setting(containerEl).setName("Skip existing notes").setDesc("If ON, existing Strong's notes will not be refetched/rewritten (only linked).").addToggle((tg) => tg.setValue(this.plugin.settings.recipe.skipExisting).onChange(async (v) => {
this.plugin.settings.recipe.skipExisting = v;
await this.plugin.saveSettings();
}));
}
};
// src/normalize.ts
function normalizeStrongId(raw, langHint) {
const s = raw.trim();
const m1 = s.match(/\b([GH])\s*0*([0-9]{1,5})\b/i);
if (m1)
return m1[1].toUpperCase() + String(parseInt(m1[2], 10));
const m2 = s.match(/\b0*([0-9]{1,5})\b/);
if (m2 && langHint) {
const prefix = langHint === "greek" ? "G" : "H";
return prefix + String(parseInt(m2[1], 10));
}
return null;
}
function langFromStrong(strong) {
return strong.toUpperCase().startsWith("G") ? "greek" : "hebrew";
}
function strongsUrl(strong) {
const lang = langFromStrong(strong);
const n = strong.slice(1);
return `https://biblehub.com/strongs/${lang}/${n}.htm`;
}
function safeFileName(name) {
return name.replace(/[\\/:*?"<>|]/g, "\u2014").replace(/\s+/g, " ").trim();
}
// src/fetcher.ts
var import_obsidian2 = __toModule(require("obsidian"));
var Fetcher = class {
constructor(rateLimitMs) {
this.rateLimitMs = rateLimitMs;
this.lastFetchAt = 0;
this.cache = new Map();
}
setRateLimit(ms) {
this.rateLimitMs = ms;
}
async get(url, useCache = true) {
if (useCache) {
const hit = this.cache.get(url);
if (hit)
return hit.text;
}
await this.rateLimit();
const res = await (0, import_obsidian2.requestUrl)({ url });
const text = res.text;
this.cache.set(url, { at: Date.now(), text });
return text;
}
async rateLimit() {
const now = Date.now();
const delta = now - this.lastFetchAt;
if (delta < this.rateLimitMs) {
await new Promise((r) => setTimeout(r, this.rateLimitMs - delta));
}
this.lastFetchAt = Date.now();
}
};
// src/writer.ts
var import_obsidian3 = __toModule(require("obsidian"));
var Writer = class {
constructor(vault) {
this.vault = vault;
}
buildTitle(entry, recipe) {
const fill = (s) => {
var _a, _b;
return s.replaceAll("{{strong}}", entry.strong).replaceAll("{{lemma}}", (_a = entry.lemma) != null ? _a : "").replaceAll("{{transliteration}}", (_b = entry.transliteration) != null ? _b : "").replaceAll("{{short_definition}}", "");
};
return safeFileName(fill(recipe.noteTitlePattern)).trim();
}
filePath(title, recipe) {
const folder = recipe.rootFolder.replace(/^\/+|\/+$/g, "");
return (0, import_obsidian3.normalizePath)(`${folder}/${title}.md`);
}
async ensureFolder(recipe) {
const folder = (0, import_obsidian3.normalizePath)(recipe.rootFolder.replace(/^\/+|\/+$/g, ""));
if (!await this.vault.adapter.exists(folder)) {
await this.vault.createFolder(folder);
}
}
async upsert(entry, recipe, renameOnUpdate) {
await this.ensureFolder(recipe);
const title = this.buildTitle(entry, recipe);
const path = this.filePath(title, recipe);
const existing = this.vault.getAbstractFileByPath(path);
if (existing instanceof import_obsidian3.TFile) {
const updated = await this.mergeIntoFile(existing, entry, recipe);
if (renameOnUpdate) {
}
return { file: existing, created: false };
}
const content = this.renderNew(entry, recipe);
const file = await this.vault.create(path, content);
return { file, created: true };
}
renderNew(entry, recipe) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
const now = new Date().toISOString().slice(0, 10);
const links_see_also = entry.links.see_also.map((id) => `[[${id}]]`);
const links_related = entry.links.related_strongs.map((id) => `[[${id}]]`);
const links_topical = entry.links.topical.map((id) => `[[${id}]]`);
const links_scripture = entry.links.scripture.map((r) => `[[${r.display}]]`);
const yaml = [
"---",
`type: lexicon/strongs`,
`lang: ${entry.lang}`,
`strong: ${entry.strong}`,
"",
`lemma: ${(_a = entry.lemma) != null ? _a : ""}`,
`transliteration: ${(_b = entry.transliteration) != null ? _b : ""}`,
`pronunciation: ${(_c = entry.pronunciation) != null ? _c : ""}`,
`phonetic: ${(_d = entry.phonetic) != null ? _d : ""}`,
`part_of_speech: ${(_e = entry.part_of_speech) != null ? _e : ""}`,
"",
`aliases:`,
` - ${entry.strong}`,
...entry.transliteration ? [` - ${entry.transliteration}`] : [],
"",
`source_primary: ${entry.source_primary}`,
`source_alt:`,
...entry.source_alt.map((u) => ` - ${u}`),
"",
`imported_at: ${now}`,
`import_recipe: ${recipe.id}`,
"",
`sections_included:`,
...recipe.includeSections.map((s) => ` - ${s}`),
"",
`links_see_also:`,
...links_see_also.map((l) => ` - "${l}"`),
`links_related_strongs:`,
...links_related.map((l) => ` - "${l}"`),
`links_topical:`,
...links_topical.map((l) => ` - "${l}"`),
`links_scripture:`,
...links_scripture.map((l) => ` - "${l}"`),
"",
`crawl_depth: ${recipe.maxDepth}`,
`crawl_root: ${entry.strong}`,
"---",
""
].join("\n");
const titleLine = `# ${entry.strong} \u2014 ${(_f = entry.lemma) != null ? _f : ""} (${(_g = entry.transliteration) != null ? _g : ""})`.trim();
const blocks = { ...entry.blocks };
if (recipe.linkTypes.includes("scripture") && links_scripture.length) {
for (const key of Object.keys(blocks)) {
if (blocks[key])
blocks[key] = linkifyScriptureRefs(blocks[key], entry.links.scripture);
}
}
const sectionTitles = {
lexical_summary: "Lexical Summary",
strongs_definition: "Strong's Definition",
helps: "HELPS Word-studies",
thayers: "Thayer's Lexicon",
forms_transliterations: "Forms & Transliterations",
englishmans_concordance: "Englishman's Concordance",
concordance: "Concordance",
topical_lexicon: "Topical Lexicon"
};
const sectionOrder = [
"lexical_summary",
"strongs_definition",
"helps",
"thayers",
"forms_transliterations",
"englishmans_concordance",
"concordance",
"topical_lexicon"
];
const sections = sectionOrder.filter((k) => recipe.includeSections.includes(k)).flatMap((k) => renderSection(sectionTitles[k], k, blocks[k]));
const body = [
titleLine,
"",
`> **Part of Speech:** ${(_h = entry.part_of_speech) != null ? _h : ""} `,
`> **Pronunciation:** ${(_i = entry.pronunciation) != null ? _i : ""} `,
`> **Primary source:** ${entry.source_primary}`,
"",
"---",
"",
...sections,
"",
"---",
"",
"## Outbound Links",
"",
"**See also (direct Strong's cross-refs):** ",
links_see_also.join(", "),
"",
"**Related Strong's (lexical / semantic):** ",
links_related.join(", "),
"",
"**Topical connections:** ",
links_topical.join(", "),
"",
"**Scripture references:** ",
recipe.linkTypes.includes("scripture") ? links_scripture.join(", ") : "",
""
].join("\n");
return yaml + body;
}
async mergeIntoFile(file, entry, recipe) {
var _a;
const original = await this.vault.read(file);
let text = original;
for (const section of recipe.includeSections) {
const replacement = (_a = entry.blocks[section]) != null ? _a : "";
text = replaceImportedBlock(text, section, replacement);
}
await this.vault.modify(file, text);
}
};
function renderSection(title, key, content) {
const block = (content != null ? content : "").trim();
return [
`## ${title}`,
`<!-- imported: ${key} -->`,
block || "",
"",
"---",
""
];
}
function replaceImportedBlock(doc, key, replacement) {
const marker = `<!-- imported: ${key} -->`;
const idx = doc.indexOf(marker);
if (idx < 0)
return doc;
const afterMarker = idx + marker.length;
const rest = doc.slice(afterMarker);
const nextHeading = rest.search(/\n##\s+/);
const nextMarker = rest.indexOf("\n<!-- imported:");
let endRel = -1;
if (nextHeading >= 0 && nextMarker >= 0)
endRel = Math.min(nextHeading, nextMarker);
else if (nextHeading >= 0)
endRel = nextHeading;
else if (nextMarker >= 0)
endRel = nextMarker;
else
endRel = rest.length;
const end = afterMarker + endRel;
return doc.slice(0, afterMarker) + "\n" + (replacement.trim() ? replacement.trim() + "\n" : "\n") + doc.slice(end);
}
function linkifyScriptureRefs(text, refs) {
let out = text;
for (const r of refs) {
if (!r.display)
continue;
const escaped = r.display.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
out = out.replace(new RegExp(`\\b${escaped}\\b`, "g"), `[[${r.display}]]`);
}
return out;
}
// src/parser/common.ts
function htmlToText(html) {
return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<\/div>/gi, "\n").replace(/<[^>]+>/g, "").replace(/ /g, " ").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").replace(/\r/g, "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
}
function pickLabel(text, label) {
var _a;
const re = new RegExp(String.raw`${escapeRegExp(label)}\s*:\s*(.+)`, "i");
const m = text.match(re);
return (_a = m == null ? void 0 : m[1]) == null ? void 0 : _a.trim();
}
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// src/scripture.ts
var import_obsidian4 = __toModule(require("obsidian"));
function slugToBookName(slug) {
const words = slug.split("_").map((w) => w.charAt(0).toUpperCase() + w.slice(1));
return words.join(" ");
}
function makeScriptureRefFromSlug(slug, chapter, verse) {
const book = slugToBookName(slug);
const display = `${book} ${chapter}:${verse}`;
const interlinearUrl = `https://biblehub.com/interlinear/${slug}/${chapter}-${verse}.htm`;
const nasbUrl = `https://biblehub.com/nasb/${slug}/${chapter}-${verse}.htm`;
return { slug, chapter, verse, display, interlinearUrl, nasbUrl };
}
function scriptureNotePath(rootFolder, ref) {
const book = safeFileName(slugToBookName(ref.slug));
const folder = rootFolder.replace(/^\/+|\/+$/g, "");
return (0, import_obsidian4.normalizePath)(`${folder}/${book}/${ref.chapter}-${ref.verse}.md`);
}
function scriptureAliases(ref) {
const book = slugToBookName(ref.slug);
const full = `${book} ${ref.chapter}:${ref.verse}`;
const abbr = bookAbbrev(book);
const abbrSpaced = abbr ? `${abbr} ${ref.chapter}:${ref.verse}` : "";
const abbrCompact = abbr ? `${abbr.replace(/\s+/g, "")} ${ref.chapter}:${ref.verse}`.replace(/\s+/g, "") : "";
return Array.from(new Set([full, abbrSpaced, abbrCompact].filter(Boolean)));
}
function bookAbbrev(book) {
var _a;
const parts = book.split(" ");
if (parts.length === 1)
return parts[0].slice(0, 3);
if (/^\d+$/.test(parts[0])) {
const rest = (_a = parts[1]) != null ? _a : "";
return `${parts[0]} ${rest.slice(0, 3)}`.trim();
}
return parts[0].slice(0, 3);
}
async function ensureScriptureNote(vault, fetcher, rootFolder, ref, relatedStrongLinks) {
const path = scriptureNotePath(rootFolder, ref);
const existing = vault.getAbstractFileByPath(path);
if (existing)
return;
const folder = path.split("/").slice(0, -1).join("/");
if (!await vault.adapter.exists(folder)) {
await vault.createFolder(folder);
}
const html = await fetcher.get(ref.nasbUrl, true);
const text = extractNasbText(html) || "";
const aliases = scriptureAliases(ref).map((a) => ` - "${a}"`);
const yaml = [
"---",
"type: scripture/verse",
`reference: ${ref.display}`,
`book: ${slugToBookName(ref.slug)}`,
`chapter: ${ref.chapter}`,
`verse: ${ref.verse}`,
"aliases:",
...aliases,
`source_nasb: ${ref.nasbUrl}`,
`source_interlinear: ${ref.interlinearUrl}`,
"related_strongs:",
...relatedStrongLinks.map((l) => ` - "${l}"`),
"---",
""
].join("\n");
const body = [
`# ${ref.display}`,
"",
text.trim(),
""
].join("\n");
await vault.create(path, yaml + body);
}
function extractNasbText(html) {
const re = /NASB 1995<\/a><\/span><br \/>([\s\S]*?)(?:<span class="versiontext">|<span class="p">)/i;
const m = html.match(re);
if (!m)
return "";
return stripHtml(m[1]).replace(/\s+/g, " ").trim();
}
function stripHtml(s) {
return s.replace(/<br\s*\/>/gi, "\n").replace(/<[^>]+>/g, "").replace(/ /g, " ").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").replace(/</g, "<").replace(/>/g, ">").trim();
}
// src/parser/strongs.ts
function parseStrongsPage(strong, url, html) {
var _a, _b, _c;
const lang = langFromStrong(strong);
const text = htmlToText(html);
const lemma = pickLabel(text, "Original Word");
const transliteration = pickLabel(text, "Transliteration");
const phonetic = pickLabel(text, "Phonetic Spelling");
const pronunciation = pickLabel(text, "Pronunciation");
const part_of_speech = pickLabel(text, "Part of Speech");
const definition = pickLabel(text, "Definition");
const seeAlso = [];
const seeMatches = Array.from(text.matchAll(/\bSee\s+([0-9]{1,5})\b/g));
for (const m of seeMatches) {
const id = normalizeStrongId(m[1], lang);
if (id)
seeAlso.push(id);
}
const scripture = extractScriptureRefsFromHtml(html);
const blocks = {
lexical_summary: buildLexicalSummaryBlock({ lemma, transliteration, pronunciation, phonetic, part_of_speech, definition }),
strongs_definition: definition ? definition : "",
helps: extractSectionApprox(text, "HELPS Word-studies", 2e3),
thayers: extractSectionApprox(text, "Thayer's Greek Lexicon", 3e3),
forms_transliterations: extractSectionApprox(text, "Forms of", 1200) || extractSectionApprox(text, "Forms & Transliterations", 1200),
englishmans_concordance: extractSectionApprox(text, "Englishman's Concordance", 3e3),
concordance: extractSectionApprox(text, "Concordance", 2e3),
topical_lexicon: extractSectionApprox(text, "Topical Lexicon", 2e3)
};
for (const k of Object.keys(blocks)) {
if (!blocks[k])
blocks[k] = "";
}
const related = uniq([
...extractStrongRefs((_a = blocks.helps) != null ? _a : "", lang),
...extractStrongRefs((_b = blocks.thayers) != null ? _b : "", lang),
...extractStrongRefs((_c = blocks.strongs_definition) != null ? _c : "", lang)
]).filter((id) => id !== strong);
return {
strong,
lang,
lemma,
transliteration,
pronunciation,
phonetic,
part_of_speech,
source_primary: url,
source_alt: [],
blocks,
links: {
see_also: uniq(seeAlso),
related_strongs: related,
topical: [],
scripture
}
};
}
function extractStrongRefs(text, lang) {
if (!text)
return [];
const refs = [];
const matches = Array.from(text.matchAll(/\b(?:STRONGS?\s*(?:NT|OT)?\s*)?([0-9]{1,5})\b/gi));
for (const m of matches) {
const id = normalizeStrongId(m[1], lang);
if (id)
refs.push(id);
}
return refs;
}
function extractScriptureRefsFromHtml(html) {
const refs = [];
const re = /(?:https?:\/\/biblehub\.com)?\/interlinear\/([a-z0-9_]+)\/(\d+)-(\d+)\.htm/gi;
const seen = new Set();
let m;
while (m = re.exec(html)) {
const slug = m[1];
const chapter = parseInt(m[2], 10);
const verse = parseInt(m[3], 10);
const key = `${slug}:${chapter}:${verse}`;
if (seen.has(key))
continue;
seen.add(key);
refs.push(makeScriptureRefFromSlug(slug, chapter, verse));
}
return refs;
}
function uniq(arr) {
return Array.from(new Set(arr));
}
function buildLexicalSummaryBlock(fields) {
const lines = [];
for (const [k, v] of Object.entries(fields)) {
if (!v)
continue;
lines.push(`- **${human(k)}:** ${v}`);
}
return lines.join("\n");
}
function human(k) {
return k.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
function extractSectionApprox(text, header, maxChars) {
const idx = text.toLowerCase().indexOf(header.toLowerCase());
if (idx < 0)
return "";
const slice = text.slice(idx, idx + maxChars);
return slice.trim();
}
// src/parser/index.ts
function parseEntryFromStrongsPage(strong, url, html) {
return parseStrongsPage(strong, url, html);
}
// src/crawler.ts
var import_obsidian5 = __toModule(require("obsidian"));
var Crawler = class {
constructor(vault, fetcher, writer) {
this.vault = vault;
this.fetcher = fetcher;
this.writer = writer;
}
async run(rootStrong, recipe, renameOnUpdate) {
var _a;
this.fetcher.setRateLimit(recipe.rateLimitMs);
const res = { created: 0, updated: 0, skipped: 0, errors: [] };
const lemmaIndex = await this.buildLemmaIndex(recipe.rootFolder);
const seen = new Set();
const q = [{ strong: rootStrong, depth: 0 }];
let processed = 0;
while (q.length > 0 && processed < recipe.maxNodes) {
const { strong, depth } = q.shift();
if (seen.has(strong))
continue;
seen.add(strong);
const exists = this.findExistingByStrongIdFallback(strong, recipe);
if (exists && recipe.skipExisting) {
res.skipped++;
processed++;
continue;
}
try {
const url = strongsUrl(strong);
const html = await this.fetcher.get(url, true);
let entry = parseEntryFromStrongsPage(strong, url, html);
if (entry.lemma)
lemmaIndex.set(entry.lemma, entry.strong);
if (recipe.linkGreekHebrew) {
entry = await this.applyLemmaLinks(entry, lemmaIndex, recipe);
}
const up = await this.writer.upsert(entry, recipe, renameOnUpdate);
if (up.created)
res.created++;
else
res.updated++;
if (recipe.linkTypes.includes("scripture") && entry.links.scripture.length) {
const related = Array.from(new Set([entry.strong, ...entry.links.related_strongs])).map((id) => `[[${id}]]`);
for (const ref of entry.links.scripture) {
await ensureScriptureNote(this.vault, this.fetcher, recipe.scriptureRootFolder, ref, related);
}
}
if (depth < recipe.maxDepth) {
for (const next of this.nextNodes(entry, recipe.followEdges)) {
if (!seen.has(next))
q.push({ strong: next, depth: depth + 1 });
}
}
} catch (e) {
res.errors.push({ id: strong, error: (_a = e == null ? void 0 : e.message) != null ? _a : String(e) });
}
processed++;
}
return res;
}
nextNodes(entry, edgeTypes) {
const out = [];
for (const et of edgeTypes) {
if (et === "see_also")
out.push(...entry.links.see_also);
if (et === "related_strongs")
out.push(...entry.links.related_strongs);
if (et === "topical")
out.push(...entry.links.topical);
}
return Array.from(new Set(out));
}
async buildLemmaIndex(rootFolder) {
const folder = rootFolder.replace(/^\/+|\/+$/g, "");
const files = this.vault.getMarkdownFiles().filter((f) => f.path.startsWith(folder + "/"));
const map = new Map();
for (const f of files) {
const content = await this.vault.read(f);
const mStrong = content.match(/^strong:\s*(G\d{1,5}|H\d{1,5})\s*$/m);
const mLemma = content.match(/^lemma:\s*(.+)$/m);
if (mStrong && mLemma) {
const lemma = mLemma[1].trim();
const strong = mStrong[1].trim();
if (lemma)
map.set(lemma, strong);
}
}
return map;
}
async applyLemmaLinks(entry, lemmaIndex, recipe) {
const blocks = { ...entry.blocks };
const lemmasFound = new Set();
const tokens = extractGreekHebrewTokens(Object.values(blocks).join("\n"));
for (const token of tokens) {
const strong = lemmaIndex.get(token);
if (!strong)
continue;
lemmasFound.add(token);
for (const k of Object.keys(blocks)) {
if (!blocks[k])
continue;
blocks[k] = replaceTokenWithLink(blocks[k], token, `[[${token}]]`);
}
}
if (recipe.lemmaAliasMode === "all" && lemmasFound.size > 0) {
for (const lemma of lemmasFound) {
const strong = lemmaIndex.get(lemma);
if (strong)
await this.ensureAliasForStrong(strong, lemma, recipe);
}
} else if (entry.lemma) {
await this.ensureAliasForStrong(entry.strong, entry.lemma, recipe);
}
return { ...entry, blocks };
}
async ensureAliasForStrong(strong, lemma, recipe) {
const existing = this.findExistingByStrongIdFallback(strong, recipe);
if (!existing) {
const title = strong;
const folder = recipe.rootFolder.replace(/^\/+|\/+$/g, "");
if (!await this.vault.adapter.exists(folder)) {
await this.vault.createFolder(folder);
}
const path = (0, import_obsidian5.normalizePath)(`${folder}/${title}.md`);
const yaml = [
"---",
`type: lexicon/strongs`,
`strong: ${strong}`,
`lemma: ${lemma}`,
`aliases:`,
` - ${strong}`,
` - ${lemma}`,
"---",
"",
`# ${strong}`,
""
].join("\n");
await this.vault.create(path, yaml);
return;
}
const text = await this.vault.read(existing);
const updated = addAliasToFrontmatter(text, lemma, strong);
if (updated !== text)
await this.vault.modify(existing, updated);
}
findExistingByStrongIdFallback(strong, recipe) {
const folder = recipe.rootFolder.replace(/^\/+|\/+$/g, "");
const files = this.vault.getMarkdownFiles().filter((f) => f.path.startsWith(folder + "/"));
const hit = files.find((f) => f.basename.includes(strong));
return hit != null ? hit : null;
}
};
function extractGreekHebrewTokens(text) {
var _a, _b;
const tokens = new Set();
const greek = (_a = text.match(/[\p{Script=Greek}]+/gu)) != null ? _a : [];
const hebrew = (_b = text.match(/[\p{Script=Hebrew}]+/gu)) != null ? _b : [];
for (const t of [...greek, ...hebrew]) {
if (t.length >= 2)
tokens.add(t);
}
return Array.from(tokens);
}
function replaceTokenWithLink(text, token, link) {
const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return text.replace(new RegExp(escaped, "g"), link);
}
function addAliasToFrontmatter(text, alias, strong) {
if (!text.startsWith("---"))
return text;
const end = text.indexOf("\n---", 3);
if (end < 0)
return text;
const fm = text.slice(0, end + 4);
const body = text.slice(end + 4);
const aliasesMatch = fm.match(/\naliases:\n([\s\S]*?)(?=\n\w|\n---|$)/);
if (!aliasesMatch) {
const insert = `
aliases:
- ${strong}
- ${alias}
`;
return fm.replace("\n---", insert + "\n---") + body;
}
const aliasesBlock = aliasesMatch[1];
if (aliasesBlock.includes(alias))
return text;
const updatedBlock = aliasesBlock + ` - ${alias}
`;
const updatedFm = fm.replace(aliasesBlock, updatedBlock);
return updatedFm + body;
}
// src/main.ts
var BibleHubLexiconImporter = class extends import_obsidian6.Plugin {
async onload() {
var _a, _b;
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
const fe = new Set((_a = this.settings.recipe.followEdges) != null ? _a : []);
fe.add("see_also");
fe.add("related_strongs");
this.settings.recipe.followEdges = Array.from(fe);
if (!this.settings.recipe.linkTypes || this.settings.recipe.linkTypes.length === 0) {
this.settings.recipe.linkTypes = ["strongs", "scripture"];
}
if (this.settings.recipe.linkGreekHebrew === void 0) {
this.settings.recipe.linkGreekHebrew = true;
}
if (!this.settings.recipe.lemmaAliasMode) {
this.settings.recipe.lemmaAliasMode = "primary";
}
if (!this.settings.recipe.scriptureRootFolder) {
this.settings.recipe.scriptureRootFolder = "Scripture";
}
if ((_b = this.settings.recipe.noteTitlePattern) == null ? void 0 : _b.includes("{{short_definition}}")) {
this.settings.recipe.noteTitlePattern = "{{strong}} \u2014 {{lemma}} ({{transliteration}})";
}
this.addSettingTab(new SettingsTab(this.app, this));
const fetcher = new Fetcher(this.settings.recipe.rateLimitMs);
const writer = new Writer(this.app.vault);
const crawler = new Crawler(this.app.vault, fetcher, writer);
this.addCommand({
id: "import-strongs-graph",
name: "Import Strong's as graph (BibleHub)",
callback: async () => {
const seed = await this.getSeedFromSelectionOrPrompt();
if (!seed)
return;
const strong = this.normalizeSeedToStrong(seed);
if (!strong) {
new import_obsidian6.Notice("Could not parse Strong's ID. Try G2198, H1623, or a BibleHub Strong's URL.");
return;
}
const recipe = this.settings.recipe;
new import_obsidian6.Notice(`Importing ${strong} (depth ${recipe.maxDepth}, max ${recipe.maxNodes} nodes)...`);
const result = await crawler.run(strong, recipe, false);
const msg = [
`Done.`,
`Created: ${result.created}`,
`Updated: ${result.updated}`,
`Skipped: ${result.skipped}`,
result.errors.length ? `Errors: ${result.errors.length}` : ""
].filter(Boolean).join(" ");
new import_obsidian6.Notice(msg);
}
});
}
async saveSettings() {
await this.saveData(this.settings);
}
async getSeedFromSelectionOrPrompt() {
var _a, _b;
const view = this.app.workspace.getActiveViewOfType(Object);
const editor = view == null ? void 0 : view.editor;
const selection = (_b = (_a = editor == null ? void 0 : editor.getSelection) == null ? void 0 : _a.call(editor)) == null ? void 0 : _b.trim();
if (selection)
return selection;
return await new SeedModal(this.app).openAndGetValue();
}
normalizeSeedToStrong(seed) {
const s = seed.trim();
const m = s.match(/biblehub\.com\/strongs\/(greek|hebrew)\/(\d+)\.htm/i);
if (m) {
const prefix = m[1].toLowerCase() === "greek" ? "G" : "H";
return prefix + String(parseInt(m[2], 10));
}
const m2 = s.match(/biblehub\.com\/(greek|hebrew)\/(\d+)\.htm/i);
if (m2) {
const prefix = m2[1].toLowerCase() === "greek" ? "G" : "H";
return prefix + String(parseInt(m2[2], 10));
}
const m3 = normalizeStrongId(s);
if (m3)
return m3;
const n = s.match(/\b(\d{1,5})\b/);
if (n)
return normalizeStrongId(n[1], "greek");
return null;
}
};
var SeedModal = class extends import_obsidian6.Modal {
constructor() {
super(...arguments);
this.value = "";
this.resolved = false;
}
async openAndGetValue() {
return new Promise((resolve) => {
this.resolver = resolve;
this.open();
});
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Import BibleHub Strong's" });
contentEl.createEl("p", {
text: "Enter a Strong's ID (G2198 / H1623) or a BibleHub Strong's URL."
});
const input = contentEl.createEl("input", { type: "text" });
input.style.width = "100%";
input.placeholder = "e.g., G2198";
input.addEventListener("input", () => this.value = input.value);
const buttons = contentEl.createDiv({ cls: "modal-button-container" });
const ok = buttons.createEl("button", { text: "Import" });
const cancel = buttons.createEl("button", { text: "Cancel" });
ok.addEventListener("click", () => {
var _a;
this.resolved = true;
this.close();
(_a = this.resolver) == null ? void 0 : _a.call(this, this.value.trim() || null);
});
cancel.addEventListener("click", () => {
var _a;
this.resolved = true;
this.close();
(_a = this.resolver) == null ? void 0 : _a.call(this, null);
});
setTimeout(() => input.focus(), 50);
}
onClose() {
var _a;
if (!this.resolved)
(_a = this.resolver) == null ? void 0 : _a.call(this, null);
this.contentEl.empty();
}
};