@mastra/rag 1.2.3-alpha.0 → 1.2.3-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/package.json +19 -6
  3. package/.turbo/turbo-build.log +0 -4
  4. package/docker-compose.yaml +0 -22
  5. package/eslint.config.js +0 -6
  6. package/src/document/document.test.ts +0 -2975
  7. package/src/document/document.ts +0 -335
  8. package/src/document/extractors/base.ts +0 -30
  9. package/src/document/extractors/index.ts +0 -5
  10. package/src/document/extractors/keywords.test.ts +0 -125
  11. package/src/document/extractors/keywords.ts +0 -126
  12. package/src/document/extractors/questions.test.ts +0 -120
  13. package/src/document/extractors/questions.ts +0 -111
  14. package/src/document/extractors/summary.test.ts +0 -107
  15. package/src/document/extractors/summary.ts +0 -122
  16. package/src/document/extractors/title.test.ts +0 -121
  17. package/src/document/extractors/title.ts +0 -185
  18. package/src/document/extractors/types.ts +0 -40
  19. package/src/document/index.ts +0 -2
  20. package/src/document/prompts/base.ts +0 -77
  21. package/src/document/prompts/format.ts +0 -9
  22. package/src/document/prompts/index.ts +0 -15
  23. package/src/document/prompts/prompt.ts +0 -60
  24. package/src/document/prompts/types.ts +0 -29
  25. package/src/document/schema/index.ts +0 -3
  26. package/src/document/schema/node.ts +0 -187
  27. package/src/document/schema/types.ts +0 -40
  28. package/src/document/transformers/character.ts +0 -267
  29. package/src/document/transformers/html.ts +0 -346
  30. package/src/document/transformers/json.ts +0 -536
  31. package/src/document/transformers/latex.ts +0 -11
  32. package/src/document/transformers/markdown.ts +0 -239
  33. package/src/document/transformers/semantic-markdown.ts +0 -227
  34. package/src/document/transformers/sentence.ts +0 -314
  35. package/src/document/transformers/text.ts +0 -158
  36. package/src/document/transformers/token.ts +0 -137
  37. package/src/document/transformers/transformer.ts +0 -5
  38. package/src/document/types.ts +0 -145
  39. package/src/document/validation.ts +0 -158
  40. package/src/graph-rag/index.test.ts +0 -235
  41. package/src/graph-rag/index.ts +0 -306
  42. package/src/index.ts +0 -8
  43. package/src/rerank/index.test.ts +0 -150
  44. package/src/rerank/index.ts +0 -198
  45. package/src/rerank/relevance/cohere/index.ts +0 -56
  46. package/src/rerank/relevance/index.ts +0 -3
  47. package/src/rerank/relevance/mastra-agent/index.ts +0 -32
  48. package/src/rerank/relevance/zeroentropy/index.ts +0 -26
  49. package/src/tools/README.md +0 -153
  50. package/src/tools/document-chunker.ts +0 -34
  51. package/src/tools/graph-rag.test.ts +0 -115
  52. package/src/tools/graph-rag.ts +0 -157
  53. package/src/tools/index.ts +0 -3
  54. package/src/tools/types.ts +0 -126
  55. package/src/tools/vector-query-database-config.test.ts +0 -190
  56. package/src/tools/vector-query.test.ts +0 -477
  57. package/src/tools/vector-query.ts +0 -171
  58. package/src/utils/convert-sources.ts +0 -43
  59. package/src/utils/default-settings.ts +0 -38
  60. package/src/utils/index.ts +0 -3
  61. package/src/utils/tool-schemas.ts +0 -38
  62. package/src/utils/vector-prompts.ts +0 -832
  63. package/src/utils/vector-search.ts +0 -130
  64. package/tsconfig.build.json +0 -9
  65. package/tsconfig.json +0 -5
  66. package/tsup.config.ts +0 -17
  67. package/vitest.config.ts +0 -8
