Client
The Mountaya API client: the Map Studio API, the Tile API and the GraphQL Data API, behind one credential.
Mountaya is the client. One instance holds one credential and one set of policies.
Builds a client over one credential and its options, checking both before anything is sent.
new Mountaya(options)
optionsClientOptions
Credential is any of the ways to authenticate, told apart by which key is present.
PublishableCredential authenticates browser and embedding access with a pk_ key, optionally scoped up by a session token minted from a secret key.
publishableKeystring
The pk_ key, sent as X-API-Key. An empty or blank one is refused as a missing credential.
sessionTokenstring | (() => string | undefined) | SessionTokenSource
The session token that accompanies the key: a sess_ string, a function the client calls whenever it reads the token, or a SessionTokenSource such as a SessionTokenEngine. The token is read for each request, each event-stream open and each read of MountayaTransport.mapCredential, so every map built on the client too.
cookieundefined
Never set: a key credential sends no cookie, and one written beside a key is refused at construction. The browser's own session is CookieCredential, a credential of its own.
SecretCredential authenticates server-to-server session minting with an sk_ key.
secretKeystring
The sk_ key, sent as X-API-Key to postSession alone. Never quoted in a refusal.
cookieundefined
Never set: see cookie.
ShareCredential authenticates a link visitor with a share_ token. It reaches exactly the itinerary or collection the token was minted for, read-only.
shareTokenstring
The share_ token, sent as X-Share-Token in place of a key.
cookieboolean
Also send ambient cookies, on every operation that takes a credential.
CookieCredential defers authentication to the browser's ambient credentials.
cookietrue
Rides the browser's own session: credentials: "include" and no credential header.
publishableKeyundefined
Never set: the cookie credential carries no key.
secretKeyundefined
Never set: the cookie credential carries no key.
sessionTokenundefined
Never set: a session token accompanies a publishable key, which this credential has not.
shareTokenundefined
Never set: a share visitor asking for cookies is a ShareCredential with cookie.
SessionTokenSource is a session token that changes over time and says when one is on its way: what a SessionTokenEngine is, and what credential.sessionToken takes beside a string and a function.
getSnapshot() => Pick<SessionTokenSnapshot, "error" | "isLoading" | "token"> & { readonly expiresAt?: Date | undefined; readonly userId?: string | null | undefined }
The token held now, whether one is on its way, and what the last mint failed with; and, where the source knows them, when the token expires and the user it was minted for.
subscribe(listener: () => void) => () => void
Registers a listener told of every change of the snapshot, and returns its release. A source may start minting on its first listener, as a SessionTokenEngine does.
The Map Studio API's map half: itineraries, zones, collections, and their catalogs. Each method resolves to the response envelope, with the payload at data.
The Map Studio API's organization half: keys, settings, members, usage and webhooks. Each method resolves to the response envelope, with the payload at data.
The AI agent: starting a run, answering it, rating it. Each method resolves to the response envelope, with the payload at data; a run's events are read through createAgentTransport of @mountaya/client/events.
The Tile API's style specifications. Each method resolves to the response envelope.
The GraphQL Data API: directions, search, terrain, isochrones, matrices. Each method resolves to the operation's own field, with no envelope.
The transport every method calls through: for a call this client binds no method for, and for the openers of @mountaya/client/events.
A MountayaTransport, documented under Classes.
Every error the client throws extends MountayaError. Catch the class, or test a value with isMountayaError or isMountayaApiError.
decodeRestSchema<N>(schema, json)
schemaN
A name under RestSchema.components["schemas"], such as "ItineraryWithDetails".
jsonunknown
The parsed JSON of one value of that schema. A list of them is decoded by calling this once per member.
Returns RestSchemas[N]: json as the schema's type, its declared instants decoded.
errorForStatus picks the class a status maps to, for a caller holding a status and no Response to read.
errorForStatus(message, status, entries?, details?)
messagestring
The error's message, as failureMessage spells one.
statusnumber
The HTTP status the response carried.
entriesreadonly ErrorEntry[]
default: []
The envelope's entries, none where omitted. The status alone decides the class, a 402's and a 429's included, whatever code an entry carries.
detailsApiErrorDetails
default: {}
What the answer sent beside them: the envelope's metadata, the request id, the rate-limit state, the Idempotency-Key the call sent, the wait its Retry-After names as retryAfter, and the tag a 412 carries as its etag, which every other status leaves out.
Returns MountayaApiError: The class the status maps to: a MountayaServerError for any 5xx, and a plain MountayaApiError for a status no class is named for.
namestring
statusnumber
The HTTP status the response carried.
errorsreadonly ErrorEntry[]
Every entry of the envelope, in the order the API wrote them; empty for a bodiless answer.
metadataErrorMetadata
The envelope's extensions.metadata, exactly as sent, or undefined where the response carried none: see ErrorMetadata.
rateLimitRateLimitInfo
The rate-limit state the answer's RateLimit-Policy and RateLimit describe, or undefined where they describe none, as on every Map Studio API answer.
requestIdstring
The answer's X-Request-Id, exactly as sent: 32 lowercase hex characters the API recorded the request under, and the one thing to quote to support. Undefined where the answer sent none; the client never makes one up.
retryAfternumber
How many seconds the answer asked the caller to wait before asking again, from its Retry-After header, read as whole seconds or an HTTP date; undefined where the header was absent or neither.
codeErrorCode | undefined
The classifying code of the response, taken from its first entry.
hasCode(code: ErrorCode) => boolean
Reports whether any entry carries the given code.
idempotencyKeystring
The Idempotency-Key the call that raised this error sent on its attempts, the caller's own or the one the client drew for it, and undefined where it sent none: a read, an operation that declares no key, a call refused before its first attempt, and a runtime with no cryptographic random source.
isMountayaApiError reports whether a value is a failure the API answered: an error of the family whose class a status maps to, carrying what that class carries, so that everything the narrowed type promises is there to read whichever copy of this package built it.
isMountayaApiError(error)
errorunknown
Returns error is MountayaApiError
isMountayaError reports whether a value is an error of this family, read from the name its class declares rather than from its constructor.
isMountayaError(error)
errorunknown
Returns error is MountayaError
paginate walks a paged Map Studio listing and answers its rows one at a time, requesting each page as the rows before it are read.
paginate<A, T>(operation, args, options?)
operation(args: A, options?: RequestOptions) => Promise<PagedResponse<T>>
A method of the client that takes cursor and limit under query, such as mountaya.admin.members.getOrganizationMembers. An operation that takes no cursor answers no PagedResponse, so it is a type error here. A free function takes its transport first, so it is passed wrapped: (args, options) => rest.getOrganizationMembers(transport, args, options).
argsNonNullable<A>
The operation's own arguments: its path parameters, and any filter, sort or starting cursor under query. {} for an operation that requires none.
optionsPaginateOptions
default: {}
The walk's pageSize and maxPages, and the retry, signal and timeoutMs each request is made under.
Returns AsyncIterable<T>: The listing's rows, in the listing's order, typed as the operation's own.
parseRateLimit reads the rate-limit state an answer's headers describe, or undefined where they describe none.
parseRateLimit(headers)
headersPick<Headers, "get">
The answer's headers, as a Response carries them.
Returns RateLimitInfo | undefined: The state, or undefined where the answer describes no policy.
policiesreadonly RateLimitPolicy[]
The policies the answer was counted against, never empty.
boundFetch resolves the fetch implementation a caller issues requests through, keeping the global one callable through a local binding.
boundFetch(fetchImpl?)
fetchImpltypeof fetch
The caller's own fetch, or undefined for the global one.
Returns typeof fetch: fetchImpl as given, or a function that calls the global fetch at each call.
constructWebhookEvent verifies a webhook delivery's signature and answers the event its body holds, typed by its type.
constructWebhookEvent(rawBody, signatureHeader, secret, options?)
rawBodystring | Uint8Array
The request body, exactly as it arrived.
signatureHeaderstring | null | undefined
The request's Mountaya-Signature header, as request.headers.get answers it: null or undefined where the request carries none.
secretstring
The signing secret of the endpoint the delivery was sent to, whsk_ included.
optionsConstructWebhookEventOptions
How far a timestamp may stand from this clock.
Returns Promise<WebhookEvent>: The event, once a v1 verifies and its timestamp is within the tolerance.
SessionTokenEngine keeps a session token fresh: it mints through the application's own endpoint, refreshes a margin before expiry, backs off from tokens that arrive already spent, and abandons a mint that does not settle.
Builds an engine over the application's mint. It mints nothing until something subscribes.
new SessionTokenEngine(options)
optionsSessionTokenEngineOptions
getSnapshot returns the current snapshot, by reference and stable between changes.
getSnapshot()
Returns SessionTokenSnapshot
errorunknown
The last mint failure: what the mint rejected with, or a MountayaConnectionError where it answered no session or did not answer within the margin. Minting is retried on schedule regardless.
expiresAtDate | undefined
When the current token expires, which can be an instant already PAST when the server hands one back that way: the engine answers that by backing off between mints rather than re-minting on a fixed floor.
isLoadingboolean
Whether a token is on its way: a mint is out, or the engine is enabled, holds no token and mints as soon as something subscribes to it. A request made through a client whose credential holds this engine waits for that token while none is held, and the client's credentialScope reads the same flag, so the scope a read is keyed under says a session wherever the read carries one.
tokenstring | undefined
The current token, or undefined before the first mint completes.
userIdstring | null | undefined
The user the current token was minted for, its mint's user_id: null where it names no user, and undefined where no token is held or the mint did not say. A client whose credential holds this engine refuses locally a call that acts as a member while it reads null, since the API would answer that call with a 401.
subscribe registers a listener for every change, and returns its own unsubscribe.
subscribe(listener)
listener() => void
Called after every change of the snapshot, with no argument.
Returns () => void: The function that removes this listener, and parks the engine when it is the last.
refresh mints now, replacing any pending refresh, or joins the mint already out.
refresh()
checkNow re-reads the wall clock against the armed deadline: one already passed fires now, and one still ahead is re-armed from the clock as it reads now.
checkNow()
setMint replaces the callback without disturbing the schedule.
setMint(mint)
mint() => Promise<Session>
setEnabled turns minting on or off.
setEnabled(enabled)
enabledboolean
dispose retires the in-flight mint, drops the timer, clears the token and latches the engine shut.
dispose()
Builds a transport over one credential and its options, checking both before anything is sent.
new MountayaTransport(options)
optionsClientOptions
Its fields are listed under new Mountaya.
applyAuth folds this transport's credential into a RequestInit, for a call this client does not make itself.
applyAuth(init?, method?, declaration?)
initRequestInit
default: {}
methodstring
default: "GET"
declarationStreamDeclaration
default: {}
Returns RequestInit
subscribeCredentialScope registers a listener told each time credentialScope or credentialScopePending moves, and returns its release.
subscribeCredentialScope(listener)
listener() => void
Called with no argument after each move of the scope or of its pending flag.
Returns () => void: The function that removes the listener.
requestRaw performs one call, retrying per the policy, and returns the Response as it arrived, including a non-ok one, with its body unread.
requestRaw(args)
argsRequestArgs
Returns Promise<Response>
request performs one call and returns the parsed body, with each instant args.dates names decoded to a Date and every other string left a string.
request<T>(args)
argsRequestArgs
Its fields are listed under requestRaw.
Returns Promise<T>
requestBinary performs one call and returns the bytes with the two headers that describe them, for tile and export responses that are protobuf, PNG, WebP or an octet stream rather than JSON.
requestBinary(args)
argsRequestArgs
Its fields are listed under requestRaw.
Returns Promise<BinaryBody>
bytesArrayBuffer
The body, whole, as it arrived.
contentTypestring
The response's Content-Type, verbatim, when the response carried one.
filenamestring
The download filename from Content-Disposition, when the response carried one.
The browser-safe entry point of @mountaya/client.
The Server-Sent Events half of talking to Mountaya: a frame parser that turns a text/event-stream byte stream into decoded records, a reader that drives a Response body through it frame by frame, and an opener that wires those over a fetch the caller supplies, with resume and abort.
agentTerminalEventTypes are the event types that end a run: once one is seen the stream is finished and the read stops rather than waiting on the server to hang up. done is the sole terminal: an ended run always finishes with one.
createAgentTransport binds an agent run's endpoints to one client's transport.
createAgentTransport(transport)
transportMountayaTransport
Returns AgentTransport
sendInput(runId: string, input: AgentInput, options?: AgentWriteOptions) => Promise<void>
sendInput delivers one input signal into a running run, resolving once the API took it.
startRun(params: AgentRunCreateParams, options?: AgentWriteOptions) => Promise<{ runId: string }>
startRun starts a run and answers its id, which sendInput and subscribe take.
subscribe(runId: string, handlers: AgentStreamHandlers, options?: AgentSubscribeOptions) => () => void
subscribe opens a run's event stream and returns the function that closes it. Every failure reaches handlers.onError; the call itself never throws.
decodeAgentFrame turns one raw SSE frame into a typed event, or null to skip it.
decodeAgentFrame(frame)
frameSseFrame
Returns AgentEvent | null
createCollabTransport binds the collaboration streams to one client's transport.
createCollabTransport(transport)
transportMountayaTransport
Its fields are listed under createAgentTransport.
Returns CollabTransport
sendSignal(resource: CollabStreamResource, signal: CollabSignal) => Promise<CollabSignalResult>
sendSignal publishes one signal for a resource, and answers how it settled: a lock another member holds is a result naming them, never a throw.
subscribeEditor(resource: CollabStreamResource, handlers: CollabStreamHandlers, options?: CollabSubscribeOptions) => () => void
subscribeEditor opens the editor stream of one resource and returns the function that closes it. Every failure reaches handlers.onError, classified; the call itself never throws.
subscribeList(organizationId: string, handlers: CollabStreamHandlers, options?: CollabSubscribeOptions) => () => void
subscribeList opens an organization's event stream, the changes to its itineraries, zones and collections, and returns the function that closes it. Every failure reaches handlers.onError, classified; the call itself never throws.
decodeCollabFrame turns one raw SSE frame into a typed event, or null to skip it.
decodeCollabFrame(frame)
frameSseFrame
Its fields are listed under decodeAgentFrame.
Returns CollabEvent | null
readEventStream reads a text/event-stream body to its end. It pulls each chunk from the body's reader, decodes it as UTF-8 across reads (so a character two reads split arrives whole), frames it with SseFrameParser, and hands every frame to onFrame. It knows nothing of the payload's shape or vocabulary: the caller decodes and validates each frame's data. Awaiting onFrame lets a slow handler backpressure the read, and a handler that returns true stops the read at once rather than waiting on the producer to hang up. It returns stopped when a handler stopped the read and ended when the body closed first.
readEventStream(body, onFrame, onLastEventId?)
bodyReadableStream<Uint8Array>
onFrameFrameHandler
onLastEventId(lastEventId: string) => void
Returns Promise<EventStreamOutcome>
openSseStream opens one resumable text/event-stream read over fetch and returns a close function that aborts it. It is the scaffolding every SSE consumer repeats: it forwards an external abort into its own controller, sets Accept and an optional Last-Event-ID, makes the request, decodes each frame through the caller's decode, hands each decoded event to onFrame (whose return stops the read on a terminal), and settles through onClose or, on a failure, onError. The reader stays vocabulary-free: every feature keeps its own decode and schema and shares only this transport shell.
openSseStream<TEvent>(options)
optionsOpenSseStreamOptions<TEvent>
Returns (() => void)
MAX_SSE_BUFFER_CHARS caps the text of one record a parser has not seen the end of: every character read since the record began, its line endings and comment lines included. A record ends only at an empty line, so a producer (or a proxy, or a hostile endpoint) that opens a text/event-stream and never sends one would grow the parser for as long as the connection lives. The bound turns that resource exhaustion into a fault the caller can act on.
SseBufferOverflowError is thrown by a parser whose unterminated record has passed its cap. It carries the limit it enforced, so a consumer can tell a broken producer apart from a network fault when it classifies the failure.
Builds the error a parser throws once its unterminated record passes the cap.
new SseBufferOverflowError(limit, operationId?, options?)
limitnumber
operationIdstring
optionsErrorOptions
SseFrameParser frames the text of a text/event-stream body into records, by the HTML standard's event-stream rules:
Builds a parser that holds at most maxBufferChars of a record it has not seen the end of.
new SseFrameParser(maxBufferChars?)
maxBufferCharsnumber
default: MAX_SSE_BUFFER_CHARS
push feeds the next decoded text chunk and returns every frame the records it completes dispatch, in stream order. What it leaves unterminated stays held for the next push, unless it passes the cap: then push throws SseBufferOverflowError instead of returning, dropping the frames the same chunk completed. The stream is being torn down with them, and a caller that resumes re-reads from the position it last recorded.
push(chunk)
chunkstring
Returns SseFrame[]