| 79 | } |
| 80 | |
| 81 | export class MemoryBackend { |
| 82 | constructor(options = {}) { |
| 83 | this.name = options.name || 'default'; |
| 84 | this.dimension = options.dimension || null; |
| 85 | this.metric = normalizeMetric(options.metric); |
| 86 | this.normalizeVectors = options.normalize ?? (this.metric === 'cosine'); |
| 87 | this.size = 0; |
| 88 | this.capacity = ensurePositiveInteger(options.capacity, 128); |
| 89 | this.ids = new Array(this.capacity); |
| 90 | this.metadata = new Array(this.capacity); |
| 91 | this.vectors = null; |
| 92 | this.idToIndex = new Map(); |
| 93 | } |
| 94 | |
| 95 | async init(options = {}) { |
| 96 | if (options.dimension) { |
| 97 | this.dimension = options.dimension; |
| 98 | } |
| 99 | if (!this.dimension || this.dimension <= 0) { |
| 100 | throw new Error('Vector dimension must be provided.'); |
| 101 | } |
| 102 | this.metric = normalizeMetric(options.metric || this.metric); |
| 103 | this.normalizeVectors = options.normalize ?? this.normalizeVectors ?? (this.metric === 'cosine'); |
| 104 | if (!this.vectors || this.vectors.length !== this.capacity * this.dimension) { |
| 105 | this.vectors = new Float32Array(this.capacity * this.dimension); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | prepareItems(items) { |
| 110 | const prepared = []; |
| 111 | for (const item of items) { |
| 112 | if (!item) continue; |
| 113 | const id = toId(item.id); |
| 114 | const vector = prepareVector(item.vector, this.dimension, this.normalizeVectors); |
| 115 | prepared.push({ |
| 116 | id, |
| 117 | vector, |
| 118 | metadata: item.metadata ?? null |
| 119 | }); |
| 120 | } |
| 121 | return prepared; |
| 122 | } |
| 123 | |
| 124 | upsertPrepared(preparedItems) { |
| 125 | for (const item of preparedItems) { |
| 126 | const existingIndex = this.idToIndex.get(item.id); |
| 127 | if (existingIndex !== undefined) { |
| 128 | this._writeVector(existingIndex, item.vector); |
| 129 | this.metadata[existingIndex] = item.metadata; |
| 130 | continue; |
| 131 | } |
| 132 | |
| 133 | const index = this.size; |
| 134 | this._ensureCapacity(index + 1); |
| 135 | this.ids[index] = item.id; |
| 136 | this.metadata[index] = item.metadata; |
| 137 | this.idToIndex.set(item.id, index); |
| 138 | this._writeVector(index, item.vector); |
nothing calls this directly
no outgoing calls
no test coverage detected