import {z} from 'zod' export type Id = string | string | number; export type Vector = Array | string; export type Columns = {id: Array, vector?: (Array | Vector) | undefined} | {[key: string]: Array}; export type Row = {id: Id, vector?: Vector | undefined} | {[key: string]: unknown}; export type DistanceMetric = 'cosine_distance' | 'euclidean_squared'; export type AttributeType = string; export type Language = 'arabic' | 'danish' | 'dutch' | 'english' | 'finnish' | 'french' | 'german' | 'greek' | 'hungarian' | 'italian' | 'norwegian' | 'portuguese' | 'romanian' | 'russian' | 'spanish' | 'swedish' | 'tamil' | 'turkish'; export type Tokenizer = 'pre_tokenized_array' | 'word_v0' | 'word_v1' | 'word_v2' | 'word_v3' | 'word_v4'; export type FullTextSearchConfig = {k1?: number | undefined, b?: number | undefined, language?: Language | undefined, stemming?: boolean | undefined, remove_stopwords?: boolean | undefined, ascii_folding?: boolean | undefined, case_sensitive?: boolean | undefined, max_token_length?: number | undefined, tokenizer?: Tokenizer | undefined}; export type FullTextSearch = boolean | FullTextSearchConfig; export type AnnConfig = {distance_metric?: DistanceMetric | undefined, late_interaction?: boolean | undefined}; export type Ann = boolean | AnnConfig; export type SparseDistanceMetric = 'dot_product'; export type SparseKnn = {distance_metric: SparseDistanceMetric}; export type AttributeEmbedConfig = {attribute?: string | undefined, model: string, dims?: number | undefined}; export type AttributeEmbed = string | AttributeEmbedConfig | null; export type AttributeSchemaConfig = {type: AttributeType, filterable?: boolean | undefined, regex?: boolean | undefined, glob?: boolean | undefined, fuzzy?: boolean | undefined, full_text_search?: FullTextSearch | undefined, ann?: Ann | undefined, sparse_knn?: SparseKnn | undefined, embed?: AttributeEmbed | undefined}; export type AttributeSchemaDrop = {drop: boolean}; export type AttributeSchema = AttributeType | AttributeSchemaConfig | AttributeSchemaDrop; export type BranchFromNamespaceConfig = {source_namespace: string}; export type BranchFromNamespaceParams = string | BranchFromNamespaceConfig; export type CopyFromNamespaceConfig = {source_namespace: string, source_api_key?: string | undefined, source_region?: string | undefined}; export type CopyFromNamespaceParams = string | CopyFromNamespaceConfig; export type PatchByFilter = {patch: {[key: string]: unknown}, filters: unknown}; export type Encryption = {mode: 'customer-managed', key_name: string, encryption_context?: {[key: string]: string} | undefined} | {mode: 'default'}; export type ShardingConfig = {num_shards: number}; export type Write = {upsert_columns?: Columns | undefined, upsert_rows?: Array | undefined, patch_columns?: Columns | undefined, patch_rows?: Array | undefined, deletes?: Array | undefined, upsert_condition: unknown, patch_condition: unknown, delete_condition: unknown, distance_metric?: DistanceMetric | undefined, schema?: {[key: string]: AttributeSchema} | undefined, branch_from_namespace?: BranchFromNamespaceParams | undefined, copy_from_namespace?: CopyFromNamespaceParams | undefined, delete_by_filter: unknown, delete_by_filter_allow_partial?: boolean | undefined, patch_by_filter?: PatchByFilter | undefined, patch_by_filter_allow_partial?: boolean | undefined, return_affected_ids?: boolean | undefined, encryption?: Encryption | undefined, sharding?: ShardingConfig | undefined, disable_backpressure?: boolean | undefined, create_namespace?: boolean | undefined}; export type CreateApiV2NamespacesNamespaceArgs = {namespace: string, body: Write}; export type CreateApiV2NamespacesNamespaceOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const id = z.union([z.string(), z.string(), z.number().int().gte(0)]); export const queryBilling = z.object({billable_logical_bytes_queried: z.number().int().gte(0), billable_logical_bytes_returned: z.number().int().gte(0)}); export const writeBilling = z.object({billable_logical_bytes_written: z.number().int().gte(0), query: queryBilling.optional()}); export const writePerformance = z.object({server_total_ms: z.number().int().gte(0), embedding_tokens: z.number().int().gte(0).optional(), embedding_ms: z.number().int().gte(0).optional()}); export const writeResult = z.object({status: z.literal("OK"), message: z.string(), rows_affected: z.number().int().gte(0), rows_upserted: z.number().int().gte(0).optional(), rows_patched: z.number().int().gte(0).optional(), rows_deleted: z.number().int().gte(0).optional(), rows_remaining: z.boolean().optional(), upserted_ids: z.array(id).optional(), patched_ids: z.array(id).optional(), deleted_ids: z.array(id).optional(), billing: writeBilling, performance: writePerformance.optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create, update, or delete documents. * * POST /v2/namespaces/{namespace} */ export const createApiV2NamespacesNamespace = async (args: CreateApiV2NamespacesNamespaceArgs, options?: CreateApiV2NamespacesNamespaceOptions) => { const {baseUrl = "https://undefined.turbopuffer.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/namespaces/${encodeURIComponent(String(args.namespace))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(writeResult, await res.json()) };