Get started

Reference

Client

The Mountaya API client: the Map Studio API, the Tile API and the GraphQL Data API, behind one credential.

new Mountaya(options)

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)

options

ClientOptions

required

Credentials

Credential is any of the ways to authenticate, told apart by which key is present.

PublishableCredential

PublishableCredential authenticates browser and embedding access with a pk_ key, optionally scoped up by a session token minted from a secret key.

publishableKey

string

required

The pk_ key, sent as X-API-Key. An empty or blank one is refused as a missing credential.

sessionToken

string | (() => 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.

cookie

undefined

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

SecretCredential authenticates server-to-server session minting with an sk_ key.

secretKey

string

required

The sk_ key, sent as X-API-Key to postSession alone. Never quoted in a refusal.

cookie

undefined

Never set: see cookie.

ShareCredential

ShareCredential authenticates a link visitor with a share_ token. It reaches exactly the itinerary or collection the token was minted for, read-only.

shareToken

string

required

The share_ token, sent as X-Share-Token in place of a key.

cookie

boolean

Also send ambient cookies, on every operation that takes a credential.

CookieCredential

CookieCredential defers authentication to the browser's ambient credentials.

cookie

true

required

Rides the browser's own session: credentials: "include" and no credential header.

publishableKey

undefined

Never set: the cookie credential carries no key.

secretKey

undefined

Never set: the cookie credential carries no key.

sessionToken

undefined

Never set: a session token accompanies a publishable key, which this credential has not.

shareToken

undefined

Never set: a share visitor asking for cookies is a ShareCredential with cookie.

SessionTokenSource

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 }

required

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

required

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.

mountaya.studio

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.

mountaya.studio.activities

MethodResolves toSummary
getActivities(){ data: CategoryActivities[] }List all activity categories and their activities.

mountaya.studio.collab

MethodResolves toSummary
getItineraryEvents({ itinerary_id })BinaryBodyStream one itinerary's collaboration session over SSE.
getOrganizationEvents({ organization_id })BinaryBodyStream an organization's list events over SSE.
getZoneEvents({ zone_id })BinaryBodyStream one zone's collaboration session over SSE.
postItineraryCollab({ itinerary_id, body: CollabSignalParams }){ data: null }Send a collaboration signal into an itinerary's session.
postZoneCollab({ zone_id, body: CollabSignalParams }){ data: null }Send a collaboration signal into a zone's session.

mountaya.studio.collections

MethodResolves toSummary
deleteCollection({ collection_id, idempotencyKey?, ifMatch? }){ data: null }Delete a collection.
deleteCollectionItinerary({ collection_id, itinerary_id, idempotencyKey?, ifMatch? }){ data: Collection }Remove an itinerary from a collection.
deleteCollectionShareLink({ collection_id, idempotencyKey? }){ data: null }Remove the collection's share link.
deleteCollectionZone({ collection_id, zone_id, idempotencyKey?, ifMatch? }){ data: Collection }Remove a zone from a collection.
getCollection({ collection_id }){ data: Collection }Retrieve a single collection with its itineraries and zones.
getCollectionItineraries({ collection_id, query? }){ data: Itinerary[] }List the itineraries a collection contains.
getCollections({ query? }?){ data: Collection[] }List collections.
getCollectionShareLink({ collection_id }){ data: ShareLink | null }Read the collection's share link.
getCollectionZones({ collection_id, query? }){ data: Zone[] }List the zones a collection contains.
patchCollection({ collection_id, body: CollectionUpdateParams, idempotencyKey?, ifMatch? }){ data: Collection }Update an existing collection.
patchCollectionItinerary({ collection_id, itinerary_id, body: CollectionItineraryUpdateParams, idempotencyKey?, ifMatch? }){ data: Collection }Set an itinerary's position within a collection.
postCollection({ body: CollectionCreateParams, idempotencyKey? }){ data: Collection }Create a new collection.
postCollectionItineraries({ collection_id, body: CollectionItinerariesAddParams, idempotencyKey?, ifMatch? }){ data: Collection }Add itineraries to a collection.
postCollectionShareLink({ collection_id, idempotencyKey? }){ data: ShareLink }Mint the collection's share link, or return the one it has.
postCollectionShareLinkRotate({ collection_id, idempotencyKey? }){ data: ShareLink }Rotate the collection's share link.
postCollectionZones({ collection_id, body: CollectionZonesAddParams, idempotencyKey?, ifMatch? }){ data: Collection }Add zones to a collection.

