/** * Every request and reply of intent-search's `/v1`, as TypeScript. * * Copy this file into your project and import the namespace: * * import type { V1 } from "./intent-search" * * const ask = { query: "เซรั่ม", mode: "auto" } satisfies V1.SearchAsk * const reply = (await res.json()) as V1.SearchReply * * It is the source the reference is held to, not a copy of it: every example * on `/docs` is written as a value of these types and the build fails when one * disagrees, the platform's handlers are typed by them, and a walk sends every * example to a running platform and compares the keys that come back. A field * here is a field the API sends. * * Types only, with no imports and nothing that runs, so the file is served * byte for byte and drops into any TypeScript project. Offered by the * deployment that answers it rather than published as a package, so it always * describes the API it came from. */ export namespace V1 { // -- shared ---------------------------------------------------------------- /** Anything JSON carries, which is what a record of yours is made of. */ export type Json = | string | number | boolean | null | Array | { [key: string]: Json } /** One of your records, stored whole and handed back whole, nested fields and all. */ export type Document = { [field: string]: Json } /** A request that sends nothing: the path says it all. */ export type Nothing = Record /** * What every reply may carry beside its answer. A warning never changes the * answer — the status and every other key are what they would have been — * so code that ignores it keeps working, and it says what to fix. */ export interface Replied { warnings?: Array } export interface Warning { reason: "service_key_in_browser" | (string & {}) message: string } /** * Every refusal, whatever its status: one English sentence that says what to * change. `from: "engine"` marks one the search engine wrote. */ export interface ErrorReply extends Replied { error: string from?: "engine" } /** * An answer smaller than the one asked for — beside the results, never * instead of them, because a quota degrades rather than fails. Branch on * `reason` and show `message`. Open-ended, so a reason added later still * type-checks and still carries a sentence somebody can act on. */ export interface Degraded { asked: string served: string reason: DegradedReason | (string & {}) message: string /** Everything else withheld from the same request, when it was more than one thing. */ also?: Array } export type DegradedReason = | "quota_exhausted" | "not_on_plan" | "not_enabled" | "not_ready" | "model_changed" | "no_vector_supplied" | "page_size_capped" | "window_capped" | "pages_capped" | "no_page_cursors" | "facet_buckets_capped" | "not_loaded" | "unreachable" | "no_endpoint" | "bad_reply" // -- the schema -------------------------------------------------------------- export type ValueType = "text" | "number" | "date" | "boolean" export type DateStep = | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year" /** * One band of a number or a date: `from` inclusive and `to` exclusive, so * `0–100` and `100–200` never both count the hundred. */ export interface Band { from?: number to?: number label?: string } /** * How a field is offered as a filter. A number's is bands somebody drew, * because a list of every price is not a filter anyone can use. */ export type FilterSpec = | { kind: "terms"; label?: string } | { kind: "range"; label?: string; ranges: Array } | { kind: "date"; label?: string; interval: DateStep } /** * One field as capabilities rather than the engine's types: a brand is both * found by its words and filtered by its values, and saying so in engine * types would mean knowing about a column nobody should have to. */ export interface SchemaField { name: string type: ValueType search: false | { weight: number } filter: false | FilterSpec sort: boolean } /** A field as you write it: `true` stands for each capability's ordinary form. */ export interface SchemaFieldAsk { name: string type: ValueType search?: boolean | { weight: number } /** `true` is a list of values for text and booleans and months for a date; a number needs its bands. */ filter?: boolean | FilterSpec sort?: boolean } /** A column a write kept in every record but left out of the index, and why. */ export interface StoredOnly { name: string reason: string } /** What arrived in one field, so a misfit is counted rather than refused. */ export interface FieldReport { types: { string: number number: number boolean: number object: number /** `null` or `""`: present in the record and saying nothing. */ empty: number } indexed_as: ValueType | null /** Values kept in the record and left out of the index, because they do not fit its type. */ not_indexed: number } /** One field a schema change would move, from what to what; `null` is absent. */ export interface FieldChange { field: string from: SchemaField | null to: SchemaField | null } // -- searching --------------------------------------------------------------- /** * A filter a dataset offers, as a search reply names it: a schema field's * `filter`, with the field's name. */ export type Filter = | { field: string; kind: "terms"; label?: string; size?: number } | { field: string; kind: "range"; label?: string; ranges: Array } | { field: string; kind: "date"; label?: string; interval: DateStep } /** * What a shopper ticked: a filter's name to the values chosen, always a list. * Values of one filter are OR and filters are AND. A range or date filter * takes the `key` of the bucket it was counted in, as the reply handed it out. */ export type Selection = { [field: string]: Array } /** * One clause of the query DSL — `match`, `term`, `terms`, `range`, `bool`, * `match_phrase`, `match_phrase_prefix`, `multi_match`, `query_string` — as * the engine's guide writes it. Typed loosely because the DSL nests without * end, and the engine checks it and names what is wrong. */ export type Clause = { [clause: string]: Json } /** One order: `"price"`, `"-price"`, `"price:desc"`, `{"price": "desc"}` or `{"field": "price", "order": "desc"}`. */ export type SortKey = | string | { [field: string]: "asc" | "desc" | { order: "asc" | "desc" } } | { field: string; order?: "asc" | "desc" } export type Sort = SortKey | Array /** * A place in an order: a hit's `sort`, sent back as `search_after`. It ends * with the hit's id, so it does not expire when the index is reorganised. */ export type Cursor = Array export interface Highlight { fields: Array | { [field: string]: { [option: string]: Json } } pre_tags?: Array post_tags?: Array fragment_size?: number number_of_fragments?: number } /** A vector you made yourself; leave it out and send `mode` for the platform to make one. */ export interface Knn { field: string query_vector: Array k?: number num_candidates?: number filter?: Clause boost?: number model?: string } /** One aggregation of your own: `{"stats": {"field": "price"}}`, or `terms`, `range`, `histogram`, `date_histogram`, `cardinality`, `filter`, `filters`, nested with `aggs`. */ export type AggregationAsk = { [kind: string]: Json } export interface Hit { id: string score: number /** Which ranking put it here, for a storefront to label. */ matched: "words" | "meaning" | "both" /** * How the words found it: as typed, only through a longer word beginning * with one typed, or by a wider question because the words as typed found * nothing. Absent when meaning alone found it. */ words?: "typed" | "compound" | "widened" /** Absent from a search by meaning, whose fused order has no cursor. */ sort?: Cursor /** Absent with `_source: false`. */ document?: Document /** Fragments per field. Not HTML-escaped: escape them before they reach a page. */ highlight?: { [field: string]: Array } /** The engine's own account of the score, with `explain` and a service key. */ explanation?: string } export interface Bucket { key: string count: number /** A range or date bucket's edges, a date's as epoch milliseconds. */ from?: number to?: number /** `significant_terms` only. */ score?: number aggregations?: { [name: string]: Aggregation } } /** Values and how many records hold each — the shape every filter's counts have. */ export interface Buckets { buckets: Array /** Records holding a value left out of `buckets`, once per value they hold: not a number of values. */ other: number /** Records with no value here at all. */ missing: number /** Distinct values left out of `buckets`; a terms count's only. */ other_values?: number } /** * One count, by name. A filter's is always `Buckets`, under its field's name; * one you sent in `aggs` comes back under your name in its kind's shape, so * narrow with `"buckets" in a` before reading buckets. */ export type Aggregation = | Buckets | { value: number; exact: boolean; missing: number } | { values: { [percent: string]: number } count: number exact: false missing: number } | { hits: Array<{ id: string; score: number }> } | { value: number | null; missing: number } | { count: number min: number max: number sum: number avg: number missing: number } /** * Which of words and meaning answered, and why — a union, so the answer that * spends a search by meaning can only carry a reason that does. */ export type Answered = | { by: "words" reason: | "looks_like_a_code" | "looks_like_a_name" | "meaning_withheld" | "meaning_not_enabled" | "no_query_text" | "sort_asked" | "mode_asked" | "no_mode" message: string } | { by: "meaning" reason: "reads_like_a_need" | "vector_supplied" | "mode_asked" message: string } /** A typed word that also read as the longer words beginning with it; every exact hit is still there, first. */ export interface Reached { word: string compounds: Array /** Longer words a cap left out. */ left_out?: number } /** * What a question that found nothing as typed was widened to. Its presence is * the signal to say "no exact matches", and its keys come in any subset, so * test for it rather than for one of them. */ export interface Broadened { split?: Array<{ word: string parts: Array by: "dictionary" | "analyzer" }> prefixed?: Array required?: "all" | "most" | "any" } /** A rerank that happened, or the text for you to rerank; one that failed is in `degraded`. */ export type Reranked = | { reranked: true; mode: "inline"; ordered: number } | { reranked: false mode: "candidates" candidates: Array<{ id: string; text: string }> } /** What the counts in `aggregations` were taken over. */ export type CountedFrom = "matches" | "words" | "all" // -- meaning ----------------------------------------------------------------- /** Work that stopped for over a minute. Every reason is on our side, and nothing is lost. */ export interface Stalled { reason: | "worker_offline" | "model_unavailable" | "model_mismatch" | "engine_unavailable" | "engine_refused" /** When it started; `null` when the worker has never been seen. */ since: string | null message: string } // -- POST /v1/documents ------------------------------------------------------ export interface DocumentsAsk { /** 1 to 5,000, each carrying the dataset's id field (`id` unless `id_field` says otherwise). */ documents: Array } export interface DocumentsReply extends Replied { received: number /** Distinct ids. */ stored: number /** New or changed since what was stored: what the next sync sends. */ changed: number duplicates?: number duplicates_note?: string /** The schema the first batch was read as, said so it can be changed without sending anything again. */ schema?: { inferred: true id_field: string fields: Array stored_only: Array note: string } report: { [field: string]: FieldReport } note: string } // -- POST /v1/documents/remove ----------------------------------------------- export interface DocumentsRemoveAsk { ids: Array } export interface DocumentsRemoveReply extends Replied { removed: number /** The first twenty ids that were not there, which is not an error. */ missing?: Array missing_count?: number note: string } // -- GET /v1/documents/:id --------------------------------------------------- export type DocumentAsk = Nothing export interface DocumentReply extends Replied { id: string document: Document /** `false` while the stored version waits for a sync, and searches still see the one before. */ published: boolean updated_at: string } // -- DELETE /v1/documents/:id ------------------------------------------------ export type DocumentDeleteAsk = Nothing export type DocumentDeleteReply = DocumentsRemoveReply // -- POST /v1/sync ----------------------------------------------------------- export type SyncAsk = Nothing export interface SyncReply extends Replied { /** Records new or changed since the last sync, not every record. */ sent: number deleted: number /** The engine had lost the dataset and was sent every record again: a recovery, not an error. */ reregistered?: boolean } // -- POST /v1/search --------------------------------------------------------- export interface SearchAsk { /** A string is what somebody typed, letter for letter, every word required; an object is the DSL. */ query?: string | Clause mode?: "auto" | "keyword" | "vector" | "hybrid" filters?: Selection size?: number from?: number /** A previous page's `next`, or an entry of `pages`; never beside `from`. */ search_after?: Cursor /** The last page a page bar links to; the reply's `pages` holds the cursor that starts each. */ pages?: number /** A search by meaning orders by closeness alone, so beside one only `{"_score": "desc"}` is taken. */ sort?: Sort _source?: boolean | Array aggs?: { [name: string]: AggregationAsk } post_filter?: Clause highlight?: Highlight track_total_hits?: boolean rerank?: "candidates" | "inline" /** A service key's only: an explanation describes the whole dataset. */ explain?: boolean /** On unless `false`; also read from `?broaden=`. */ broaden?: boolean knn?: Knn } export interface SearchReply extends Replied { /** After what was ticked. */ total: number /** `false` only when `total` is a lower bound, which a hybrid can be. */ total_is_exact: boolean /** Absent while the dataset holds nothing yet. */ took_us?: number hits: Array /** Present only while more results exist: no `next` means this was the last page. */ next?: Cursor /** Page number to the `search_after` that starts it, for a page bar. */ pages?: { [page: string]: Cursor } /** What the counts were taken over — before what was ticked, so it is not `total`. */ counted_over?: number counted_from?: CountedFrom aggregations?: { [name: string]: Aggregation } /** Every filter the dataset offers, an empty list when none. */ filters: Array answered: Answered degraded?: Degraded reached?: Array broadened?: Broadened rerank?: Reranked /** The query as the engine planned it, with `explain`. */ plan?: string } // -- POST /v1/similar -------------------------------------------------------- export interface SimilarAsk { id: string | number size?: number filters?: Selection _source?: boolean | Array /** Text fields likeness is read from when it is measured by words. */ fields?: Array } /** No `total` and no `next`: a strip of neighbours is not paged. */ export interface SimilarReply extends Replied { similar_to: string by: "meaning" | "words" /** Never the record itself. */ hits: Array degraded?: Degraded } // -- GET /v1/suggest --------------------------------------------------------- export type SuggestSource = "titles" | "queries" | "dictionary" /** Sent as the query string. */ export interface SuggestAsk { /** What has been typed so far; send it even when empty. */ q: string n?: number /** Where suggestions come from, not a cursor: one source, or several comma-separated in the order wanted. */ from?: string field?: string /** The top products for what is typed, counted as one search. */ products?: number } export interface SuggestReply extends Replied { suggestions: Array<{ text: string; from: SuggestSource }> /** Absent while the dataset holds nothing yet. */ sources?: Array products?: Array degraded?: Degraded } // -- POST /v1/filters -------------------------------------------------------- export type ValueOrder = "value" | "count" | "key" export interface ValueCount { value: string count: number } export interface FiltersAsk { query?: string filters?: Selection size?: number /** `value` is Thai dictionary order, which byte order is not. */ order?: ValueOrder } export interface FilterCounts { field: string kind: "terms" | "range" | "date" label?: string /** A terms filter's only. */ order?: ValueOrder values: Array other: number other_values: number missing: number /** Where to page the rest when `other_values` is above 0, since this path has no cursor. */ note?: string } export interface FiltersReply extends Replied { counted_over: number filters: Array } // -- POST /v1/filters/:field ------------------------------------------------- export interface FilterValuesAsk extends FiltersAsk { /** The previous page's `next`, in `key` order. */ after?: string } export interface FilterValuesReply extends Replied { field: string /** A range or date filter is refused here: its values are the bands every search reply counts. */ kind: "terms" label?: string order: ValueOrder counted_over: number values: Array /** Records holding the values after this page, once per value. 0 on the last page. */ other: number /** Values after this page. 0 on the last page. */ other_values: number missing: number /** `key` order only, and only while values are left. */ next?: string note?: string } // -- GET /v1/schema ---------------------------------------------------------- export type SchemaAsk = Nothing export interface SchemaReply extends Replied { id_field: string fields: Array /** Columns records carry that are not indexed, still handed back with every hit. */ stored_only: Array /** Columns the platform writes, such as the categories' one. */ generated?: Array<{ name: string; type: "text"; from: "categories" }> documents: { stored: number; pending: number } } // -- PUT /v1/schema ---------------------------------------------------------- export interface SchemaPutAsk { id_field?: string /** The whole list: a field left out stops being indexed and is still stored and returned. */ fields?: Array /** In the body only; `?dry_run=` in the URL is refused before anything changes. */ dry_run?: boolean } export type SchemaPutReply = SchemaDryRun | SchemaApplied export interface SchemaDryRun extends Replied { dry_run: true changes: Array id_field?: { from: string; to: string } /** Whether every record would be written again, the one cost a change has. */ reindex: boolean documents: number } export interface SchemaApplied extends SchemaReply { reindexed: number } // -- GET and PUT /v1/synonyms ------------------------------------------------ export type SynonymsAsk = Nothing export interface SynonymsReply extends Replied { groups: Array> } /** The whole list at once, because a backend keeps its vocabulary as a file. */ export interface SynonymsPutAsk { groups: Array> } export type SynonymsPutReply = SynonymsReply // -- GET and PUT /v1/origins ------------------------------------------------- export type OriginsAsk = Nothing export interface OriginsReply extends Replied { origins: Array } export interface OriginsPutAsk { /** `https://shop.example.com`, `https://*.example.com`, or `http://localhost:*` for any port on this machine. */ origins: Array } export type OriginsPutReply = OriginsReply // -- GET and PUT /v1/vectors ------------------------------------------------- export type VectorsAsk = Nothing /** Every key but `enabled` and `ready` is `null` on a dataset that never switched meaning on. */ export interface VectorsReply extends Replied { enabled: boolean ready: boolean model: string | null progress: { done: number; total: number } | null phase: | "queued" | "copying" | "filling" | "committing" | "ready" | "failed" | (string & {}) | null eta_seconds: number | null /** Records saved after the vectors went live and still waiting for theirs; `null` while the first fill runs. */ pending: number | null stalled: Stalled | null } export interface VectorsPutAsk { enabled: boolean } export type VectorsPutReply = VectorsReply // -- GET and PUT /v1/categories ---------------------------------------------- export interface Category { name: string /** Read by the model, never shown. */ description?: string examples?: Array } export type CategoriesAsk = Nothing export type CategoriesReply = Uncategorized | Categorized export interface Uncategorized extends Replied { categories: Array } export interface Categorized extends Replied { /** The column the category is written to, beside your own. */ field: string categories: Array from?: Array /** * How near, as a cosine from 0 to 1, a record must be to its nearest * category to be put in it; the one sent, or the default. */ min_score: number version: number /** `null` until the worker has started sorting. */ model: string | null /** `unfit`: sorted, and nearer no category than `min_score`, so in none. */ progress: { sorted: number; total: number; unfit: number } updated_at: string } export interface CategoriesPutAsk { /** An empty list stops sorting. */ categories: Array field?: string from?: Array /** 0 to 1. Changing only this sorts nothing again. */ min_score?: number } export type CategoriesPutReply = CategoriesReply // -- every route ------------------------------------------------------------- /** * Each route's ask and reply by method and path, for a client typed once: * * type Route = keyof V1.Routes * declare function call(route: R, ask: V1.Routes[R]["ask"]): Promise * * A `GET`'s ask is its query string and every other one is a JSON body; * `:id` and `:field` are filled into the path. */ export interface Routes { "POST /v1/documents": { ask: DocumentsAsk; reply: DocumentsReply } "POST /v1/documents/remove": { ask: DocumentsRemoveAsk reply: DocumentsRemoveReply } "GET /v1/documents/:id": { ask: DocumentAsk; reply: DocumentReply } "DELETE /v1/documents/:id": { ask: DocumentDeleteAsk reply: DocumentDeleteReply } "POST /v1/sync": { ask: SyncAsk; reply: SyncReply } "POST /v1/search": { ask: SearchAsk; reply: SearchReply } "POST /v1/similar": { ask: SimilarAsk; reply: SimilarReply } "GET /v1/suggest": { ask: SuggestAsk; reply: SuggestReply } "POST /v1/filters": { ask: FiltersAsk; reply: FiltersReply } "POST /v1/filters/:field": { ask: FilterValuesAsk; reply: FilterValuesReply } "GET /v1/schema": { ask: SchemaAsk; reply: SchemaReply } "PUT /v1/schema": { ask: SchemaPutAsk; reply: SchemaPutReply } "GET /v1/synonyms": { ask: SynonymsAsk; reply: SynonymsReply } "PUT /v1/synonyms": { ask: SynonymsPutAsk; reply: SynonymsPutReply } "GET /v1/origins": { ask: OriginsAsk; reply: OriginsReply } "PUT /v1/origins": { ask: OriginsPutAsk; reply: OriginsPutReply } "GET /v1/vectors": { ask: VectorsAsk; reply: VectorsReply } "PUT /v1/vectors": { ask: VectorsPutAsk; reply: VectorsPutReply } "GET /v1/categories": { ask: CategoriesAsk; reply: CategoriesReply } "PUT /v1/categories": { ask: CategoriesPutAsk; reply: CategoriesPutReply } } }