@@ -1,185 +0,0 @@
1
- import { Agent } from '@mastra/core/agent';
2
- import type { MastraLanguageModel } from '@mastra/core/agent';
3
- import { defaultTitleCombinePromptTemplate, defaultTitleExtractorPromptTemplate, PromptTemplate } from '../prompts';
4
- import type { TitleCombinePrompt, TitleExtractorPrompt } from '../prompts';
5
- import { TextNode } from '../schema';
6
- import type { BaseNode } from '../schema';
7
- import { BaseExtractor } from './base';
8
- import { baseLLM } from './types';
9
- import type { TitleExtractorsArgs } from './types';
10
-
11
- type ExtractTitle = {
12
- documentTitle: string;
13
- };
14
-
15
- /**
16
- * Extract title from a list of nodes.
17
- */
18
- export class TitleExtractor extends BaseExtractor {
19
- llm: MastraLanguageModel;
20
- isTextNodeOnly: boolean = false;
21
- nodes: number = 5;
22
- nodeTemplate: TitleExtractorPrompt;
23
- combineTemplate: TitleCombinePrompt;
24
-
25
- constructor(options?: TitleExtractorsArgs) {
26
- super();
27
-
28
- this.llm = options?.llm ?? baseLLM;
29
- this.nodes = options?.nodes ?? 5;
30
-
31
- this.nodeTemplate = options?.nodeTemplate
32
- ? new PromptTemplate({
33
- templateVars: ['context'],
34
- template: options.nodeTemplate,
35
- })
36
- : defaultTitleExtractorPromptTemplate;
37
-
38
- this.combineTemplate = options?.combineTemplate
39
- ? new PromptTemplate({
40
- templateVars: ['context'],
41
- template: options.combineTemplate,
42
- })
43
- : defaultTitleCombinePromptTemplate;
44
- }
45
-
46
- /**
47
- * Extract titles from a list of nodes.
48
- * @param {BaseNode[]} nodes Nodes to extract titles from.
49
- * @returns {Promise<BaseNode<ExtractTitle>[]>} Titles extracted from the nodes.
50
- */
51
- async extract(nodes: BaseNode[]): Promise<Array<ExtractTitle>> {
52
- // Prepare output array in original node order
53
- const results: ExtractTitle[] = new Array(nodes.length);
54
- // Keep track of nodes with content to extract
55
- const nodesToExtractTitle: BaseNode[] = [];
56
- const nodeIndexes: number[] = [];
57
-
58
- nodes.forEach((node, idx) => {
59
- const text = node.getContent();
60
- if (!text || text.trim() === '') {
61
- results[idx] = { documentTitle: '' };
62
- } else {
63
- nodesToExtractTitle.push(node);
64
- nodeIndexes.push(idx);
65
- }
66
- });
67
-
68
- if (nodesToExtractTitle.length) {
69
- const filteredNodes = this.filterNodes(nodesToExtractTitle);
70
- if (filteredNodes.length) {
71
- const nodesByDocument = this.separateNodesByDocument(filteredNodes);
72
- const titlesByDocument = await this.extractTitles(nodesByDocument);
73
- filteredNodes.forEach((node, i) => {
74
- const nodeIndex = nodeIndexes[i];
75
- const groupKey = node.sourceNode?.nodeId ?? node.id_;
76
- if (typeof nodeIndex === 'number') {
77
- results[nodeIndex] = {
78
- documentTitle: titlesByDocument[groupKey] ?? '',
79
- };
80
- }
81
- });
82
- }
83
- }
84
- return results;
85
- }
86
-
87
- private filterNodes(nodes: BaseNode[]): BaseNode[] {
88
- return nodes.filter(node => {
89
- if (this.isTextNodeOnly && !(node instanceof TextNode)) {
90
- return false;
91
- }
92
- return true;
93
- });
94
- }
95
-
96
- private separateNodesByDocument(nodes: BaseNode[]): Record<string, BaseNode[]> {
97
- const nodesByDocument: Record<string, BaseNode[]> = {};
98
-
99
- for (const node of nodes) {
100
- const groupKey = node.sourceNode?.nodeId ?? node.id_;
101
- nodesByDocument[groupKey] = nodesByDocument[groupKey] || [];
102
- nodesByDocument[groupKey].push(node);
103
- }
104
-
105
- return nodesByDocument;
106
- }
107
-
108
- private async extractTitles(nodesByDocument: Record<string, BaseNode[]>): Promise<Record<string, string>> {
109
- const titlesByDocument: Record<string, string> = {};
110
-
111
- for (const [key, nodes] of Object.entries(nodesByDocument)) {
112
- const titleCandidates = await this.getTitlesCandidates(nodes);
113
- const combinedTitles = titleCandidates.join(', ');
114
-
115
- let title = '';
116
-
117
- if (this.llm.specificationVersion === 'v2') {
118
- const miniAgent = new Agent({
119
- model: this.llm,
120
- name: 'title-extractor',
121
- instructions:
122
- 'You are a title extractor. You are given a list of nodes and you need to extract the title from the nodes.',
123
- });
124
- const result = await miniAgent.generateVNext(
125
- [{ role: 'user', content: this.combineTemplate.format({ context: combinedTitles }) }],
126
- { format: 'mastra' },
127
- );
128
- title = result.text;
129
- } else {
130
- const miniAgent = new Agent({
131
- model: this.llm,
132
- name: 'title-extractor',
133
- instructions:
134
- 'You are a title extractor. You are given a list of nodes and you need to extract the title from the nodes.',
135
- });
136
- const result = await miniAgent.generate([
137
- { role: 'user', content: this.combineTemplate.format({ context: combinedTitles }) },
138
- ]);
139
- title = result.text;
140
- }
141
-
142
- if (!title) {
143
- console.warn('Title extraction LLM output returned empty');
144
- }
145
-
146
- titlesByDocument[key] = title;
147
- }
148
-
149
- return titlesByDocument;
150
- }
151
-
152
- private async getTitlesCandidates(nodes: BaseNode[]): Promise<string[]> {
153
- const miniAgent = new Agent({
154
- model: this.llm,
155
- name: 'titles-candidates-extractor',
156
- instructions:
157
- 'You are a titles candidates extractor. You are given a list of nodes and you need to extract the titles candidates from the nodes.',
158
- });
159
-
160
- const titleJobs = nodes.map(async node => {
161
- let completion: string;
162
- if (this.llm.specificationVersion === 'v2') {
163
- const result = await miniAgent.generateVNext(
164
- [{ role: 'user', content: this.nodeTemplate.format({ context: node.getContent() }) }],
165
- { format: 'mastra' },
166
- );
167
- completion = result.text;
168
- } else {
169
- const result = await miniAgent.generate([
170
- { role: 'user', content: this.nodeTemplate.format({ context: node.getContent() }) },
171
- ]);
172
- completion = result.text;
173
- }
174
-
175
- if (!completion) {
176
- console.warn('Title candidate extraction LLM output returned empty');
177
- return '';
178
- }
179
-
180
- return completion.trim();
181
- });
182
-
183
- return await Promise.all(titleJobs);
184
- }
185
- }
@@ -1,40 +0,0 @@
1
- import { createOpenAI } from '@ai-sdk/openai';
2
- import type { MastraLanguageModel } from '@mastra/core/agent';
3
- import type {
4
- KeywordExtractPrompt,
5
- QuestionExtractPrompt,
6
- SummaryPrompt,
7
- TitleExtractorPrompt,
8
- TitleCombinePrompt,
9
- } from '../prompts';
10
-
11
- export type KeywordExtractArgs = {
12
- llm?: MastraLanguageModel;
13
- keywords?: number;
14
- promptTemplate?: KeywordExtractPrompt['template'];
15
- };
16
-
17
- export type QuestionAnswerExtractArgs = {
18
- llm?: MastraLanguageModel;
19
- questions?: number;
20
- promptTemplate?: QuestionExtractPrompt['template'];
21
- embeddingOnly?: boolean;
22
- };
23
-
24
- export type SummaryExtractArgs = {
25
- llm?: MastraLanguageModel;
26
- summaries?: string[];
27
- promptTemplate?: SummaryPrompt['template'];
28
- };
29
-
30
- export type TitleExtractorsArgs = {
31
- llm?: MastraLanguageModel;
32
- nodes?: number;
33
- nodeTemplate?: TitleExtractorPrompt['template'];
34
- combineTemplate?: TitleCombinePrompt['template'];
35
- };
36
-
37
- export const STRIP_REGEX = /(\r\n|\n|\r)/gm;
38
-
39
- const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });
40
- export const baseLLM: MastraLanguageModel = openai('gpt-4o');
@@ -1,2 +0,0 @@
1
- export * from './document';
2
- export * from './types';
@@ -1,77 +0,0 @@
1
- import { format } from './format';
2
- import type { BasePromptTemplateOptions, ChatMessage, PromptTemplateOptions } from './types';
3
-
4
- export abstract class BasePromptTemplate<const TemplatesVar extends readonly string[] = string[]> {
5
- templateVars: Set<string> = new Set();
6
- options: Partial<Record<TemplatesVar[number] | (string & {}), string>> = {};
7
-
8
- protected constructor(options: BasePromptTemplateOptions<TemplatesVar>) {
9
- const { templateVars } = options;
10
- if (templateVars) {
11
- this.templateVars = new Set(templateVars);
12
- }
13
- if (options.options) {
14
- this.options = options.options;
15
- }
16
- }
17
-
18
- abstract partialFormat(
19
- options: Partial<Record<TemplatesVar[number] | (string & {}), string>>,
20
- ): BasePromptTemplate<TemplatesVar>;
21
-
22
- abstract format(options?: Partial<Record<TemplatesVar[number] | (string & {}), string>>): string;
23
-
24
- abstract formatMessages(options?: Partial<Record<TemplatesVar[number] | (string & {}), string>>): ChatMessage[];
25
-
26
- abstract get template(): string;
27
- }
28
-
29
- export class PromptTemplate<
30
- const TemplatesVar extends readonly string[] = string[],
31
- > extends BasePromptTemplate<TemplatesVar> {
32
- #template: string;
33
-
34
- constructor(options: PromptTemplateOptions<TemplatesVar>) {
35
- const { template, ...rest } = options;
36
- super(rest);
37
- this.#template = template;
38
- }
39
-
40
- partialFormat(options: Partial<Record<TemplatesVar[number] | (string & {}), string>>): PromptTemplate<TemplatesVar> {
41
- const prompt = new PromptTemplate({
42
- template: this.template,
43
- templateVars: [...this.templateVars],
44
- options: this.options,
45
- });
46
-
47
- prompt.options = {
48
- ...prompt.options,
49
- ...options,
50
- };
51
-
52
- return prompt;
53
- }
54
-
55
- format(options?: Partial<Record<TemplatesVar[number] | (string & {}), string>>): string {
56
- const allOptions = {
57
- ...this.options,
58
- ...options,
59
- } as Record<TemplatesVar[number], string>;
60
-
61
- return format(this.template, allOptions);
62
- }
63
-
64
- formatMessages(options?: Partial<Record<TemplatesVar[number] | (string & {}), string>>): ChatMessage[] {
65
- const prompt = this.format(options);
66
- return [
67
- {
68
- role: 'user',
69
- content: prompt,
70
- },
71
- ];
72
- }
73
-
74
- get template(): string {
75
- return this.#template;
76
- }
77
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Formats a string by replacing placeholders with values from the provided parameters.
3
- * @param str The string to format.
4
- * @param params A record of placeholder names to their corresponding values.
5
- * @returns The formatted string.
6
- */
7
- export function format(str: string, params: Record<string, string>) {
8
- return str.replace(/{(\w+)}/g, (_, k) => params[k] ?? '');
9
- }
@@ -1,15 +0,0 @@
1
- export { BasePromptTemplate, PromptTemplate } from './base';
2
- export {
3
- defaultKeywordExtractPrompt,
4
- defaultQuestionExtractPrompt,
5
- defaultSummaryPrompt,
6
- defaultTitleCombinePromptTemplate,
7
- defaultTitleExtractorPromptTemplate,
8
- } from './prompt';
9
- export type {
10
- KeywordExtractPrompt,
11
- QuestionExtractPrompt,
12
- SummaryPrompt,
13
- TitleCombinePrompt,
14
- TitleExtractorPrompt,
15
- } from './prompt';
@@ -1,60 +0,0 @@
1
- import { PromptTemplate } from './base';
2
-
3
- export type SummaryPrompt = PromptTemplate<['context']>;
4
- export type KeywordExtractPrompt = PromptTemplate<['context', 'maxKeywords']>;
5
- export type QuestionExtractPrompt = PromptTemplate<['context', 'numQuestions']>;
6
- export type TitleExtractorPrompt = PromptTemplate<['context']>;
7
- export type TitleCombinePrompt = PromptTemplate<['context']>;
8
-
9
- export const defaultSummaryPrompt: SummaryPrompt = new PromptTemplate({
10
- templateVars: ['context'],
11
- template: `Write a summary of the following. Try to use only the information provided. Try to include as many key details as possible.
12
-
13
-
14
- {context}
15
-
16
-
17
- SUMMARY:"""
18
- `,
19
- });
20
-
21
- export const defaultKeywordExtractPrompt: KeywordExtractPrompt = new PromptTemplate({
22
- templateVars: ['maxKeywords', 'context'],
23
- template: `
24
- Some text is provided below. Given the text, extract up to {maxKeywords} keywords from the text. Avoid stopwords.
25
- ---------------------
26
- {context}
27
- ---------------------
28
- Provide keywords in the following comma-separated format: 'KEYWORDS: <keywords>'
29
- `,
30
- }).partialFormat({
31
- maxKeywords: '10',
32
- });
33
-
34
- export const defaultQuestionExtractPrompt = new PromptTemplate({
35
- templateVars: ['numQuestions', 'context'],
36
- template: `(
37
- "Given the contextual informations below, generate {numQuestions} questions this context can provides specific answers to which are unlikely to be found else where. Higher-level summaries of surrounding context may be provided as well. "
38
- "Try using these summaries to generate better questions that this context can answer."
39
- "---------------------"
40
- "{context}"
41
- "---------------------"
42
- "Provide questions in the following format: 'QUESTIONS: <questions>'"
43
- )`,
44
- }).partialFormat({
45
- numQuestions: '5',
46
- });
47
-
48
- export const defaultTitleExtractorPromptTemplate = new PromptTemplate({
49
- templateVars: ['context'],
50
- template: `{context}
51
- Give a title that summarizes all of the unique entities, titles or themes found in the context.
52
- Title: `,
53
- });
54
-
55
- export const defaultTitleCombinePromptTemplate = new PromptTemplate({
56
- templateVars: ['context'],
57
- template: `{context}
58
- Based on the above candidate titles and contents, what is the comprehensive title for this document?
59
- Title: `,
60
- });
@@ -1,29 +0,0 @@
1
- export type MessageType = 'user' | 'assistant' | 'system' | 'memory' | 'developer';
2
-
3
- export type MessageContentTextDetail = {
4
- type: 'text';
5
- text: string;
6
- };
7
-
8
- /**
9
- * Extended type for the content of a message that allows for multi-modal messages.
10
- */
11
- export type MessageContent = string | MessageContentTextDetail[];
12
-
13
- export type ChatMessage<AdditionalMessageOptions extends object = object> = {
14
- content: MessageContent;
15
- role: MessageType;
16
- options?: undefined | AdditionalMessageOptions;
17
- };
18
-
19
- export type BasePromptTemplateOptions<TemplatesVar extends readonly string[]> = {
20
- templateVars?:
21
- | TemplatesVar
22
- // loose type for better type inference
23
- | readonly string[];
24
- options?: Partial<Record<TemplatesVar[number] | (string & {}), string>>;
25
- };
26
-
27
- export type PromptTemplateOptions<TemplatesVar extends readonly string[]> = BasePromptTemplateOptions<TemplatesVar> & {
28
- template: string;
29
- };
@@ -1,3 +0,0 @@
1
- export { BaseNode, Document, TextNode } from './node';
2
- export { NodeRelationship, ObjectType } from './types';
3
- export type { Metadata, RelatedNodeInfo, RelatedNodeType, BaseNodeParams, TextNodeParams } from './types';
@@ -1,187 +0,0 @@
1
- import { createHash, randomUUID } from 'crypto';
2
- import { NodeRelationship, ObjectType } from './types';
3
- import type { Metadata, RelatedNodeInfo, RelatedNodeType, BaseNodeParams, TextNodeParams } from './types';
4
-
5
- /**
6
- * Generic abstract class for retrievable nodes
7
- */
8
- export abstract class BaseNode<T extends Metadata = Metadata> {
9
- id_: string;
10
- metadata: T;
11
- relationships: Partial<Record<NodeRelationship, RelatedNodeType<T>>>;
12
-
13
- @lazyInitHash
14
- accessor hash: string = '';
15
-
16
- protected constructor(init?: BaseNodeParams<T>) {
17
- const { id_, metadata, relationships } = init || {};
18
- this.id_ = id_ ?? randomUUID();
19
- this.metadata = metadata ?? ({} as T);
20
- this.relationships = relationships ?? {};
21
- }
22
-
23
- abstract get type(): ObjectType;
24
-
25
- abstract getContent(): string;
26
-
27
- abstract getMetadataStr(): string;
28
-
29
- get sourceNode(): RelatedNodeInfo<T> | undefined {
30
- const relationship = this.relationships[NodeRelationship.SOURCE];
31
-
32
- if (Array.isArray(relationship)) {
33
- throw new Error('Source object must be a single RelatedNodeInfo object');
34
- }
35
-
36
- return relationship;
37
- }
38
-
39
- get prevNode(): RelatedNodeInfo<T> | undefined {
40
- const relationship = this.relationships[NodeRelationship.PREVIOUS];
41
-
42
- if (Array.isArray(relationship)) {
43
- throw new Error('Previous object must be a single RelatedNodeInfo object');
44
- }
45
-
46
- return relationship;
47
- }
48
-
49
- get nextNode(): RelatedNodeInfo<T> | undefined {
50
- const relationship = this.relationships[NodeRelationship.NEXT];
51
-
52
- if (Array.isArray(relationship)) {
53
- throw new Error('Next object must be a single RelatedNodeInfo object');
54
- }
55
-
56
- return relationship;
57
- }
58
-
59
- get parentNode(): RelatedNodeInfo<T> | undefined {
60
- const relationship = this.relationships[NodeRelationship.PARENT];
61
-
62
- if (Array.isArray(relationship)) {
63
- throw new Error('Parent object must be a single RelatedNodeInfo object');
64
- }
65
-
66
- return relationship;
67
- }
68
-
69
- get childNodes(): RelatedNodeInfo<T>[] | undefined {
70
- const relationship = this.relationships[NodeRelationship.CHILD];
71
-
72
- if (!Array.isArray(relationship)) {
73
- throw new Error('Child object must be a an array of RelatedNodeInfo objects');
74
- }
75
-
76
- return relationship;
77
- }
78
-
79
- abstract generateHash(): string;
80
- }
81
-
82
- /**
83
- * TextNode is the default node type for text.
84
- */
85
- export class TextNode<T extends Metadata = Metadata> extends BaseNode<T> {
86
- text: string;
87
-
88
- startCharIdx?: number;
89
- endCharIdx?: number;
90
- metadataSeparator: string;
91
-
92
- constructor(init: TextNodeParams<T> = {}) {
93
- super(init);
94
- const { text, startCharIdx, endCharIdx, metadataSeparator } = init;
95
- this.text = text ?? '';
96
- if (startCharIdx) {
97
- this.startCharIdx = startCharIdx;
98
- }
99
- if (endCharIdx) {
100
- this.endCharIdx = endCharIdx;
101
- }
102
- this.metadataSeparator = metadataSeparator ?? '\n';
103
- }
104
-
105
- /**
106
- * Generate a hash of the text node.
107
- * The ID is not part of the hash as it can change independent of content.
108
- * @returns
109
- */
110
- generateHash() {
111
- const hashFunction = createSHA256();
112
- hashFunction.update(`type=${this.type}`);
113
- hashFunction.update(`startCharIdx=${this.startCharIdx} endCharIdx=${this.endCharIdx}`);
114
- hashFunction.update(this.getContent());
115
- return hashFunction.digest();
116
- }
117
-
118
- get type() {
119
- return ObjectType.TEXT;
120
- }
121
-
122
- getContent(): string {
123
- const metadataStr = this.getMetadataStr().trim();
124
- return `${metadataStr}\n\n${this.text}`.trim();
125
- }
126
-
127
- getMetadataStr(): string {
128
- const usableMetadataKeys = new Set(Object.keys(this.metadata).sort());
129
-
130
- return [...usableMetadataKeys].map(key => `${key}: ${this.metadata[key]}`).join(this.metadataSeparator);
131
- }
132
-
133
- getNodeInfo() {
134
- return { start: this.startCharIdx, end: this.endCharIdx };
135
- }
136
-
137
- getText() {
138
- return this.text;
139
- }
140
- }
141
-
142
- /**
143
- * A document is just a special text node with a docId.
144
- */
145
- export class Document<T extends Metadata = Metadata> extends TextNode<T> {
146
- constructor(init?: TextNodeParams<T>) {
147
- super(init);
148
- }
149
-
150
- get type() {
151
- return ObjectType.DOCUMENT;
152
- }
153
- }
154
-
155
- function lazyInitHash(
156
- value: ClassAccessorDecoratorTarget<BaseNode, string>,
157
- _context: ClassAccessorDecoratorContext,
158
- ): ClassAccessorDecoratorResult<BaseNode, string> {
159
- return {
160
- get() {
161
- const oldValue = value.get.call(this);
162
- if (oldValue === '') {
163
- const hash = this.generateHash();
164
- value.set.call(this, hash);
165
- }
166
- return value.get.call(this);
167
- },
168
- set(newValue: string) {
169
- value.set.call(this, newValue);
170
- },
171
- init(value: string): string {
172
- return value;
173
- },
174
- };
175
- }
176
-
177
- function createSHA256() {
178
- const hash = createHash('sha256');
179
- return {
180
- update(data: string | Uint8Array): void {
181
- hash.update(data);
182
- },
183
- digest() {
184
- return hash.digest('base64');
185
- },
186
- };
187
- }
@@ -1,40 +0,0 @@
1
- export enum NodeRelationship {
2
- SOURCE = 'SOURCE',
3
- PREVIOUS = 'PREVIOUS',
4
- NEXT = 'NEXT',
5
- PARENT = 'PARENT',
6
- CHILD = 'CHILD',
7
- }
8
-
9
- export enum ObjectType {
10
- TEXT = 'TEXT',
11
- IMAGE = 'IMAGE',
12
- INDEX = 'INDEX',
13
- DOCUMENT = 'DOCUMENT',
14
- IMAGE_DOCUMENT = 'IMAGE_DOCUMENT',
15
- }
16
-
17
- export type Metadata = Record<string, any>;
18
-
19
- export interface RelatedNodeInfo<T extends Metadata = Metadata> {
20
- nodeId: string;
21
- nodeType?: ObjectType;
22
- metadata: T;
23
- hash?: string;
24
- }
25
-
26
- export type RelatedNodeType<T extends Metadata = Metadata> = RelatedNodeInfo<T> | RelatedNodeInfo<T>[];
27
-
28
- export type BaseNodeParams<T extends Metadata = Metadata> = {
29
- id_?: string | undefined;
30
- metadata?: T | undefined;
31
- relationships?: Partial<Record<NodeRelationship, RelatedNodeType<T>>> | undefined;
32
- hash?: string | undefined;
33
- };
34
-
35
- export type TextNodeParams<T extends Metadata = Metadata> = BaseNodeParams<T> & {
36
- text?: string | undefined;
37
- startCharIdx?: number | undefined;
38
- endCharIdx?: number | undefined;
39
- metadataSeparator?: string | undefined;
40
- };