mountaya.studio.itineraries

MethodResolves toSummary
deleteItinerary({ itinerary_id, idempotencyKey?, ifMatch? }){ data: null }Delete an itinerary.
deleteItineraryPublication({ itinerary_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Take the itinerary's publication down.
deleteItinerarySegment({ itinerary_id, segment_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Delete a segment from an itinerary.
deleteItinerarySegmentGroup({ itinerary_id, group_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Delete a segment group.
deleteItineraryShareLink({ itinerary_id, idempotencyKey? }){ data: null }Remove the itinerary's share link.
deleteItineraryWaypoint({ itinerary_id, waypoint_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Delete a waypoint from an itinerary.
getItineraries({ query? }?){ data: Itinerary[] }List the itineraries the credential reaches.
getItinerary({ itinerary_id, query? }){ data: ItineraryWithDetails }Retrieve a single itinerary with its segments and waypoints.
getItineraryExport({ itinerary_id, query? })BinaryBodyExport an itinerary as a downloadable file.
getItineraryPace({ itinerary_id, query? }){ data: ItineraryPace }Re-time an itinerary at a travel pace the caller names.
getItineraryShareLink({ itinerary_id }){ data: ShareLink | null }Read the itinerary's share link.
patchItinerary({ itinerary_id, body: ItineraryUpdateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Update an existing itinerary.
patchItinerarySegment({ itinerary_id, segment_id, body: SegmentUpdateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Update an existing segment.
patchItinerarySegmentGroup({ itinerary_id, group_id, body: SegmentGroupUpdateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Update a segment group.
patchItineraryWaypoint({ itinerary_id, waypoint_id, body: WaypointUpdateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Update an existing waypoint.
postItinerary({ body: ItineraryCreateParams, idempotencyKey? }){ data: ItineraryWithDetails }Create a new itinerary.
postItineraryDuplicate({ itinerary_id, query?, body: ItineraryDuplicateParams, idempotencyKey? }){ data: ItineraryWithDetails }Duplicate an itinerary into the key's organization.
postItineraryImport({ body: ItineraryImportConfirmParams, idempotencyKey? }){ data: ItineraryWithDetails }Confirm an itinerary import, persisting the reviewed draft.
postItineraryPreview({ body: object, idempotencyKey? }){ data: ItineraryImportPreview }Preview an itinerary import without persisting it.
postItineraryPublication({ itinerary_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Publish the itinerary's current draft.
postItinerarySegment({ itinerary_id, body: SegmentCreateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Create a segment, at the end of the chain or before another.
postItinerarySegmentConvert({ itinerary_id, segment_id, body: SegmentConvertParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Convert a segment between routed and freehand.
postItinerarySegmentGroup({ itinerary_id, body: SegmentGroupCreateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Group a contiguous run of an itinerary's segments.
postItinerarySegmentMerge({ itinerary_id, segment_id, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Merge a segment with the one that follows it.
postItinerarySegmentSplit({ itinerary_id, segment_id, body: SegmentSplitParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Split a segment in two at a fraction of its length.
postItineraryShareLink({ itinerary_id, idempotencyKey? }){ data: ShareLink }Mint the itinerary's share link, or return the one it has.
postItineraryShareLinkRotate({ itinerary_id, idempotencyKey? }){ data: ShareLink }Rotate the itinerary's share link.
postItineraryWaypoint({ itinerary_id, body: WaypointCreateParams, idempotencyKey?, ifMatch? }){ data: ItineraryWithDetails }Create a new waypoint within an itinerary.

mountaya.studio.layers

MethodResolves toSummary
getLayers({ query? }?){ data: Layers }List terrains, overlays, and the zone layer.

mountaya.studio.zones

MethodResolves toSummary
deleteZone({ zone_id, idempotencyKey?, ifMatch? }){ data: null }Delete a zone.
deleteZonePublication({ zone_id, idempotencyKey?, ifMatch? }){ data: Zone }Take the zone's publication down.
getZone({ zone_id, query? }){ data: Zone }Retrieve a single zone with its geometry.
getZones({ query? }?){ data: Zone[] }List zones.
patchZone({ zone_id, body: ZoneUpdateParams, idempotencyKey?, ifMatch? }){ data: Zone }Update an existing zone.
postZone({ body: ZoneCreateParams, idempotencyKey? }){ data: Zone }Create a new zone.
postZonePublication({ zone_id, idempotencyKey?, ifMatch? }){ data: Zone }Publish the zone's current draft.

mountaya.admin

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.

mountaya.admin.billing

MethodResolves toSummary
deleteOrganizationBillingPaymentMethod({ organization_id, payment_method_id, idempotencyKey? }){ data: null }Detach a payment method from an organization.
deleteOrganizationBillingSubscription({ organization_id, idempotencyKey? }){ data: OrganizationSubscriptionSummary | null }End an organization's Data API subscription at the end of its period.
getBillingProducts(){ data: BillingProduct[] }List the billing catalog.
getOrganizationBillingInfo({ organization_id }){ data: BillingInfo | null }Retrieve an organization's billing information.
getOrganizationBillingInvoices({ organization_id, query? }){ data: Invoice[] }List an organization's invoices.
getOrganizationBillingPaymentMethods({ organization_id, query? }){ data: PaymentMethod[] }List an organization's saved payment methods.
getOrganizationBillingPromotionCode({ organization_id, code }){ data: PromotionCodePreview }Check what a promotion code is worth to an organization.
getOrganizationBillingSubscription({ organization_id }){ data: OrganizationSubscriptionSummary | null }Retrieve an organization's subscription.
patchOrganizationBillingInfo({ organization_id, body: BillingInfoUpdateParams, idempotencyKey? }){ data: BillingInfo }Update an organization's billing information.
postOrganizationBillingPaymentMethod({ organization_id, body: OrganizationBillingPaymentMethodParams, idempotencyKey? }){ data: PaymentMethod }Save a confirmed card against an organization.
postOrganizationBillingPaymentMethodSetDefault({ organization_id, payment_method_id, idempotencyKey? }){ data: PaymentMethod }Choose which payment method an organization is charged on.
postOrganizationBillingPaymentMethodSetup({ organization_id, idempotencyKey? }){ data: SetupIntentSession }Start collecting a card for an organization.
postOrganizationBillingProvision({ organization_id, body: OrganizationBillingProvisionParams, idempotencyKey? }){ data: BillingInfo }Open an organization's billing.
postOrganizationBillingSubscription({ organization_id, idempotencyKey? }){ data: OrganizationSubscriptionSummary }Run an organization's Data API subscription.

mountaya.admin.invitations

MethodResolves toSummary
deleteOrganizationInvitation({ organization_id, invitation_id, idempotencyKey? }){ data: null }Withdraw a pending invitation.
getOrganizationInvitation({ organization_id, invitation_id }){ data: OrganizationInvitation }Retrieve a pending invitation.
getOrganizationInvitations({ organization_id, query? }){ data: OrganizationInvitation[] }List an organization's pending invitations.
postOrganizationInvitation({ organization_id, body: OrganizationInvitationCreateParams, idempotencyKey? }){ data: OrganizationInvitation }Invite somebody to an organization by email.

mountaya.admin.keys

MethodResolves toSummary
deleteOrganizationPublishableKey({ organization_id, key_id, idempotencyKey?, ifMatch? }){ data: PublishableKey }Revoke a publishable key.
getOrganizationPublishableKey({ organization_id, key_id }){ data: PublishableKey }Retrieve a publishable key.
getOrganizationPublishableKeys({ organization_id, query? }){ data: PublishableKey[] }List an organization's publishable keys.
patchOrganizationPublishableKey({ organization_id, key_id, body: PublishableKeyUpdateParams, idempotencyKey?, ifMatch? }){ data: PublishableKey }Update a publishable key's name or scopes.
postOrganizationPublishableKey({ organization_id, body: PublishableKeyCreateParams, idempotencyKey? }){ data: PublishableKey }Create a publishable key.

mountaya.admin.members

MethodResolves toSummary
deleteOrganizationMember({ organization_id, user_id, idempotencyKey? }){ data: null }Remove a member from an organization, or leave it.
getOrganizationMembers({ organization_id, query? }){ data: OrganizationMember[] }List an organization's members.
patchOrganizationMember({ organization_id, user_id, body: OrganizationMemberUpdateParams, idempotencyKey? }){ data: OrganizationMember }Change a member's role.

mountaya.admin.organizations

MethodResolves toSummary
deleteOrganizationAiProviderConfig({ organization_id, idempotencyKey?, ifMatch? }){ data: null }Delete an organization's AI provider configuration.
getAiProviders(){ data: AiProviderCatalog[] }List the AI provider catalog.
getOrganization({ organization_id }){ data: Organization }Retrieve an organization.
getOrganizationAiProviderConfig({ organization_id }){ data: AiProviderConfig | null }Retrieve an organization's AI provider configuration.
getOrganizationSettings({ organization_id }){ data: OrganizationSettings }Retrieve an organization's Map Publishing settings.
getOrganizationUsageData({ organization_id, query? }){ data: UsageDataPoint[] }Retrieve an organization's data usage.
getOrganizationUsageTiles({ organization_id, query? }){ data: UsageTilePoint[] }Retrieve an organization's Tile API usage.
patchOrganization({ organization_id, body: OrganizationUpdateParams, idempotencyKey?, ifMatch? }){ data: Organization }Update an organization.
patchOrganizationAiProviderConfig({ organization_id, body: AiProviderConfigUpdateParams, idempotencyKey?, ifMatch? }){ data: AiProviderConfig }Update an organization's AI provider configuration.
patchOrganizationSettings({ organization_id, body: OrganizationSettingsPatchParams, idempotencyKey?, ifMatch? }){ data: OrganizationSettings }Update an organization's Map Publishing settings.
postOrganization({ body: OrganizationCreateParams, idempotencyKey? }){ data: Organization }Create an organization.
postOrganizationAiProviderConfig({ organization_id, body: AiProviderConfigCreateParams, idempotencyKey? }){ data: AiProviderConfig }Configure an organization's AI provider.
postOrganizationLookup({ body: OrganizationLookupParams }){ data: Organization }Resolve the organization a publishable key belongs to.

mountaya.admin.sessions

MethodResolves toSummary
postSession({ body: SessionCreateParams }){ data: Session }Create a session token using a secret key.

mountaya.admin.users

MethodResolves toSummary
deleteMyInvitation({ invitation_id, idempotencyKey? }){ data: null }Decline an invitation.
getMyInvitations({ query? }?){ data: UserInvitation[] }List the invitations waiting for the acting user.
getMyOrganizationNotificationPreferences({ organization_id }){ data: NotificationPreferences }Retrieve the acting user's notification emails for an organization.
getMyOrganizations({ query? }?){ data: Membership[] }List the acting user's memberships.
getMyPreferences(){ data: Preferences }Retrieve the acting user's display preferences.
patchMyOrganizationNotificationPreferences({ organization_id, body: NotificationPreferencesUpdateParams, idempotencyKey? }){ data: NotificationPreferences }Turn the acting user's notification emails for an organization on or off.
patchMyPreferences({ body: PreferencesUpdateParams, idempotencyKey? }){ data: Preferences }Update the acting user's display preferences.
postMyInvitationAccept({ invitation_id, idempotencyKey? }){ data: Membership }Accept an invitation.

mountaya.admin.webhooks

MethodResolves toSummary
deleteOrganizationWebhookEndpoint({ organization_id, webhook_endpoint_id, idempotencyKey?, ifMatch? }){ data: null }Delete a webhook endpoint.
getOrganizationWebhookDeliveries({ organization_id, query? }){ data: WebhookDelivery[] }List an organization's webhook deliveries.
getOrganizationWebhookDelivery({ organization_id, delivery_id }){ data: WebhookDeliveryWithAttempts }Retrieve a webhook delivery with its attempts.
getOrganizationWebhookEndpoint({ organization_id, webhook_endpoint_id }){ data: WebhookEndpoint }Retrieve a webhook endpoint.
getOrganizationWebhookEndpoints({ organization_id, query? }){ data: WebhookEndpoint[] }List an organization's webhook endpoints.
getOrganizationWebhookEvent({ organization_id, event_id }){ data: WebhookEventWithDeliveries }Retrieve a webhook event with its deliveries.
getOrganizationWebhookEvents({ organization_id, query? }){ data: WebhookEvent[] }List an organization's webhook events.
getOrganizationWebhookHealth({ organization_id, query? }){ data: WebhookHealth }Retrieve the reliability of an organization's webhooks.
getWebhookEventTypes(){ data: WebhookEventCatalogEntry[] }List the public webhook event types.
patchOrganizationWebhookEndpoint({ organization_id, webhook_endpoint_id, body: WebhookEndpointUpdateParams, idempotencyKey?, ifMatch? }){ data: WebhookEndpoint }Update a webhook endpoint.
postOrganizationWebhookDelivery({ organization_id, body: WebhookDeliveryCreateParams, idempotencyKey? }){ data: WebhookDeliveryTrigger }Resend an event, send a test event, or redeliver an endpoint's events.
postOrganizationWebhookEndpoint({ organization_id, body: WebhookEndpointCreateParams, idempotencyKey? }){ data: WebhookEndpointWithSecret }Create a webhook endpoint.

mountaya.agent

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.

mountaya.agent.runs

MethodResolves toSummary
getAgentRunEvents({ run_id })BinaryBodyStream an agent run's events over Server-Sent Events.
postAgentRun({ body: AgentRunCreateParams, idempotencyKey? }){ data: AgentRun }Start a new agent run.
postAgentRunFeedback({ run_id, body: AgentRunFeedbackParams, idempotencyKey? }){ data: null }Record the user's rating of one assistant message in a run.
postAgentRunInput({ run_id, body: AgentRunInputParams, idempotencyKey? }){ data: null }Send an input signal into a running agent run.

mountaya.tiles

The Tile API's style specifications. Each method resolves to the response envelope.

MethodResolves toSummary
getCollectionSpecification({ collection_id, query? }){ data: TileSpecification }Retrieve the tile specification for a collection.
getItinerariesSpecification(){ data: TileSpecification }Retrieve the tile specification for the organization's itineraries.
getItinerarySpecification({ itinerary_id }){ data: TileSpecification }Retrieve the tile specification for a single itinerary.
getOverlaySpecification({ overlay, query? }){ data: TileSpecification }Retrieve the tile specification for a map overlay.
getTileLayers({ query? }?){ data: Layers }List the terrains, overlays and layers this API draws.
getZonesSpecification(){ data: TileSpecification }Retrieve the tile specification for the organization's zones.

mountaya.data

The GraphQL Data API: directions, search, terrain, isochrones, matrices. Each method resolves to the operation's own field, with no envelope.

MethodResolves toSummary
analyzeGeometry(input: AnalyzeGeometryInput, options?)AnalyzeGeometryResultAnalyze surface and way type of an existing geometry.
directions(input: DirectionsInput, options?)DirectionsResultCompute directions between waypoints for a given activity.
exportItinerary(input: ExportItineraryInput, options?)ExportItineraryResultPrepare a download of an itinerary in a route file format.
geocode(input: GeocodeInput, options?)GeocodeResultForward geocode a free-text query into a list of named places.
isochrones(input: IsochronesInput, options?)IsochronesResultCompute isochrones (reachability polygons) from one or more locations for a given activity.
itinerary(input: ItineraryInput, options?)ItineraryResultRead a single itinerary by identifier, with its ordered segments and waypoints.
matrix(input: MatrixInput, options?)MatrixResultCompute a time-distance matrix between locations for a given activity.
pois(input: PoisInput, options?)PoisResultList points-of-interest matching one or more categories inside a bounding box or a buffered geometry.
reverseGeocode(input: ReverseGeocodeInput, options?)ReverseGeocodeResultReverse geocode a [longitude, latitude] point into a list of named places.
search(input: SearchInput, options?)SearchResultUnified full-text search across geocoded places, POIs, ways, and Mountaya entities (itineraries, collections, zones).
suggestions(input: SuggestionsInput, options?)SuggestionsResultGenerate route suggestions matching distance constraints for a given activity.
terrainGrid(input: TerrainGridInput, options?)TerrainGridResultSample the surface over a rectangular grid inside a bounding box, for area reconnaissance: finding high ground, a steep band, or a slope facing a given direction before routing through it.
terrainProfile(input: TerrainProfileInput, options?)TerrainProfileResultSample the surface along a geometry at a fixed interval, producing an elevation profile as data.
terrainSamples(input: TerrainSamplesInput, options?)TerrainSamplesResultSample elevation, slope, and aspect at standalone [longitude, latitude] points.

mountaya.transport

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.

Errors

Every error the client throws extends MountayaError. Catch the class, or test a value with isMountayaError or isMountayaApiError.

ClassExtendsSummary
MountayaApiErrorMountayaErrorMountayaApiError is any error the API itself reported, carrying the HTTP status, the parsed envelope entries, the envelope's metadata where it sent any, the answer's request id, the rate-limit state it describes and the wait its Retry-After names.
MountayaAuthenticationErrorMountayaApiError401: the credential is missing, malformed, unknown, rotated or disabled.
MountayaBadRequestErrorMountayaApiError400: the request was malformed or a field failed validation.
MountayaBillingErrorMountayaApiError402: the organization does not hold the product the call needs, such as Map Studio for a write into one of its itineraries; or, on the Data API, a self-serve organization has no payment method on file, or still owes invoices its payment method could not pay, which keep a subscription from opening.
MountayaConfigurationErrorMountayaErrorMountayaConfigurationError is thrown when the client is set up in a way that cannot work, and before any request is made wherever that can be known: no credential (an empty or blank key included), a credential whose prefix does not match its slot, a secret key in a browser, or an option outside its range (a timeoutMs, a retry member, a baseUrls entry).
MountayaConflictErrorMountayaApiError409: the write conflicts with the current state of the resource: a lock another member holds, a write that landed first, a name already taken, or a state that forbids the act, as the shape of an itinerary's chain forbids deleting one of its interior segments.
MountayaConnectionErrorMountayaErrorMountayaConnectionError wraps a transport failure: DNS, TLS, a dropped socket, an attempt that had no response within its timeoutMs (the call's, or else the client's), a wait for the first session token that the mint did not answer within it, a stream open with no response within its bound, a stream that delivered nothing (not even the heartbeat comment the API writes to every live stream) for its stall window, a response whose body broke off before it was complete, a success whose body is not JSON on a call that answers JSON (on REST, the Tile API and the Data API alike), or an ok answer to a stream open that carries no body.
MountayaDataErrorMountayaApiErrorMountayaDataError is a Data API failure the API reported in a GraphQL envelope carried by a SUCCESS: a 200 whose errors say the operation did not happen, or one with no data at all.
MountayaErrorErrorMountayaError is the base of every error this package throws.
MountayaForbiddenErrorMountayaApiError403: the caller may not do this, whatever the organization's agreement holds.
MountayaIdempotencyKeyInUseErrorMountayaConflictErrorMountayaIdempotencyKeyInUseError is the 409 whose first entry is coded IDEMPOTENCY_KEY_IN_USE: the first request with this key is still running; send the same call again with the same key.
MountayaIdempotentAnswerUnavailableErrorMountayaConflictErrorMountayaIdempotentAnswerUnavailableError is the 409 whose first entry is coded IDEMPOTENCY_ANSWER_UNAVAILABLE: the write was made; re-read the resource.
MountayaMethodNotAllowedErrorMountayaApiError405: the path exists and does not answer that method.
MountayaNotFoundErrorMountayaApiError404: no such resource, or none the caller is allowed to know exists.
MountayaPayloadTooLargeErrorMountayaApiError413: the request body exceeds the accepted size.
MountayaPreconditionFailedErrorMountayaApiError412: a conditional write whose ifMatch names a tag the resource no longer carries.
MountayaRateLimitErrorMountayaApiError429: a limit is spent, or a ceiling is reached.
MountayaServerErrorMountayaApiError5xx: the API failed.
MountayaSelectionErrorMountayaErrorMountayaSelectionError is a selection that names something the schema does not have.
MountayaWebhookSignatureErrorMountayaErrorMountayaWebhookSignatureError is a webhook delivery constructWebhookEvent cannot trust: a signature header missing or malformed, a signature no v1 matches, or a timestamp outside the tolerance.

Functions

decodeRestSchema

decodeRestSchema<N>(schema, json)

schema

N

required

A name under RestSchema.components["schemas"], such as "ItineraryWithDetails".

json

unknown

required

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

errorForStatus picks the class a status maps to, for a caller holding a status and no Response to read.

errorForStatus(message, status, entries?, details?)

message

string

required

The error's message, as failureMessage spells one.

status

number

required

The HTTP status the response carried.

entries

readonly 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.

details

ApiErrorDetails

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.

name

string

required
status

number

required

The HTTP status the response carried.

errors

readonly ErrorEntry[]

required

Every entry of the envelope, in the order the API wrote them; empty for a bodiless answer.

metadata

ErrorMetadata

The envelope's extensions.metadata, exactly as sent, or undefined where the response carried none: see ErrorMetadata.

rateLimit

RateLimitInfo

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.

requestId

string

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.

retryAfter

number

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.

code

ErrorCode | undefined

required

The classifying code of the response, taken from its first entry.

hasCode

(code: ErrorCode) => boolean

required

Reports whether any entry carries the given code.

idempotencyKey

string

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

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)

error

unknown

required

Returns error is MountayaApiError

isMountayaError

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)

error

unknown

required

Returns error is MountayaError

paginate

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>>

required

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).

args

NonNullable<A>

required

The operation's own arguments: its path parameters, and any filter, sort or starting cursor under query. {} for an operation that requires none.

options

PaginateOptions

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

parseRateLimit reads the rate-limit state an answer's headers describe, or undefined where they describe none.

parseRateLimit(headers)

headers

Pick<Headers, "get">

required

The answer's headers, as a Response carries them.

Returns RateLimitInfo | undefined: The state, or undefined where the answer describes no policy.

policies

readonly RateLimitPolicy[]

required

The policies the answer was counted against, never empty.

boundFetch

boundFetch resolves the fetch implementation a caller issues requests through, keeping the global one callable through a local binding.

boundFetch(fetchImpl?)

fetchImpl

typeof 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

constructWebhookEvent verifies a webhook delivery's signature and answers the event its body holds, typed by its type.

constructWebhookEvent(rawBody, signatureHeader, secret, options?)

rawBody

string | Uint8Array

required

The request body, exactly as it arrived.

signatureHeader

string | null | undefined

required

The request's Mountaya-Signature header, as request.headers.get answers it: null or undefined where the request carries none.

secret

string

required

The signing secret of the endpoint the delivery was sent to, whsk_ included.

options

ConstructWebhookEventOptions

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.

Classes

SessionTokenEngine

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.

new SessionTokenEngine

Builds an engine over the application's mint. It mints nothing until something subscribes.

new SessionTokenEngine(options)

options

SessionTokenEngineOptions

required

getSnapshot

getSnapshot returns the current snapshot, by reference and stable between changes.

getSnapshot()

Returns SessionTokenSnapshot

error

unknown

required

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.

expiresAt

Date | undefined

required

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.

isLoading

boolean

required

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.

token

string | undefined

required

The current token, or undefined before the first mint completes.

userId

string | null | undefined

required

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

subscribe registers a listener for every change, and returns its own unsubscribe.

subscribe(listener)

listener

() => void

required

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

refresh mints now, replacing any pending refresh, or joins the mint already out.

refresh()

checkNow

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

setMint replaces the callback without disturbing the schedule.

setMint(mint)

mint

() => Promise<Session>

required

setEnabled

setEnabled turns minting on or off.

setEnabled(enabled)

enabled

boolean

required

dispose

dispose retires the in-flight mint, drops the timer, clears the token and latches the engine shut.

dispose()

MountayaTransport

new MountayaTransport

Builds a transport over one credential and its options, checking both before anything is sent.

new MountayaTransport(options)

options

ClientOptions

required

Its fields are listed under new Mountaya.

PropertyTypeSummary
mapCredential{ readonly cookie?: boolean | undefined; readonly publishableKey?: string | undefined; readonly sessionToken?: string | undefined; readonly shareToken?: string | undefined }mapCredential projects the browser-safe half of this transport's credential, for a renderer that has to authenticate requests it makes for itself.
streamSeamStreamSeam
credentialScopestringcredentialScope identifies WHICH credential this transport holds and WHO it acts as, for a cache key.
credentialScopePendingbooleancredentialScopePending reports whether credentialScope is still to be told who the session acts as: the credential's SessionTokenSource holds no token and reports one on its way, which it does from its construction until its first mint answers, and again after a sign-out while the next person's mint is out.
actsAsMemberboolean | undefinedactsAsMember reports whether a call that acts as a member can be made under this transport's credential now, as far as the client is told: true where its session source reports a token minted for a user, false where it reports one minted for nobody, and where the credential carries no session token at all (a bare publishable key, a secret key, a share token), and undefined where the client is not told, as under a token held as a string or a function, a source that reports no user, or the browser's own session.
reachesSessionOperationsbooleanreachesSessionOperations reports whether this transport can make the operations that require a session token: every Data API request, and every management and studio-embedded operation of the Map Studio API, the writes and the collaboration and agent streams among them.
tilesBaseUrlstringtilesBaseUrl is the origin the Tile API is being reached at.
requestLanguagestring | undefinedrequestLanguage is the Accept-Language this transport sends, or undefined.

applyAuth

applyAuth folds this transport's credential into a RequestInit, for a call this client does not make itself.

applyAuth(init?, method?, declaration?)

init

RequestInit

default: {}

method

string

default: "GET"

declaration

StreamDeclaration

default: {}

Returns RequestInit

subscribeCredentialScope

subscribeCredentialScope registers a listener told each time credentialScope or credentialScopePending moves, and returns its release.

subscribeCredentialScope(listener)

listener

() => void

required

Called with no argument after each move of the scope or of its pending flag.

Returns () => void: The function that removes the listener.

requestRaw

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)

args

RequestArgs

required

Returns Promise<Response>

request

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)

args

RequestArgs

required

Its fields are listed under requestRaw.

Returns Promise<T>

requestBinary

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)

args

RequestArgs

required

Its fields are listed under requestRaw.

Returns Promise<BinaryBody>

bytes

ArrayBuffer

required

The body, whole, as it arrived.

contentType

string

The response's Content-Type, verbatim, when the response carried one.

filename

string

The download filename from Content-Disposition, when the response carried one.

Constants

NameSummary
PAYMENT_REQUIRED_CODEPAYMENT_REQUIRED_CODE is the code of a 402, the status MountayaBillingError stands for: a product the organization does not hold, or, on the Data API, a self-serve organization with no payment method on file or with invoices still owed.
defaultBaseUrls
SCHEMA_VERSIONSCHEMA_VERSION is the mountayaapp/schemas tag this client was generated from.

Namespaces

NameSummary
dataThe Data API operations as free functions, each taking the transport first. Import one for the smallest bundle.
DataSchemaThe Data API's generated input and result types.
DataSelectionThe selectable field tree of each Data API operation.
restThe Map Studio API operations as free functions, each taking the transport first.
RestSchemaThe Map Studio API's generated wire types.
tilesThe Tile API operations as free functions, each taking the transport first.
TileSchemaThe Tile API's generated wire types.

@mountaya/client/browser

The browser-safe entry point of @mountaya/client.

@mountaya/client/events

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

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

createAgentTransport binds an agent run's endpoints to one client's transport.

createAgentTransport(transport)

transport

MountayaTransport

required

Returns AgentTransport

sendInput

(runId: string, input: AgentInput, options?: AgentWriteOptions) => Promise<void>

required

sendInput delivers one input signal into a running run, resolving once the API took it.

startRun

(params: AgentRunCreateParams, options?: AgentWriteOptions) => Promise<{ runId: string }>

required

startRun starts a run and answers its id, which sendInput and subscribe take.

subscribe

(runId: string, handlers: AgentStreamHandlers, options?: AgentSubscribeOptions) => () => void

required

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

decodeAgentFrame turns one raw SSE frame into a typed event, or null to skip it.

decodeAgentFrame(frame)

frame

SseFrame

required

Returns AgentEvent | null

createCollabTransport

createCollabTransport binds the collaboration streams to one client's transport.

createCollabTransport(transport)

transport

MountayaTransport

required

Its fields are listed under createAgentTransport.

Returns CollabTransport

sendSignal

(resource: CollabStreamResource, signal: CollabSignal) => Promise<CollabSignalResult>

required

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

required

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

required

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

decodeCollabFrame turns one raw SSE frame into a typed event, or null to skip it.

decodeCollabFrame(frame)

frame

SseFrame

required

Its fields are listed under decodeAgentFrame.

Returns CollabEvent | null

readEventStream

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?)

body

ReadableStream<Uint8Array>

required
onFrame

FrameHandler

required
onLastEventId

(lastEventId: string) => void

Returns Promise<EventStreamOutcome>

openSseStream

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)

options

OpenSseStreamOptions<TEvent>

required

Returns (() => void)

MAX_SSE_BUFFER_CHARS

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

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.

new SseBufferOverflowError

Builds the error a parser throws once its unterminated record passes the cap.

new SseBufferOverflowError(limit, operationId?, options?)

limit

number

required
operationId

string

options

ErrorOptions

PropertyTypeSummary
name"SseBufferOverflowError"
limitnumberThe cap the parser enforced, in UTF-16 code units.

SseFrameParser

SseFrameParser frames the text of a text/event-stream body into records, by the HTML standard's event-stream rules:

new SseFrameParser

Builds a parser that holds at most maxBufferChars of a record it has not seen the end of.

new SseFrameParser(maxBufferChars?)

maxBufferChars

number

default: MAX_SSE_BUFFER_CHARS

PropertyTypeSummary
lastEventIdstring | undefinedlastEventId is the stream's last event ID, as the HTML standard defines it: the value of the latest id: in a record the parser has seen the end of, whatever else that record carried.

push

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)

chunk

string

required

Returns SseFrame[]