@mastra/turbopuffer 0.0.0-vector-sources-20250516175436 → 0.0.0-vector-extension-schema-20250922130418

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.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
1
2
  import { MastraVector } from '@mastra/core/vector';
2
3
  import { Turbopuffer } from '@turbopuffer/turbopuffer';
3
4
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
@@ -186,28 +187,40 @@ var TurbopufferVector = class extends MastraVector {
186
187
  }
187
188
  async createIndex({ indexName, dimension, metric }) {
188
189
  metric = metric ?? "cosine";
189
- if (this.createIndexCache.has(indexName)) {
190
- const expected = this.createIndexCache.get(indexName);
191
- if (dimension !== expected.dimension || metric !== expected.metric) {
192
- throw new Error(
193
- `createIndex() called more than once with inconsistent inputs. Index ${indexName} expected dimensions=${expected.dimension} and metric=${expected.metric} but got dimensions=${dimension} and metric=${metric}`
194
- );
195
- }
196
- return;
197
- }
198
- if (dimension <= 0) {
199
- throw new Error("Dimension must be a positive integer");
200
- }
201
190
  let distanceMetric = "cosine_distance";
202
- switch (metric) {
203
- case "cosine":
204
- distanceMetric = "cosine_distance";
205
- break;
206
- case "euclidean":
207
- distanceMetric = "euclidean_squared";
208
- break;
209
- case "dotproduct":
210
- throw new Error("dotproduct is not supported in Turbopuffer");
191
+ try {
192
+ if (this.createIndexCache.has(indexName)) {
193
+ const expected = this.createIndexCache.get(indexName);
194
+ if (dimension !== expected.dimension || metric !== expected.metric) {
195
+ throw new Error(
196
+ `createIndex() called more than once with inconsistent inputs. Index ${indexName} expected dimensions=${expected.dimension} and metric=${expected.metric} but got dimensions=${dimension} and metric=${metric}`
197
+ );
198
+ }
199
+ return;
200
+ }
201
+ if (dimension <= 0) {
202
+ throw new Error("Dimension must be a positive integer");
203
+ }
204
+ switch (metric) {
205
+ case "cosine":
206
+ distanceMetric = "cosine_distance";
207
+ break;
208
+ case "euclidean":
209
+ distanceMetric = "euclidean_squared";
210
+ break;
211
+ case "dotproduct":
212
+ throw new Error("dotproduct is not supported in Turbopuffer");
213
+ }
214
+ } catch (error) {
215
+ throw new MastraError(
216
+ {
217
+ id: "STORAGE_TURBOBUFFER_VECTOR_CREATE_INDEX_INVALID_ARGS",
218
+ domain: ErrorDomain.STORAGE,
219
+ category: ErrorCategory.USER,
220
+ details: { indexName, dimension, metric }
221
+ },
222
+ error
223
+ );
211
224
  }
212
225
  this.createIndexCache.set(indexName, {
213
226
  indexName,
@@ -217,15 +230,29 @@ var TurbopufferVector = class extends MastraVector {
217
230
  });
218
231
  }
219
232
  async upsert({ indexName, vectors, metadata, ids }) {
233
+ let index;
234
+ let createIndex;
220
235
  try {
221
236
  if (vectors.length === 0) {
222
237
  throw new Error("upsert() called with empty vectors");
223
238
  }
224
- const index = this.client.namespace(indexName);
225
- const createIndex = this.createIndexCache.get(indexName);
239
+ index = this.client.namespace(indexName);
240
+ createIndex = this.createIndexCache.get(indexName);
226
241
  if (!createIndex) {
227
242
  throw new Error(`createIndex() not called for this index`);
228
243
  }
244
+ } catch (error) {
245
+ throw new MastraError(
246
+ {
247
+ id: "STORAGE_TURBOBUFFER_VECTOR_UPSERT_INVALID_ARGS",
248
+ domain: ErrorDomain.STORAGE,
249
+ category: ErrorCategory.USER,
250
+ details: { indexName }
251
+ },
252
+ error
253
+ );
254
+ }
255
+ try {
229
256
  const distanceMetric = createIndex.tpufDistanceMetric;
230
257
  const vectorIds = ids || vectors.map(() => crypto.randomUUID());
231
258
  const records = vectors.map((vector, i) => ({
@@ -253,21 +280,48 @@ var TurbopufferVector = class extends MastraVector {
253
280
  }
254
281
  return vectorIds;
255
282
  } catch (error) {
256
- throw new Error(`Failed to upsert vectors into Turbopuffer namespace ${indexName}: ${error}`);
283
+ throw new MastraError(
284
+ {
285
+ id: "STORAGE_TURBOBUFFER_VECTOR_UPSERT_FAILED",
286
+ domain: ErrorDomain.STORAGE,
287
+ category: ErrorCategory.THIRD_PARTY,
288
+ details: { indexName }
289
+ },
290
+ error
291
+ );
257
292
  }
258
293
  }
259
- async query({ indexName, queryVector, topK, filter, includeVector }) {
260
- const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
261
- if (schemaConfig) {
262
- if (queryVector.length !== schemaConfig.dimensions) {
263
- throw new Error(
264
- `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to query with queryVector.length=${queryVector.length}`
265
- );
294
+ async query({
295
+ indexName,
296
+ queryVector,
297
+ topK,
298
+ filter,
299
+ includeVector
300
+ }) {
301
+ let createIndex;
302
+ try {
303
+ const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
304
+ if (schemaConfig) {
305
+ if (queryVector.length !== schemaConfig.dimensions) {
306
+ throw new Error(
307
+ `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to query with queryVector.length=${queryVector.length}`
308
+ );
309
+ }
266
310
  }
267
- }
268
- const createIndex = this.createIndexCache.get(indexName);
269
- if (!createIndex) {
270
- throw new Error(`createIndex() not called for this index`);
311
+ createIndex = this.createIndexCache.get(indexName);
312
+ if (!createIndex) {
313
+ throw new Error(`createIndex() not called for this index`);
314
+ }
315
+ } catch (error) {
316
+ throw new MastraError(
317
+ {
318
+ id: "STORAGE_TURBOBUFFER_VECTOR_QUERY_INVALID_ARGS",
319
+ domain: ErrorDomain.STORAGE,
320
+ category: ErrorCategory.USER,
321
+ details: { indexName }
322
+ },
323
+ error
324
+ );
271
325
  }
272
326
  const distanceMetric = createIndex.tpufDistanceMetric;
273
327
  try {
@@ -290,7 +344,15 @@ var TurbopufferVector = class extends MastraVector {
290
344
  ...includeVector && item.vector ? { vector: item.vector } : {}
291
345
  }));
292
346
  } catch (error) {
293
- throw new Error(`Failed to query Turbopuffer namespace ${indexName}: ${error}`);
347
+ throw new MastraError(
348
+ {
349
+ id: "STORAGE_TURBOBUFFER_VECTOR_QUERY_FAILED",
350
+ domain: ErrorDomain.STORAGE,
351
+ category: ErrorCategory.THIRD_PARTY,
352
+ details: { indexName }
353
+ },
354
+ error
355
+ );
294
356
  }
295
357
  }
296
358
  async listIndexes() {
@@ -298,19 +360,23 @@ var TurbopufferVector = class extends MastraVector {
298
360
  const namespacesResult = await this.client.namespaces({});
299
361
  return namespacesResult.namespaces.map((namespace) => namespace.id);
300
362
  } catch (error) {
301
- throw new Error(`Failed to list Turbopuffer namespaces: ${error}`);
363
+ throw new MastraError(
364
+ {
365
+ id: "STORAGE_TURBOBUFFER_VECTOR_LIST_INDEXES_FAILED",
366
+ domain: ErrorDomain.STORAGE,
367
+ category: ErrorCategory.THIRD_PARTY
368
+ },
369
+ error
370
+ );
302
371
  }
303
372
  }
304
373
  /**
305
374
  * Retrieves statistics about a vector index.
306
375
  *
307
- * @param params - The parameters for describing an index
308
- * @param params.indexName - The name of the index to describe
376
+ * @param {string} indexName - The name of the index to describe
309
377
  * @returns A promise that resolves to the index statistics including dimension, count and metric
310
378
  */
311
- async describeIndex(...args) {
312
- const params = this.normalizeArgs("describeIndex", args);
313
- const { indexName } = params;
379
+ async describeIndex({ indexName }) {
314
380
  try {
315
381
  const namespace = this.client.namespace(indexName);
316
382
  const metadata = await namespace.metadata();
@@ -326,18 +392,32 @@ var TurbopufferVector = class extends MastraVector {
326
392
  metric: createIndex.metric
327
393
  };
328
394
  } catch (error) {
329
- throw new Error(`Failed to describe Turbopuffer namespace ${indexName}: ${error}`);
395
+ throw new MastraError(
396
+ {
397
+ id: "STORAGE_TURBOBUFFER_VECTOR_DESCRIBE_INDEX_FAILED",
398
+ domain: ErrorDomain.STORAGE,
399
+ category: ErrorCategory.THIRD_PARTY,
400
+ details: { indexName }
401
+ },
402
+ error
403
+ );
330
404
  }
331
405
  }
332
- async deleteIndex(...args) {
333
- const params = this.normalizeArgs("deleteIndex", args);
334
- const { indexName } = params;
406
+ async deleteIndex({ indexName }) {
335
407
  try {
336
408
  const namespace = this.client.namespace(indexName);
337
409
  await namespace.deleteAll();
338
410
  this.createIndexCache.delete(indexName);
339
411
  } catch (error) {
340
- throw new Error(`Failed to delete Turbopuffer namespace ${indexName}: ${error.message}`);
412
+ throw new MastraError(
413
+ {
414
+ id: "STORAGE_TURBOBUFFER_VECTOR_DELETE_INDEX_FAILED",
415
+ domain: ErrorDomain.STORAGE,
416
+ category: ErrorCategory.THIRD_PARTY,
417
+ details: { indexName }
418
+ },
419
+ error
420
+ );
341
421
  }
342
422
  }
343
423
  /**
@@ -350,25 +430,47 @@ var TurbopufferVector = class extends MastraVector {
350
430
  * @returns A promise that resolves when the update is complete.
351
431
  * @throws Will throw an error if no updates are provided or if the update operation fails.
352
432
  */
353
- async updateVector(...args) {
354
- const params = this.normalizeArgs("updateVector", args);
355
- const { indexName, id, update } = params;
433
+ async updateVector({ indexName, id, update }) {
434
+ let namespace;
435
+ let createIndex;
436
+ let distanceMetric;
437
+ let record;
356
438
  try {
357
- const namespace = this.client.namespace(indexName);
358
- const createIndex = this.createIndexCache.get(indexName);
439
+ namespace = this.client.namespace(indexName);
440
+ createIndex = this.createIndexCache.get(indexName);
359
441
  if (!createIndex) {
360
442
  throw new Error(`createIndex() not called for this index`);
361
443
  }
362
- const distanceMetric = createIndex.tpufDistanceMetric;
363
- const record = { id };
444
+ distanceMetric = createIndex.tpufDistanceMetric;
445
+ record = { id };
364
446
  if (update.vector) record.vector = update.vector;
365
447
  if (update.metadata) record.attributes = update.metadata;
448
+ } catch (error) {
449
+ throw new MastraError(
450
+ {
451
+ id: "STORAGE_TURBOBUFFER_VECTOR_UPDATE_VECTOR_INVALID_ARGS",
452
+ domain: ErrorDomain.STORAGE,
453
+ category: ErrorCategory.USER,
454
+ details: { indexName }
455
+ },
456
+ error
457
+ );
458
+ }
459
+ try {
366
460
  await namespace.upsert({
367
461
  vectors: [record],
368
462
  distance_metric: distanceMetric
369
463
  });
370
464
  } catch (error) {
371
- throw new Error(`Failed to update Turbopuffer namespace ${indexName}: ${error.message}`);
465
+ throw new MastraError(
466
+ {
467
+ id: "STORAGE_TURBOBUFFER_VECTOR_UPDATE_VECTOR_FAILED",
468
+ domain: ErrorDomain.STORAGE,
469
+ category: ErrorCategory.THIRD_PARTY,
470
+ details: { indexName }
471
+ },
472
+ error
473
+ );
372
474
  }
373
475
  }
374
476
  /**
@@ -378,16 +480,24 @@ var TurbopufferVector = class extends MastraVector {
378
480
  * @returns A promise that resolves when the deletion is complete.
379
481
  * @throws Will throw an error if the deletion operation fails.
380
482
  */
381
- async deleteVector(...args) {
382
- const params = this.normalizeArgs("deleteVector", args);
383
- const { indexName, id } = params;
483
+ async deleteVector({ indexName, id }) {
384
484
  try {
385
485
  const namespace = this.client.namespace(indexName);
386
486
  await namespace.delete({ ids: [id] });
387
487
  } catch (error) {
388
- throw new Error(`Failed to delete Turbopuffer namespace ${indexName}: ${error.message}`);
488
+ throw new MastraError(
489
+ {
490
+ id: "STORAGE_TURBOBUFFER_VECTOR_DELETE_VECTOR_FAILED",
491
+ domain: ErrorDomain.STORAGE,
492
+ category: ErrorCategory.THIRD_PARTY,
493
+ details: { indexName }
494
+ },
495
+ error
496
+ );
389
497
  }
390
498
  }
391
499
  };
392
500
 
393
501
  export { TurbopufferVector };
502
+ //# sourceMappingURL=index.js.map
503
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vector/filter.ts","../src/vector/index.ts"],"names":["op"],"mappings":";;;;;;AA6BO,IAAM,2BAAA,GAAN,cAA0C,oBAAA,CAAmE;AAAA,EAC/F,qBAAA,GAAyC;AAC1D,IAAA,OAAO;AAAA,MACL,GAAG,oBAAA,CAAqB,iBAAA;AAAA,MACxB,OAAA,EAAS,CAAC,MAAA,EAAQ,KAAK,CAAA;AAAA,MACvB,KAAA,EAAO,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAM,CAAA;AAAA,MAC7B,OAAA,EAAS,CAAC,SAAS,CAAA;AAAA,MACnB,OAAO,EAAC;AAAA;AAAA,MACR,Q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tC,SAAS,KAAA,EAAY;AACnB,MAAA,MAAM,IAAI,WAAA;AAAA,QACR;AAAA,UACE,EAAA,EAAI,iDAAA;AAAA,UACJ,QAAQ,WAAA,CAAY,OAAA;AAAA,UACpB,UAAU,aAAA,CAAc,WAAA;AAAA,UACxB,OAAA,EAAS,EAAE,SAAA;AAAU,SACvB;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type {\n OperatorSupport,\n VectorFilter,\n OperatorValueMap,\n LogicalOperatorValueMap,\n BlacklistedRootOperators,\n} from '@mastra/core/vector/filter';\nimport { BaseFilterTranslator } from '@mastra/core/vector/filter';\nimport type { FilterCondition, FilterConnective, FilterOperator, Filters } from '@turbopuffer/turbopuffer';\n\ntype TurbopufferOperatorValueMap = Omit<OperatorValueMap, '$regex' | '$options' | '$elemMatch'>;\n\ntype TurbopufferLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor' | '$not'>;\n\ntype TurbopufferBlacklistedRootOperators = BlacklistedRootOperators | '$nor' | '$not';\n\nexport type TurbopufferVectorFilter = VectorFilter<\n keyof TurbopufferOperatorValueMap,\n TurbopufferOperatorValueMap,\n TurbopufferLogicalOperatorValueMap,\n TurbopufferBlacklistedRootOperators\n>;\n\n/**\n * Translator for converting Mastra filters to Turbopuffer format\n *\n * Mastra filters: { field: { $gt: 10 } }\n * Turbopuffer filters: [\"And\", [[\"field\", \"Gt\", 10]]]\n */\nexport class TurbopufferFilterTranslator extends BaseFilterTranslator<TurbopufferVectorFilter, Filters | undefined> {\n protected override getSupportedOperators(): OperatorSupport {\n return {\n ...BaseFilterTranslator.DEFAULT_OPERATORS,\n logical: ['$and', '$or'],\n array: ['$in', '$nin', '$all'],\n element: ['$exists'],\n regex: [], // No regex support in Turbopuffer\n custom: [], // No custom operators\n };\n }\n\n /**\n * Map Mastra operators to Turbopuffer operators\n */\n private operatorMap: Record<string, FilterOperator> = {\n $eq: 'Eq',\n $ne: 'NotEq',\n $gt: 'Gt',\n $gte: 'Gte',\n $lt: 'Lt',\n $lte: 'Lte',\n $in: 'In',\n $nin: 'NotIn',\n };\n\n /**\n * Convert the Mastra filter to Turbopuffer format\n */\n translate(filter?: TurbopufferVectorFilter): Filters | undefined {\n if (this.isEmpty(filter)) {\n return undefined;\n }\n\n // Validate the filter structure before translating\n this.validateFilter(filter);\n\n // Translate the filter\n const result = this.translateNode(filter);\n\n // If we have a single condition (not a logical operator at the top level),\n // wrap it in an implicit AND to match Turbopuffer's expected format\n if (!Array.isArray(result) || result.length !== 2 || (result[0] !== 'And' && result[0] !== 'Or')) {\n return ['And', [result as FilterCondition]];\n }\n\n return result as Filters;\n }\n\n /**\n * Recursively translate a filter node\n */\n private translateNode(node: TurbopufferVectorFilter): Filters | FilterCondition {\n // Handle empty or null nodes\n if (node === null || node === undefined || Object.keys(node).length === 0) {\n return ['And', []];\n }\n\n // Handle primitive values (direct equality comparison)\n if (this.isPrimitive(node)) {\n throw new Error('Direct primitive values not valid in this context for Turbopuffer');\n }\n\n // Handle direct array value (convert to $in)\n if (Array.isArray(node)) {\n throw new Error('Direct array values not valid in this context for Turbopuffer');\n }\n\n const entries = Object.entries(node);\n\n // Process the first operator or field\n if (entries.length === 0) {\n return ['And', []];\n }\n\n const [key, value] = entries[0] as [string, any];\n\n // Handle logical operators\n if (key && this.isLogicalOperator(key)) {\n return this.translateLogical(key, value);\n }\n\n // Multiple fields at top level - implicit AND\n if (entries.length > 1) {\n const conditions = entries.map(([field, fieldValue]) => this.translateFieldCondition(field, fieldValue));\n return ['And', conditions];\n }\n\n // Single field with condition(s)\n return this.translateFieldCondition(key, value);\n }\n\n /**\n * Translate a field condition\n */\n private translateFieldCondition(field: string, value: any): FilterCondition {\n // Handle Date object directly (convert to ISO string)\n if (value instanceof Date) {\n return [field, 'Eq', this.normalizeValue(value)];\n }\n\n // Handle primitive value (direct equality)\n if (this.isPrimitive(value)) {\n return [field, 'Eq', this.normalizeValue(value)];\n }\n\n // Handle array value (convert to $in)\n if (Array.isArray(value)) {\n return [field, 'In', this.normalizeArrayValues(value)];\n }\n\n // Handle object with operators\n if (typeof value === 'object' && value !== null) {\n const operators = Object.keys(value);\n\n // If multiple operators for the same field, create an AND condition\n if (operators.length > 1) {\n // Check if all keys are operators\n const allOperators = operators.every(op => this.isOperator(op));\n if (allOperators) {\n // For multiple comparison operators on one field\n const conditions = operators.map(op => this.translateOperator(field, op, value[op]));\n return ['And', conditions] as unknown as FilterCondition;\n } else {\n // For nested objects with multiple fields\n const conditions = operators.map(op => {\n const nestedField = `${field}.${op}`;\n return this.translateFieldCondition(nestedField, value[op]);\n });\n return ['And', conditions] as unknown as FilterCondition;\n }\n }\n\n // Single operator\n const op = operators[0];\n if (op && this.isOperator(op)) {\n return this.translateOperator(field, op, value[op]);\n }\n\n // Nested field path (use dot notation)\n if (op && !this.isOperator(op)) {\n const nestedField = `${field}.${op}`;\n return this.translateFieldCondition(nestedField, value[op]);\n }\n }\n\n throw new Error(`Unsupported filter format for field: ${field}`);\n }\n\n /**\n * Translate a logical operator\n */\n private translateLogical(operator: string, conditions: any[]): Filters {\n // Map Mastra logical operators to Turbopuffer\n const logicalOp: FilterConnective = operator === '$and' ? 'And' : 'Or';\n\n // Validate conditions\n if (!Array.isArray(conditions)) {\n throw new Error(`Logical operator ${operator} requires an array of conditions`);\n }\n\n // Translate each condition\n const translatedConditions = conditions.map(condition => {\n if (typeof condition !== 'object' || condition === null) {\n throw new Error(`Invalid condition for logical operator ${operator}`);\n }\n return this.translateNode(condition);\n });\n\n return [logicalOp, translatedConditions];\n }\n\n /**\n * Translate a specific operator\n */\n private translateOperator(field: string, operator: string, value: any): FilterCondition {\n // Handle comparison operators\n if (operator && this.operatorMap[operator]) {\n return [field, this.operatorMap[operator], this.normalizeValue(value)];\n }\n\n // Handle special cases\n switch (operator) {\n case '$exists':\n // $exists: true -> use NotEq with null (field exists if it's not null)\n // $exists: false -> use Eq with null (field doesn't exist if it is null)\n return value ? [field, 'NotEq', null] : [field, 'Eq', null];\n\n case '$all':\n // $all is not directly supported, simulate with AND + IN conditions\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error('$all operator requires a non-empty array');\n }\n\n const allConditions = value.map(item => [field, 'In', [this.normalizeValue(item)]] as FilterCondition);\n\n // Return the array of conditions directly without nesting\n return ['And', allConditions] as unknown as FilterCondition;\n\n default:\n throw new Error(`Unsupported operator: ${operator || 'undefined'}`);\n }\n }\n\n /**\n * Normalize a value for comparison operations\n */\n protected normalizeValue(value: any): any {\n // Handle special value types\n if (value instanceof Date) {\n return value.toISOString();\n }\n return value;\n }\n\n /**\n * Normalize array values\n */\n protected normalizeArrayValues(values: any[]): any[] {\n return values.map(value => this.normalizeValue(value));\n }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport type {\n CreateIndexParams,\n DeleteIndexParams,\n DeleteVectorParams,\n DescribeIndexParams,\n IndexStats,\n QueryResult,\n QueryVectorParams,\n UpdateVectorParams,\n UpsertVectorParams,\n} from '@mastra/core/vector';\nimport { MastraVector } from '@mastra/core/vector';\nimport { Turbopuffer } from '@turbopuffer/turbopuffer';\nimport type { DistanceMetric, QueryResults, Schema, Vector } from '@turbopuffer/turbopuffer';\nimport { TurbopufferFilterTranslator } from './filter';\nimport type { TurbopufferVectorFilter } from './filter';\n\ntype TurbopufferQueryVectorParams = QueryVectorParams<TurbopufferVectorFilter>;\n\nexport interface TurbopufferVectorOptions {\n /** The API key to authenticate with. */\n apiKey: string;\n /** The base URL. Default is https://api.turbopuffer.com. */\n baseUrl?: string;\n /** The timeout to establish a connection, in ms. Default is 10_000. Only applicable in Node and Deno.*/\n connectTimeout?: number;\n /** The socket idle timeout, in ms. Default is 60_000. Only applicable in Node and Deno.*/\n connectionIdleTimeout?: number;\n /** The number of connections to open initially when creating a new client. Default is 0. */\n warmConnections?: number;\n /** Whether to compress requests and accept compressed responses. Default is true. */\n compression?: boolean;\n /**\n * A callback function that takes an index name and returns a config object for that index.\n * This allows you to define explicit schemas per index.\n *\n * Example:\n * ```typescript\n * schemaConfigForIndex: (indexName: string) => {\n * // Mastra's default embedding model and index for memory messages:\n * if (indexName === \"memory_messages_384\") {\n * return {\n * dimensions: 384,\n * schema: {\n * thread_id: {\n * type: \"string\",\n * filterable: true,\n * },\n * },\n * };\n * } else {\n * throw new Error(`TODO: add schema for index: ${indexName}`);\n * }\n * },\n * ```\n */\n schemaConfigForIndex?: (indexName: string) => {\n dimensions: number;\n schema: Schema;\n };\n}\n\nexport class TurbopufferVector extends MastraVector<TurbopufferVectorFilter> {\n private client: Turbopuffer;\n private filterTranslator: TurbopufferFilterTranslator;\n // There is no explicit create index operation in Turbopuffer, so just register that\n // someone has called createIndex() and verify that subsequent upsert calls are consistent\n // with how the index was \"created\"\n private createIndexCache: Map<\n string,\n CreateIndexParams & {\n tpufDistanceMetric: DistanceMetric;\n }\n > = new Map();\n private opts: TurbopufferVectorOptions;\n\n constructor(opts: TurbopufferVectorOptions) {\n super();\n this.filterTranslator = new TurbopufferFilterTranslator();\n this.opts = opts;\n\n const baseClient = new Turbopuffer(opts);\n const telemetry = this.__getTelemetry();\n this.client =\n telemetry?.traceClass(baseClient, {\n spanNamePrefix: 'turbopuffer-vector',\n attributes: {\n 'vector.type': 'turbopuffer',\n },\n }) ?? baseClient;\n }\n\n async createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void> {\n metric = metric ?? 'cosine'; // default to cosine distance\n let distanceMetric: DistanceMetric = 'cosine_distance';\n try {\n if (this.createIndexCache.has(indexName)) {\n // verify that the dimensions and distance metric match what we expect\n const expected = this.createIndexCache.get(indexName)!;\n if (dimension !== expected.dimension || metric !== expected.metric) {\n throw new Error(\n `createIndex() called more than once with inconsistent inputs. Index ${indexName} expected dimensions=${expected.dimension} and metric=${expected.metric} but got dimensions=${dimension} and metric=${metric}`,\n );\n }\n return;\n }\n if (dimension <= 0) {\n throw new Error('Dimension must be a positive integer');\n }\n switch (metric) {\n case 'cosine':\n distanceMetric = 'cosine_distance';\n break;\n case 'euclidean':\n distanceMetric = 'euclidean_squared';\n break;\n case 'dotproduct':\n throw new Error('dotproduct is not supported in Turbopuffer');\n }\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_CREATE_INDEX_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName, dimension, metric },\n },\n error,\n );\n }\n\n this.createIndexCache.set(indexName, {\n indexName,\n dimension,\n metric,\n tpufDistanceMetric: distanceMetric,\n });\n }\n\n async upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]> {\n let index;\n let createIndex;\n try {\n if (vectors.length === 0) {\n throw new Error('upsert() called with empty vectors');\n }\n\n index = this.client.namespace(indexName);\n createIndex = this.createIndexCache.get(indexName);\n if (!createIndex) {\n throw new Error(`createIndex() not called for this index`);\n }\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_UPSERT_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName },\n },\n error,\n );\n }\n\n try {\n const distanceMetric = createIndex.tpufDistanceMetric;\n const vectorIds = ids || vectors.map(() => crypto.randomUUID());\n const records: Vector[] = vectors.map((vector, i) => ({\n id: vectorIds[i]!,\n vector: vector,\n attributes: metadata?.[i] || {},\n }));\n\n // limit is 256 MB per upsert request, so set a reasonable batch size here that will stay under that for most cases\n // https://turbopuffer.com/docs/limits\n const batchSize = 100;\n for (let i = 0; i < records.length; i += batchSize) {\n const batch = records.slice(i, i + batchSize);\n const upsertOptions: {\n vectors: Vector[];\n distance_metric: DistanceMetric;\n schema?: Schema;\n batchSize?: number;\n } = {\n vectors: batch,\n distance_metric: distanceMetric,\n };\n\n // Use the schemaForIndex callback if provided\n const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);\n if (schemaConfig) {\n upsertOptions.schema = schemaConfig.schema;\n if (vectors[0]?.length !== schemaConfig.dimensions) {\n throw new Error(\n `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to upsert vectors[0].length=${vectors[0]?.length}`,\n );\n }\n }\n\n await index.upsert(upsertOptions);\n }\n\n return vectorIds;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_UPSERT_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n\n async query({\n indexName,\n queryVector,\n topK,\n filter,\n includeVector,\n }: TurbopufferQueryVectorParams): Promise<QueryResult[]> {\n let createIndex;\n try {\n const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);\n if (schemaConfig) {\n if (queryVector.length !== schemaConfig.dimensions) {\n throw new Error(\n `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to query with queryVector.length=${queryVector.length}`,\n );\n }\n }\n createIndex = this.createIndexCache.get(indexName);\n if (!createIndex) {\n throw new Error(`createIndex() not called for this index`);\n }\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_QUERY_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName },\n },\n error,\n );\n }\n\n const distanceMetric = createIndex.tpufDistanceMetric;\n try {\n const index = this.client.namespace(indexName);\n const translatedFilter = this.filterTranslator.translate(filter);\n const results: QueryResults = await index.query({\n distance_metric: distanceMetric,\n vector: queryVector,\n top_k: topK,\n filters: translatedFilter,\n include_vectors: includeVector,\n include_attributes: true,\n consistency: { level: 'strong' }, // todo: make this configurable somehow?\n });\n return results.map(item => ({\n id: String(item.id),\n score: typeof item.dist === 'number' ? item.dist : 0,\n metadata: item.attributes || {},\n ...(includeVector && item.vector ? { vector: item.vector } : {}),\n }));\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_QUERY_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n\n async listIndexes(): Promise<string[]> {\n try {\n const namespacesResult = await this.client.namespaces({});\n return namespacesResult.namespaces.map(namespace => namespace.id);\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_LIST_INDEXES_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n },\n error,\n );\n }\n }\n\n /**\n * Retrieves statistics about a vector index.\n *\n * @param {string} indexName - The name of the index to describe\n * @returns A promise that resolves to the index statistics including dimension, count and metric\n */\n async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {\n try {\n const namespace = this.client.namespace(indexName);\n const metadata = await namespace.metadata();\n const createIndex = this.createIndexCache.get(indexName);\n if (!createIndex) {\n throw new Error(`createIndex() not called for this index`);\n }\n const dimension = metadata.dimensions;\n const count = metadata.approx_count;\n return {\n dimension,\n count,\n metric: createIndex.metric,\n };\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_DESCRIBE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n\n async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {\n try {\n const namespace = this.client.namespace(indexName);\n await namespace.deleteAll();\n this.createIndexCache.delete(indexName);\n } catch (error: any) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_DELETE_INDEX_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n\n /**\n * Updates a vector by its ID with the provided vector and/or metadata.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to update.\n * @param update - An object containing the vector and/or metadata to update.\n * @param update.vector - An optional array of numbers representing the new vector.\n * @param update.metadata - An optional record containing the new metadata.\n * @returns A promise that resolves when the update is complete.\n * @throws Will throw an error if no updates are provided or if the update operation fails.\n */\n async updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void> {\n let namespace;\n let createIndex;\n let distanceMetric;\n let record;\n try {\n namespace = this.client.namespace(indexName);\n createIndex = this.createIndexCache.get(indexName);\n if (!createIndex) {\n throw new Error(`createIndex() not called for this index`);\n }\n distanceMetric = createIndex.tpufDistanceMetric;\n record = { id } as Vector;\n if (update.vector) record.vector = update.vector;\n if (update.metadata) record.attributes = update.metadata;\n } catch (error) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_UPDATE_VECTOR_INVALID_ARGS',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.USER,\n details: { indexName },\n },\n error,\n );\n }\n try {\n await namespace.upsert({\n vectors: [record],\n distance_metric: distanceMetric,\n });\n } catch (error: any) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_UPDATE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n\n /**\n * Deletes a vector by its ID.\n * @param indexName - The name of the index containing the vector.\n * @param id - The ID of the vector to delete.\n * @returns A promise that resolves when the deletion is complete.\n * @throws Will throw an error if the deletion operation fails.\n */\n async deleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {\n try {\n const namespace = this.client.namespace(indexName);\n await namespace.delete({ ids: [id] });\n } catch (error: any) {\n throw new MastraError(\n {\n id: 'STORAGE_TURBOBUFFER_VECTOR_DELETE_VECTOR_FAILED',\n domain: ErrorDomain.STORAGE,\n category: ErrorCategory.THIRD_PARTY,\n details: { indexName },\n },\n error,\n );\n }\n }\n}\n"]}
@@ -0,0 +1,50 @@
1
+ import type { OperatorSupport, VectorFilter, OperatorValueMap, LogicalOperatorValueMap, BlacklistedRootOperators } from '@mastra/core/vector/filter';
2
+ import { BaseFilterTranslator } from '@mastra/core/vector/filter';
3
+ import type { Filters } from '@turbopuffer/turbopuffer';
4
+ type TurbopufferOperatorValueMap = Omit<OperatorValueMap, '$regex' | '$options' | '$elemMatch'>;
5
+ type TurbopufferLogicalOperatorValueMap = Omit<LogicalOperatorValueMap, '$nor' | '$not'>;
6
+ type TurbopufferBlacklistedRootOperators = BlacklistedRootOperators | '$nor' | '$not';
7
+ export type TurbopufferVectorFilter = VectorFilter<keyof TurbopufferOperatorValueMap, TurbopufferOperatorValueMap, TurbopufferLogicalOperatorValueMap, TurbopufferBlacklistedRootOperators>;
8
+ /**
9
+ * Translator for converting Mastra filters to Turbopuffer format
10
+ *
11
+ * Mastra filters: { field: { $gt: 10 } }
12
+ * Turbopuffer filters: ["And", [["field", "Gt", 10]]]
13
+ */
14
+ export declare class TurbopufferFilterTranslator extends BaseFilterTranslator<TurbopufferVectorFilter, Filters | undefined> {
15
+ protected getSupportedOperators(): OperatorSupport;
16
+ /**
17
+ * Map Mastra operators to Turbopuffer operators
18
+ */
19
+ private operatorMap;
20
+ /**
21
+ * Convert the Mastra filter to Turbopuffer format
22
+ */
23
+ translate(filter?: TurbopufferVectorFilter): Filters | undefined;
24
+ /**
25
+ * Recursively translate a filter node
26
+ */
27
+ private translateNode;
28
+ /**
29
+ * Translate a field condition
30
+ */
31
+ private translateFieldCondition;
32
+ /**
33
+ * Translate a logical operator
34
+ */
35
+ private translateLogical;
36
+ /**
37
+ * Translate a specific operator
38
+ */
39
+ private translateOperator;
40
+ /**
41
+ * Normalize a value for comparison operations
42
+ */
43
+ protected normalizeValue(value: any): any;
44
+ /**
45
+ * Normalize array values
46
+ */
47
+ protected normalizeArrayValues(values: any[]): any[];
48
+ }
49
+ export {};
50
+ //# sourceMappingURL=filter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"filter.d.ts","sourceRoot":"","sources":["../../src/vector/filter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,uBAAuB,EACvB,wBAAwB,EACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,KAAK,EAAqD,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAE3G,KAAK,2BAA2B,GAAG,IAAI,CAAC,gBAAgB,EAAE,QAAQ,GAAG,UAAU,GAAG,YAAY,CAAC,CAAC;AAEhG,KAAK,kCAAkC,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;AAEzF,KAAK,mCAAmC,GAAG,wBAAwB,GAAG,MAAM,GAAG,MAAM,CAAC;AAEtF,MAAM,MAAM,uBAAuB,GAAG,YAAY,CAChD,MAAM,2BAA2B,EACjC,2BAA2B,EAC3B,kCAAkC,EAClC,mCAAmC,CACpC,CAAC;AAEF;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,oBAAoB,CAAC,uBAAuB,EAAE,OAAO,GAAG,SAAS,CAAC;cAC9F,qBAAqB,IAAI,eAAe;IAW3D;;OAEG;IACH,OAAO,CAAC,WAAW,CASjB;IAEF;;OAEG;IACH,SAAS,CAAC,MAAM,CAAC,EAAE,uBAAuB,GAAG,OAAO,GAAG,SAAS;IAoBhE;;OAEG;IACH,OAAO,CAAC,aAAa;IAwCrB;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAsD/B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAoBxB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IA6BzB;;OAEG;IACH,SAAS,CAAC,cAAc,CAAC,KAAK,EAAE,GAAG,GAAG,GAAG;IAQzC;;OAEG;IACH,SAAS,CAAC,oBAAoB,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,GAAG,EAAE;CAGrD"}
@@ -1,105 +1,9 @@
1
- import { BaseFilterTranslator } from '@mastra/core/vector/filter';
2
- import type { CreateIndexParams } from '@mastra/core/vector';
3
- import type { DeleteIndexParams } from '@mastra/core/vector';
4
- import type { DeleteVectorParams } from '@mastra/core/vector';
5
- import type { DescribeIndexParams } from '@mastra/core/vector';
6
- import type { Filters } from '@turbopuffer/turbopuffer';
7
- import type { IndexStats } from '@mastra/core/vector';
1
+ import type { CreateIndexParams, DeleteIndexParams, DeleteVectorParams, DescribeIndexParams, IndexStats, QueryResult, QueryVectorParams, UpdateVectorParams, UpsertVectorParams } from '@mastra/core/vector';
8
2
  import { MastraVector } from '@mastra/core/vector';
9
- import type { OperatorSupport } from '@mastra/core/vector/filter';
10
- import type { ParamsToArgs } from '@mastra/core/vector';
11
- import type { QueryResult } from '@mastra/core/vector';
12
- import type { QueryVectorParams } from '@mastra/core/vector';
13
3
  import type { Schema } from '@turbopuffer/turbopuffer';
14
- import type { UpdateVectorParams } from '@mastra/core/vector';
15
- import type { UpsertVectorParams } from '@mastra/core/vector';
16
- import type { VectorFilter } from '@mastra/core/vector/filter';
17
-
18
- /**
19
- * Translator for converting Mastra filters to Turbopuffer format
20
- *
21
- * Mastra filters: { field: { $gt: 10 } }
22
- * Turbopuffer filters: ["And", [["field", "Gt", 10]]]
23
- */
24
- export declare class TurbopufferFilterTranslator extends BaseFilterTranslator {
25
- protected getSupportedOperators(): OperatorSupport;
26
- /**
27
- * Map Mastra operators to Turbopuffer operators
28
- */
29
- private operatorMap;
30
- /**
31
- * Convert the Mastra filter to Turbopuffer format
32
- */
33
- translate(filter?: VectorFilter): Filters | undefined;
34
- /**
35
- * Recursively translate a filter node
36
- */
37
- private translateNode;
38
- /**
39
- * Translate a field condition
40
- */
41
- private translateFieldCondition;
42
- /**
43
- * Translate a logical operator
44
- */
45
- private translateLogical;
46
- /**
47
- * Translate a specific operator
48
- */
49
- private translateOperator;
50
- /**
51
- * Normalize a value for comparison operations
52
- */
53
- protected normalizeValue(value: any): any;
54
- /**
55
- * Normalize array values
56
- */
57
- protected normalizeArrayValues(values: any[]): any[];
58
- }
59
-
60
- declare class TurbopufferVector extends MastraVector {
61
- private client;
62
- private filterTranslator;
63
- private createIndexCache;
64
- private opts;
65
- constructor(opts: TurbopufferVectorOptions);
66
- createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
67
- upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
68
- query({ indexName, queryVector, topK, filter, includeVector }: QueryVectorParams): Promise<QueryResult[]>;
69
- listIndexes(): Promise<string[]>;
70
- /**
71
- * Retrieves statistics about a vector index.
72
- *
73
- * @param params - The parameters for describing an index
74
- * @param params.indexName - The name of the index to describe
75
- * @returns A promise that resolves to the index statistics including dimension, count and metric
76
- */
77
- describeIndex(...args: ParamsToArgs<DescribeIndexParams>): Promise<IndexStats>;
78
- deleteIndex(...args: ParamsToArgs<DeleteIndexParams>): Promise<void>;
79
- /**
80
- * Updates a vector by its ID with the provided vector and/or metadata.
81
- * @param indexName - The name of the index containing the vector.
82
- * @param id - The ID of the vector to update.
83
- * @param update - An object containing the vector and/or metadata to update.
84
- * @param update.vector - An optional array of numbers representing the new vector.
85
- * @param update.metadata - An optional record containing the new metadata.
86
- * @returns A promise that resolves when the update is complete.
87
- * @throws Will throw an error if no updates are provided or if the update operation fails.
88
- */
89
- updateVector(...args: ParamsToArgs<UpdateVectorParams>): Promise<void>;
90
- /**
91
- * Deletes a vector by its ID.
92
- * @param indexName - The name of the index containing the vector.
93
- * @param id - The ID of the vector to delete.
94
- * @returns A promise that resolves when the deletion is complete.
95
- * @throws Will throw an error if the deletion operation fails.
96
- */
97
- deleteVector(...args: ParamsToArgs<DeleteVectorParams>): Promise<void>;
98
- }
99
- export { TurbopufferVector }
100
- export { TurbopufferVector as TurbopufferVector_alias_1 }
101
-
102
- declare interface TurbopufferVectorOptions {
4
+ import type { TurbopufferVectorFilter } from './filter.js';
5
+ type TurbopufferQueryVectorParams = QueryVectorParams<TurbopufferVectorFilter>;
6
+ export interface TurbopufferVectorOptions {
103
7
  /** The API key to authenticate with. */
104
8
  apiKey: string;
105
9
  /** The base URL. Default is https://api.turbopuffer.com. */
@@ -141,7 +45,43 @@ declare interface TurbopufferVectorOptions {
141
45
  schema: Schema;
142
46
  };
143
47
  }
144
- export { TurbopufferVectorOptions }
145
- export { TurbopufferVectorOptions as TurbopufferVectorOptions_alias_1 }
146
-
147
- export { }
48
+ export declare class TurbopufferVector extends MastraVector<TurbopufferVectorFilter> {
49
+ private client;
50
+ private filterTranslator;
51
+ private createIndexCache;
52
+ private opts;
53
+ constructor(opts: TurbopufferVectorOptions);
54
+ createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
55
+ upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
56
+ query({ indexName, queryVector, topK, filter, includeVector, }: TurbopufferQueryVectorParams): Promise<QueryResult[]>;
57
+ listIndexes(): Promise<string[]>;
58
+ /**
59
+ * Retrieves statistics about a vector index.
60
+ *
61
+ * @param {string} indexName - The name of the index to describe
62
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
63
+ */
64
+ describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats>;
65
+ deleteIndex({ indexName }: DeleteIndexParams): Promise<void>;
66
+ /**
67
+ * Updates a vector by its ID with the provided vector and/or metadata.
68
+ * @param indexName - The name of the index containing the vector.
69
+ * @param id - The ID of the vector to update.
70
+ * @param update - An object containing the vector and/or metadata to update.
71
+ * @param update.vector - An optional array of numbers representing the new vector.
72
+ * @param update.metadata - An optional record containing the new metadata.
73
+ * @returns A promise that resolves when the update is complete.
74
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
75
+ */
76
+ updateVector({ indexName, id, update }: UpdateVectorParams): Promise<void>;
77
+ /**
78
+ * Deletes a vector by its ID.
79
+ * @param indexName - The name of the index containing the vector.
80
+ * @param id - The ID of the vector to delete.
81
+ * @returns A promise that resolves when the deletion is complete.
82
+ * @throws Will throw an error if the deletion operation fails.
83
+ */
84
+ deleteVector({ indexName, id }: DeleteVectorParams): Promise<void>;
85
+ }
86
+ export {};
87
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources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