-
Notifications
You must be signed in to change notification settings - Fork 1
/
api_request_handler.ts
2112 lines (1890 loc) · 72.1 KB
/
api_request_handler.ts
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
/* eslint-disable @typescript-eslint/no-use-before-define */
import {JewishCalendar} from "kosher-zmanim";
import * as _ from "underscore";
import {Converter as MarkdownConverter} from 'showdown';
import {
ApiResponse,
CommentaryMap,
Section,
ApiComment,
} from "./apiTypes";
import {surroundingContext} from "./arrays";
import {Book, books, internalLinkableRef} from "./books";
import {ALL_COMMENTARIES, CommentaryType} from "./commentaries";
import {readUtf8} from "./files";
import {hadranSegments, isHadran} from "./precomputed/hadran";
import {
stripHebrewNonletters,
stripHebrewNonlettersOrVowels,
intToHebrewNumeral,
mishnehTorahHebrewTitleName,
penineiHalachaHebrewTitleName,
ALEPH,
TAV,
} from "./hebrew";
import {Logger, consoleLogger} from "./logger";
import {mergeRefs} from "./ref_merging";
import {refSorter} from "./js/google_drive/ref_sorter";
import {ListMultimap} from "./multimap";
import {
getSugyaSpanningRef,
mishnaReferencesForPage,
shulchanArukhChapterTitle,
segmentCount,
} from "./precomputed";
import {dedupeEnglishRabbiNames, dedupeHebrewRabbiNames, topicJson} from "./precomputed/topics";
import {llmGeneratedTopic, LlmGeneratedTopic} from "./precomputed/tanakh_context_cache";
import {getTanakhPassage} from "./precomputed/tanakh_passages";
import {expandRef} from "./ref_expander";
import {splitOnBookName} from "./refs";
import {RequestMaker} from "./request_makers";
import {
equalJaggedArrays,
firstOrOnlyElement,
flatten,
sefariaTextTypeTransformation,
} from "./sefariaTextType";
import {
BIGIFY_REFS,
BOLDIFY_REFS,
DONT_MAKE_INTO_EXPLANATIONS,
ENGLISH_TEXT_REPLACEMENTS,
HARDCODED_TEXT,
HEBREW_SECTION_NAMES,
HEBREW_TEXT_REPLACEMENTS,
KEEP_TROPE_REFS,
REALLY_BIG_TEXT_REFS,
SEGMENT_SEPERATOR_REF,
SIDDUR_DEFAULT_MERGE_WITH_NEXT,
SIDDUR_IGNORED_COMMENTARIES,
SIDDUR_IGNORED_FOOTNOTES,
SIDDUR_IGNORED_REFS,
SIDDUR_IGNORED_SOURCE_REFS,
SIDDUR_IGNORED_TARGET_REFS,
SIDDUR_MERGE_PAIRS,
SIDDUR_REFS_ASHKENAZ,
SIDDUR_REFS_SEFARD,
SMALLIFY_REFS,
SYNTHETIC_REFS,
UNSMALL_REFS,
BIRKAT_HAMAZON_REFS,
MergeWithNext,
MergeRefsByDefault,
RefPiece,
getRef,
} from "./siddur";
import {CommentaryParenthesesTransformer} from "./source_formatting/commentary_parentheses";
import {CommentaryPrefixStripper} from "./source_formatting/commentary_prefixes";
import {boldDibureiHamatchil} from "./source_formatting/dibur_hamatchil";
import {FootnotesExtractor} from "./source_formatting/footnotes";
import {HebrewSmallToEmphasisTagTranslator} from "./source_formatting/hebrew_small_to_emphasis";
import {highlightRashiQuotations} from "./source_formatting/rashi_quoting";
import {HtmlNormalizer} from "./source_formatting/html_normalizer";
import {ImageNumberingFormatter} from "./source_formatting/image_numbering";
import {JastrowReformatter} from "./source_formatting/jastrow";
import {parseOtzarLaazeiRashi} from "./source_formatting/otzar_laazei_rashi";
import {SectionSymbolRemover} from "./source_formatting/section_symbol";
import {SefariaLinkSanitizer} from "./source_formatting/sefaria_link_sanitizer";
import {SefariaTopicCollector} from "./source_formatting/sefaria_topic_collector";
import {ShulchanArukhHeaderRemover} from "./source_formatting/shulchan_arukh_remove_header";
import {isPehSectionEnding, transformTanakhSpacing} from "./source_formatting/tanakh_spacing";
import {
makeSteinsaltzCommentPairings,
getTextWithImages,
filterDuplicateImages,
} from "./steinsaltz";
import {formatDafInHebrew} from "./talmud";
import {hasMatchingProperty} from "./util/objects";
import {checkNotUndefined} from "./js/undefined";
import {getWeekdayReading} from "./weekday_parshiot";
import {ASERET_YIMEI_TESHUVA_REFS} from "./js/aseret_yimei_teshuva";
const markdown = new MarkdownConverter();
const standardHebrewTransformations = sefariaTextTypeTransformation(
hebrew => (
HtmlNormalizer.process(SefariaLinkSanitizer.process(hebrew))
));
const standardEnglishTransformations = sefariaTextTypeTransformation(
english => (
HtmlNormalizer.process(
SectionSymbolRemover.process(
SefariaLinkSanitizer.process(english)))
));
function stripRefSegmentNumber(ref: string): string {
const index = ref.indexOf(":");
return index === -1 ? ref : ref.substring(0, index);
}
function stripRefQuotationMarks(ref: string): string {
const parts = ref.split(" ");
const lastPart = parts.pop() ?? "";
if (!lastPart.includes(":")) {
return ref;
}
parts.push(lastPart.replace(/׳/g, "").replace(/״/g, ""));
return parts.join(" ");
}
function stripPossiblePrefix(text: string, prefix: string): string {
if (text.startsWith(prefix)) {
return text.slice(prefix.length);
}
return text;
}
type SplitType = [string, string][];
function llmGeneratedTopicForLink(link: sefaria.TextLink): LlmGeneratedTopic | undefined {
return llmGeneratedTopic(link.ref) ?? llmGeneratedTopic(link.sourceRef);
}
/** A single comment on a text. */
class Comment {
duplicateRefs: string[] = [];
constructor(
readonly englishName: string,
readonly hebrew: sefaria.TextType,
readonly english: sefaria.TextType,
readonly ref: string,
readonly sourceRef: string,
private sourceHeRef: string,
private talmudPageLink?: string,
private readonly originalRefsBeforeRewriting?: string[],
private readonly expandedRefsAfterRewriting?: string[],
) {}
static create(
link: sefaria.TextLink,
sefariaComment: sefaria.TextResponse,
englishName: string,
logger: Logger,
): Comment {
const {ref} = sefariaComment;
let {he: hebrew, text: english} = sefariaComment;
let {sourceRef, sourceHeRef} = link;
if (equalJaggedArrays(hebrew, english)) {
// Fix an issue where sometimes Sefaria returns the exact same text. For now, safe to
// assume that the equivalent text is Hebrew.
logger.log(`${ref} has identical hebrew and english`);
english = "";
}
if (englishName === "Otzar Laazei Rashi") {
[hebrew, english] = parseOtzarLaazeiRashi(hebrew as string);
}
hebrew = standardHebrewTransformations(hebrew);
hebrew = boldDibureiHamatchil(hebrew, englishName);
hebrew = highlightRashiQuotations(hebrew);
for (const processor of (
[
HebrewSmallToEmphasisTagTranslator,
CommentaryPrefixStripper,
CommentaryParenthesesTransformer,
ImageNumberingFormatter,
])) {
hebrew = processor.process(hebrew, englishName);
}
english = standardEnglishTransformations(english);
english = JastrowReformatter.process(english, englishName);
const _internalLinkableRef = internalLinkableRef(sourceRef);
if (englishName === "Mesorat Hashas" && _internalLinkableRef) {
sourceRef = stripRefSegmentNumber(sourceRef);
sourceHeRef = stripRefSegmentNumber(sourceHeRef);
} else {
sourceHeRef = stripRefQuotationMarks(sourceHeRef);
}
const talmudPageLink = _internalLinkableRef?.toUrlPathname();
[sourceRef, sourceHeRef] = Comment.maybeRewriteRefNames(englishName, sourceRef, sourceHeRef);
if (englishName === "Shulchan Arukh") {
const subtitle = shulchanArukhChapterTitle(ref);
if (subtitle) {
sourceHeRef = `${sourceHeRef} - ${subtitle}`;
if (ref.endsWith(":1")) {
hebrew = ShulchanArukhHeaderRemover.process(hebrew, englishName);
}
}
}
if (englishName === "Verses") {
const llmResult = llmGeneratedTopicForLink(link);
if (llmResult === undefined) {
// TODO: this happens for spanned refs!
logger.error("No result for", ref);
} else if (typeof llmResult === "string") {
logger.error("Error result for", ref, llmResult);
} else {
sourceRef += " - " + llmResult.english;
sourceHeRef += " - " + llmResult.hebrew;
}
}
return new Comment(
englishName,
hebrew,
english,
ref,
sourceRef,
sourceHeRef,
talmudPageLink,
link.originalRefsBeforeRewriting,
link.expandedRefsAfterRewriting,
);
}
static maybeRewriteRefNames(
englishName: string, sourceRef: string, sourceHeRef: string,
): [string, string] {
if (englishName === "Shulchan Arukh") {
sourceRef = stripPossiblePrefix(sourceRef, "Shulchan Arukh, ");
sourceHeRef = stripPossiblePrefix(sourceHeRef, "שולחן ערוך, ");
} else if (englishName === "Mishneh Torah") {
sourceRef = stripPossiblePrefix(sourceRef, "Mishneh Torah, ");
sourceHeRef = stripPossiblePrefix(sourceHeRef, "משנה תורה, ");
} else if (englishName === "Peninei Halakhah") {
sourceRef = stripPossiblePrefix(sourceRef, "Peninei Halakhah, ");
sourceHeRef = stripPossiblePrefix(sourceHeRef, "פניני הלכה, ");
} else if (englishName === "Jastrow") {
sourceHeRef = stripPossiblePrefix(sourceHeRef, "מילון יסטרוב, ");
const match = sourceHeRef.match(/^(.*)( [א-ת]['׳])$/);
if (match) {
sourceHeRef = match[1]; // eslint-disable-line prefer-destructuring
}
sourceHeRef = stripHebrewNonletters(sourceHeRef);
}
return [sourceRef, sourceHeRef];
}
toJson(): ApiComment {
const result: ApiComment = {
he: this.hebrew,
en: this.english,
ref: this.ref,
sourceRef: this.sourceRef,
sourceHeRef: this.sourceHeRef,
};
if (this.talmudPageLink) {
result.link = this.talmudPageLink;
}
if (this.originalRefsBeforeRewriting) {
result.originalRefsBeforeRewriting = this.originalRefsBeforeRewriting;
}
if (this.expandedRefsAfterRewriting) {
result.expandedRefsAfterRewriting = this.expandedRefsAfterRewriting;
}
if (this.duplicateRefs.length > 0) {
result.duplicateRefs = this.duplicateRefs;
}
return result;
}
static fakeTextLink = {
sourceRef: "fake",
sourceHeRef: "fake",
ref: "fake",
anchorRef: "fake",
anchorRefExpanded: ["fake"],
versionTitle: "fake",
};
}
/** Maintains the state of all comments on a particular segment or (nested) commentary. */
class InternalCommentary {
private refs = new Set<string>();
comments: Comment[] = [];
nestedCommentaries: Record<string, InternalCommentary> = {};
addComment(comment: Comment) {
if (this.refs.has(comment.ref)) {
return;
}
this.refs.add(comment.ref);
this.comments.push(comment);
for (const topicComment of extractTopicComments(
flatten(comment.hebrew) ?? "", flatten(comment.english) ?? "")) {
this.nestedCommentary(comment.ref).addComment(topicComment);
}
}
nestedCommentary(parentRef: string) {
if (!(parentRef in this.nestedCommentaries)) {
this.nestedCommentaries[parentRef] = new InternalCommentary();
}
return this.nestedCommentaries[parentRef];
}
removeComment(comment: Comment) {
const {ref} = comment;
this.refs.delete(ref);
this.comments = this.comments.filter(x => x.ref !== ref);
}
removeCommentWithRef(ref: string) {
for (const comment of this.comments) {
if (ref === comment.ref) {
this.removeComment(comment);
break;
}
}
}
toJson(): CommentaryMap {
const result: CommentaryMap = {};
for (const comment of this.comments) {
if (!(comment.englishName in result)) {
result[comment.englishName] = {comments: []};
}
const apiComment = comment.toJson();
for (const [ref, nestedCommentary] of Object.entries(this.nestedCommentaries)) {
if (comment.ref !== ref) continue;
const nestedCommentaryValue = nestedCommentary.toJson();
if (Object.keys(nestedCommentaryValue).length === 0) continue;
if (apiComment.commentary === undefined) {
apiComment.commentary = {};
}
Object.assign(apiComment.commentary, nestedCommentaryValue);
}
result[comment.englishName].comments.push(apiComment);
}
/*
for (const [englishName, nestedCommentary] of Object.entries(this.nestedCommentaries)) {
const nestedCommentaryValue = nestedCommentary.toJson();
if (Object.keys(nestedCommentaryValue).length > 0) {
if (!result[englishName]) {
// This case can arise when a duplicated nested commentary is removed. The parent still
// has a reference to the nested commentary, but there is no parent comment to attach it
// to.
continue;
}
result[englishName].commentary = nestedCommentaryValue;
}
}
*/
return result;
}
addAll(other: InternalCommentary) {
for (const ref of other.refs) {
this.refs.add(ref);
}
this.comments.push(...other.comments);
for (const [key, nested] of Object.entries(other.nestedCommentaries)) {
if (!(key in this.nestedCommentaries)) {
this.nestedCommentaries[key] = new InternalCommentary();
}
this.nestedCommentaries[key].addAll(nested);
}
}
}
interface InternalSegmentConstructorParams {
hebrew: sefaria.TextType,
english: sefaria.TextType,
ref: string,
}
export class InternalSegment {
hebrew: sefaria.TextType;
english: sefaria.TextType;
readonly ref: string;
commentary = new InternalCommentary();
hadran?: true;
// eslint-disable-next-line camelcase
startOfSection?: true;
lastSegmentOfSection?: true;
defaultMergeWithNext?: true;
constructor({hebrew, english, ref}: InternalSegmentConstructorParams) {
this.hebrew = hebrew;
this.english = english;
this.ref = ref;
}
static merge(segments: InternalSegment[]): InternalSegment {
const hebrews = [];
const englishes = [];
const refs = [];
for (const segment of segments) {
if (typeof segment.hebrew !== "string") {
throw new TypeError("segment.hebrew is not a string! " + segment.hebrew);
} else if (typeof segment.english !== "string") {
throw new TypeError("segment.english is not a string! " + segment.english);
}
hebrews.push(segment.hebrew);
englishes.push(segment.english);
refs.push(segment.ref);
}
const mergedRefs = Array.from(mergeRefs(refs).keys());
if (mergedRefs.length !== 1) {
throw new Error(mergedRefs.join(" :: "));
}
const newSegment = new InternalSegment({
hebrew: hebrews.join(" "),
english: englishes.join(" "),
ref: mergedRefs[0],
});
for (const segment of segments) {
newSegment.commentary.addAll(segment.commentary);
if (segment.hadran) {
newSegment.hadran = true;
}
if (segment.startOfSection) {
newSegment.startOfSection = true;
}
if (segment.defaultMergeWithNext) {
newSegment.defaultMergeWithNext = true;
}
}
return newSegment;
}
toJson(): Section {
const json: Section = {
he: this.hebrew,
en: this.english,
ref: this.ref,
commentary: this.commentary.toJson(),
};
if (this.hadran) {
json.hadran = this.hadran;
}
if (this.startOfSection) {
json.startOfSection = this.startOfSection;
json.steinsaltz_start_of_sugya = this.startOfSection;
}
if (this.lastSegmentOfSection) {
json.lastSegmentOfSection = true;
}
if (this.defaultMergeWithNext) {
json.defaultMergeWithNext = this.defaultMergeWithNext;
}
return json;
}
}
class LinkGraph {
graph: Record<string, Set<string>> = {};
links: Record<string, Record<string, sefaria.TextLink>> = {}
textResponses: Record<string, sefaria.TextResponse> = {};
// TODO(typescript): don't cache the result if the link graph is incomlete
complete = true;
hasLink(sourceRef: string, targetRef: string): boolean {
return this.getGraph(sourceRef).has(targetRef);
}
getGraph(sourceRef: string): Set<string> {
if (!(sourceRef in this.graph)) {
this.graph[sourceRef] = new Set<string>();
}
return this.graph[sourceRef];
}
addLink(sourceRef: string, link: sefaria.TextLink): void {
this.getGraph(sourceRef).add(link.ref);
if (this.links[sourceRef] === undefined) {
this.links[sourceRef] = {};
}
this.links[sourceRef][link.ref] = link;
}
}
function textRequestEndpoint(ref: string): string {
const params = [
["wrapLinks", "0"],
["commentary", "0"],
["context", "0"],
["wrapNamedEntities", "1"],
].map(pair => pair.join("=")).join("&");
return `/texts/${ref}?${params}`;
}
export class ApiException extends Error {
static SEFARIA_HTTP_ERROR = 1;
static UNEQAUL_HEBREW_ENGLISH_LENGTH = 2;
constructor(
message: string,
readonly httpStatus: number,
readonly internalCode: number,
) {
super(message);
}
}
class BulkTextGroup {
constructor(
readonly key: string,
readonly refs: string[],
readonly urlExtension: string,
) {}
}
function isSefariaError(response: any): response is sefaria.ErrorResponse {
return "error" in response;
}
const LOTS_OF_NON_BREAKING_SPACES = new RegExp(String.fromCharCode(160) + "{4,}", 'g');
export abstract class AbstractApiRequestHandler {
private applicableCommentaries: CommentaryType[];
constructor(
protected readonly bookName: string,
protected readonly page: string,
protected readonly requestMaker: RequestMaker,
protected readonly logger: Logger,
) {
this.applicableCommentaries = this.getApplicableCommentaries();
}
protected abstract makeId(): string;
protected makeSubRef(mainRef: string, index: number): string {
if (mainRef.includes("-")) {
const lastColon = mainRef.lastIndexOf(":");
const range = mainRef.substring(lastColon + 1);
const start = parseInt(range.split("-")[0]);
return `${mainRef.substring(0, lastColon)}:${start + index}`;
} else {
return `${mainRef}:${index + 1}`;
}
}
protected makeTitle(): string {
return `${this.book().canonicalName} ${this.page}`;
}
protected abstract makeTitleHebrew(): string;
private replaceLotsOfNonBreakingSpacesWithNewlines(text: string): string {
return text.replace(LOTS_OF_NON_BREAKING_SPACES, "<br>");
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected translateHebrewText(text: sefaria.TextType, ref: string): sefaria.TextType {
return standardHebrewTransformations(
sefariaTextTypeTransformation(this.replaceLotsOfNonBreakingSpacesWithNewlines)(text));
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected translateEnglishText(text: sefaria.TextType, ref: string): sefaria.TextType {
return standardEnglishTransformations(text);
}
protected maybeSplit(ref: string, hebrew: string, english: string): SplitType {
return [[hebrew, english]];
}
private dedupeTopicComments(segments: InternalSegment[]) {
const currentSugyaTopics = new Set<string>();
for (const segment of segments) {
if (segment.startOfSection) {
currentSugyaTopics.clear();
}
for (const comment of segment.commentary.comments) {
if (comment.englishName !== "Topics") continue;
if (currentSugyaTopics.has(comment.ref)) {
segment.commentary.removeComment(comment);
} else {
currentSugyaTopics.add(comment.ref);
}
}
}
}
private detectDupes(segments: InternalSegment[]) {
const comments: Comment[] = [];
for (const segment of segments) {
for (const comment of segment.commentary.comments) {
if (typeof comment.hebrew !== "string" || comment.hebrew.length === 0) continue;
if (comment.englishName === "Verses") continue; // some verses have identical text!
comments.push(comment);
}
}
const key = (comment: Comment) => `${comment.englishName} // ${comment.hebrew}`;
const dupedRefs = new ListMultimap<string, string>();
for (const comment of comments) {
dupedRefs.put(key(comment), comment.ref);
}
for (const comment of comments) {
const dupes = dupedRefs.get(key(comment));
if (dupes.length > 1) {
comment.duplicateRefs = dupes.filter(x => x !== comment.ref);
}
}
}
/** Called before postProcessAllSegments(). */
protected postProcessSegment(segment: InternalSegment): InternalSegment {
return segment;
}
protected postProcessAllSegments(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
segments: InternalSegment[], ...extraValues: any[]
): InternalSegment[] {
return segments;
}
protected injectSegmentSeperators(segments: InternalSegment[]): InternalSegment[] {
const newSegments = [];
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
if (segment.ref === SEGMENT_SEPERATOR_REF) {
segments[i + 1].startOfSection = true;
} else {
newSegments.push(segment);
}
}
return newSegments;
}
protected extraSegments(): Section[] {
return [];
}
protected linkDepth(): number {
return 2;
}
handleRequest(): Promise<ApiResponse> {
const book = this.book();
const ref = `${book.bookNameForRef()} ${book.rewriteSectionRef(this.page)}`;
const underlyingRefs = this.expandRef(ref);
const textRequest = this.makeTextRequest(ref, underlyingRefs);
const linksTraversalTimer = this.logger.newTimer();
const linkGraphRequest = this.linksTraversal(
this.startingLinkGraph(), ListMultimap.identity(underlyingRefs), this.linkDepth(), true)
.finally(() => linksTraversalTimer.finish("links traversal"));
return Promise.all([
textRequest,
linkGraphRequest.then(linkGraph => {
const textRequestRefs = new Set<string>();
const addTextRequestRef = (requestRef: string) => {
if (!(requestRef in linkGraph.textResponses)
&& !underlyingRefs.some(underlyingRef => requestRef.startsWith(underlyingRef))) {
textRequestRefs.add(requestRef);
}
};
for (const [key, graph] of Object.entries(linkGraph.graph)) {
addTextRequestRef(key);
graph.forEach(addTextRequestRef);
}
return this.fetchData(Array.from(textRequestRefs), ref)
.then(fetched => {
for (const [fetchedRef, textResponse] of Object.entries(fetched)) {
linkGraph.textResponses[fetchedRef] = textResponse;
}
})
.then(() => linkGraph);
}),
...this.extraPromises(),
]).then(args => this.transformData(...args));
}
protected extraPromises(): Promise<any>[] {
return [];
}
protected expandRef(ref: string): string[] {
return [ref];
}
private makeTextRequest(ref: string, underlyingRefs: string[]): Promise<sefaria.TextResponse> {
if (underlyingRefs.length === 1 && ref === underlyingRefs[0]) {
return this.requestMaker.makeRequest<sefaria.TextResponse>(textRequestEndpoint(ref));
}
return this.fetchData(underlyingRefs, ref + "_bulk_root")
.then(fetchedData => {
const response: sefaria.TextResponse = {
he: [],
text: [],
ref,
refsPerSubText: [],
};
for (const underlyingRef of underlyingRefs) {
const underlyingRefData = fetchedData[underlyingRef];
let {he, text} = underlyingRefData;
const addSegment = (
hebrew: sefaria.TextType,
english: sefaria.TextType,
segmentRef: string,
) => {
(response.he as string[]).push(hebrew as string);
(response.text as string[]).push(english as string);
response.refsPerSubText!.push(segmentRef);
};
if (typeof he === "string") {
addSegment(he, text, underlyingRef);
} else {
he = he.flat();
text = (text as any).flat();
const addSegmentRange = (
prefixRef: string, segmentIndices: number[], suffixIndices: number[]) => {
for (let i = 0; i < segmentIndices.length; i++) {
addSegment(
he[segmentIndices[i]],
text[segmentIndices[i]],
// The -1 here is a hack, since makeSubRef typically expects zero-indexed offsets.
this.makeSubRef(prefixRef, suffixIndices[i] - 1));
}
};
if (Number.isNaN(parseInt(underlyingRef.slice(-1))) || !underlyingRef.includes("-")) {
addSegmentRange(underlyingRef, _.range(he.length), _.range(1, he.length + 1));
continue;
}
const [baseRef, refRange] = splitOnBookName(underlyingRef);
const [start, end] = refRange.split("-");
const chapterAndVerse = (combined: string): [string, number] => {
const [chapter, verse] = combined.split(":");
return [chapter, parseInt(verse)];
};
if (start.includes(":") && end.includes(":")) {
const [startChapter, startVerse] = chapterAndVerse(start);
const [endChapter, endVerse] = chapterAndVerse(end);
addSegmentRange(
`${baseRef} ${startChapter}`,
_.range(he.length - endVerse),
_.range(startVerse, startVerse + he.length - endVerse));
addSegmentRange(
`${baseRef} ${endChapter}`,
_.range(he.length - endVerse, he.length),
_.range(endVerse));
continue;
}
if (start.includes(":")) {
const [startChapter, startVerse] = chapterAndVerse(start);
addSegmentRange(
`${baseRef} ${startChapter}`,
_.range(he.length),
_.range(startVerse, startVerse + he.length));
} else {
addSegmentRange(
baseRef,
_.range(he.length),
_.range(parseInt(start), parseInt(start) + he.length));
}
}
}
return response;
});
}
private linksRequestUrl(ref: string) {
return `/links/${ref}?with_text=0`;
}
private linksTraversal(
linkGraph: LinkGraph,
refsInRound: ListMultimap<string, string>,
remainingDepth: number,
isRoot: boolean,
): Promise<LinkGraph> {
if (remainingDepth === 0) {
return Promise.resolve(linkGraph);
}
const nextRefs: string[] = [];
if (isRoot) {
for (const targetRefs of Object.values(linkGraph.graph)) {
nextRefs.push(...targetRefs);
}
}
const allLinksRequests = Promise.allSettled(
Array.from(refsInRound.keys()).map(ref => {
if (SYNTHETIC_REFS.has(ref)) {
return Promise.resolve<sefaria.TextLink[]>([]);
}
const url = this.linksRequestUrl(ref);
return this.requestMaker.makeRequest<sefaria.TextLink[] | sefaria.ErrorResponse>(url);
}));
return allLinksRequests.then(allLinksResponses => {
const refsInRoundKeys = Array.from(refsInRound.keys());
for (let i = 0; i < allLinksResponses.length; i++) {
const linksResponse = allLinksResponses[i];
if (linksResponse.status === "rejected" || isSefariaError(linksResponse.value)) {
this.logger.error("Links request error", linksResponse);
linkGraph.complete = false;
continue;
}
const ref = refsInRoundKeys[i];
const mergedRefs = refsInRound.get(ref);
for (const link of linksResponse.value) {
const commentaryType = this.matchingCommentaryType(link);
if (!commentaryType) continue;
this.maybeRewriteLinkRef(commentaryType, link);
const targetRef = link.ref;
if (this.ignoreLink(mergedRefs, targetRef)) {
continue;
}
if (targetRef in linkGraph.graph) {
continue;
}
let sourceRefIndex = Math.min(
...mergedRefs.map(x => link.anchorRefExpanded.indexOf(x)).filter(x => x !== -1));
if (sourceRefIndex === Infinity) {
sourceRefIndex = 0;
}
if (targetRef.startsWith("Introductions to the Babylonian Talmud")
&& targetRef.includes("Summary of Perek")) {
sourceRefIndex = link.anchorRefExpanded.length - 1;
}
const sourceRef = link.anchorRefExpanded[sourceRefIndex];
if (linkGraph.hasLink(sourceRef, targetRef)
|| (!isRoot && commentaryType.ignoreIfNotTypeLevel)) {
continue;
}
linkGraph.addLink(sourceRef, link);
if (remainingDepth !== 0 && this.shouldTraverseNestedRef(commentaryType, link)) {
nextRefs.push(targetRef);
}
}
}
return this.linksTraversal(linkGraph, mergeRefs(nextRefs), remainingDepth - 1, false);
});
}
// Allows for creating synthetic links from what's known statically.
protected startingLinkGraph(): LinkGraph {
return new LinkGraph();
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected ignoreLink(mergedSourceRefs: string[], targetRef: string): boolean {
return false;
}
protected maybeRewriteLinkRef(commentaryType: CommentaryType, link: sefaria.TextLink): void {
if (books.byCanonicalName[link.collectiveTitle?.en ?? ""]?.isBibleBook()) {
if (link.ref.includes(":")) {
const expandedRefs = expandRef(link.ref)!;
const passage = getTanakhPassage(expandedRefs[0]);
if (passage) {
link.originalRefsBeforeRewriting = expandedRefs;
const context = surroundingContext(passage, expandedRefs[0], 10);
link.expandedRefsAfterRewriting = context;
link.ref = `${context[0]}-${splitOnBookName(context.at(-1)!)[1]}`;
}
} else {
link.expandedRefsAfterRewriting = (
_.range(1, segmentCount(link.ref)!).map(x => `${link.ref}:${x}`));
}
}
if (this.isMesoratHashasTalmudRef(commentaryType, link)) {
const newRef = getSugyaSpanningRef(link.collectiveTitle?.en ?? "", link.ref);
if (!newRef) return;
link.originalRefsBeforeRewriting = expandRef(link.ref);
link.ref = newRef;
link.expandedRefsAfterRewriting = expandRef(newRef);
}
}
private isMesoratHashasTalmudRef(
commentaryType: CommentaryType, link: sefaria.TextLink,
): boolean {
return commentaryType.englishName === "Mesorat Hashas" && link.category === "Talmud";
}
private shouldTraverseNestedRef(commentaryType: CommentaryType, link: sefaria.TextLink): boolean {
return (commentaryType.allowNestedTraversals
|| this.isMesoratHashasTalmudRef(commentaryType, link));
}
private fetchData(
refs: string[],
requestId: string,
): Promise<Record<string, sefaria.TextResponse>> {
if (refs.length === 0) {
return Promise.resolve({});
}
const timer = this.logger.newTimer();
const fetched: Record<string, sefaria.TextResponse> = {};
const nestedPromises: Promise<unknown>[] = [];
// 40 seems to be a sweet spot for speed. Perhaps it's because it limits the number of requests
// without making any of those requests heavyweight.
const shardSize = 40;
// Sorting helps maintain expected outputs for tests, and also for debugging queries that may go
// awry. There isn't much need to use mergeRefs(), and in fact it may cause problems with the
// maintaining a stable shard size.
refs = Array.from(refs);
refs.sort(refSorter);
for (const syntheticRef of SYNTHETIC_REFS) {
if (refs.includes(syntheticRef)) {
fetched[syntheticRef] = {ref: syntheticRef, he: "", text: ""};
const [first, last] = [
refs.indexOf(syntheticRef), refs.lastIndexOf(syntheticRef)];
refs.splice(first, last - first + 1);
}
}
for (const bulkTextGroup of this.groupRefsByCustomParameters(refs)) {
for (let i = 0; i < bulkTextGroup.refs.length; i += shardSize) {
const delimitedRefs = bulkTextGroup.refs.slice(i, i + shardSize).join("|");
let url = `/bulktext/${delimitedRefs}?useTextFamily=1`;
// The tp parameter is helpful for debugging and maintaining stability of recorded test data
url += `&tp=${requestId}@${bulkTextGroup.key}_${i}`;
url += bulkTextGroup.urlExtension;
nestedPromises.push(
this.requestMaker.makeRequest<sefaria.BulkTextResponse>(url).then(allTexts => {
for (const ref of Object.keys(allTexts)) {
const response = allTexts[ref];
fetched[ref] = {
he: response.he,
text: response.en,
ref,
};
}
}));
}
}
return Promise.allSettled(nestedPromises)
.then(() => fetched)
.finally(() => timer.finish("fetching secondary texts"));
}
private groupRefsByCustomParameters(refs: string[]): BulkTextGroup[] {
const indexed = new ListMultimap<string, string>();
const extensions: Record<string, string> = {
/* eslint-disable quote-props */
"Tanakh": "&ven=Tanakh: The Holy Scriptures, published by JPS",
"Standard": "",
/* eslint-enable quote-props */
};
for (const ref of refs) {
const title = ref.slice(0, ref.lastIndexOf(" "));
if (books.byCanonicalName[title]?.isBibleBook()) {
indexed.put("Tanakh", ref);
} else {
indexed.put("Standard", ref);
}
}
const result = [];
for (const [key, groupedRefs] of indexed.asMap().entries()) {
result.push(new BulkTextGroup(key, groupedRefs, extensions[key] ?? ""));
}
return result;
}