Sign in

    notionsdk

    A moonbit client for the Notion API. This reference covers the SDK's methods, options, and helpers.

    notion
    notionapi
    rest
    notion-api
    Download zip
    Author
    Version
    0.1.2
    License
    MIT
    Last updated
    10 days ago
    Downloads
    19

    No dependencies

    #kupas/notionsdk

    A MoonBit port of @notionhq/client (the Notion SDK for JavaScript). It keeps the API surface and the request logic of the original: the same endpoints, the same parameter filtering, the same headers, the same retry rules, the same error codes and the same webhook signature scheme.

    What changes is the language and the transport. Payload objects travel as Json, and the client never calls the network itself — you hand it a fetch function. That keeps the SDK usable on every runtime and trivial to test.

    #Quick start

    ///|
    fn main {
    let fetch : @notionsdk.Fetch = (url, init) => {
    // Connect a real HTTP stack here (for example one built on
    // moonbitlang/async) and return an HttpResponse.
    @notionsdk.HttpResponse::from_text(
    status=200,
    headers=[],
    body="{\"object\":\"user\",\"id\":\"u1\"}",
    )
    }

    let client = @notionsdk.Client::new(
    options=@notionsdk.ClientOptions::new(
    auth=Some("secret_your_integration_token"),
    fetch=Some(fetch),
    ),
    )

    let me = (client.users().me)({})
    println(me.stringify())
    }

    There is a runnable version of this in cmd/main: moon run cmd/main.

    Resource calls mirror the JavaScript client:

    ///|
    let page = (client.pages().create)({
    "parent": { "page_id": parent },
    "properties": {},
    })

    ///|
    let block = (client.blocks().retrieve)({ "block_id": block_id })

    ///|
    let results = (client.search().search)({ "query": "roadmap" })

    ///|
    let events = (client.sessions().stream)({ "message": "hi" })

    The resource accessors are users(), pages(), blocks(), databases(), data_sources(), comments(), file_uploads(), views(), search(), agents(), async_tasks(), plugins(), skills(), sessions() and oauth().

    #What maps to what

    TypeScript sourceMoonBit file
    src/Client.tsClient.mbt
    src/api-endpoint-methods.tsapi_endpoint_methods.mbt
    src/api-endpoints.ts + src/api-endpoints/*.tsapi-endpoints/*.mbt
    src/errors.tserrors.mbt
    src/helpers.tshelpers.mbt
    src/utils.tsutils.mbt
    src/logging.tslogging.mbt
    src/constants.tsconstants.mbt
    src/fetch-types.tsfetch_types.mbt
    src/webhooks.tswebhooks.mbt (+ sha256.mbt)

    The object types in the original are generated and enormous. Rather than transcribe them, this port carries payloads as Json; api-endpoints/ keeps the part that drives behavior — the HTTP method, the path, and the path/query/body/ form-data parameter names.

    #Documentation

    • docs/API.md — reference for every method: HTTP verb, path, parameters and usage examples.

    #Error handling

    Every failure is a NotionClientError wrapping a NotionError with code, message, status, headers, body, additional_data, request_id and ray_id, matching the TypeScript error fields.

    ///|
    let response = (client.pages().retrieve)({ "page_id": id }) catch {
    @notionsdk.NotionClientError(error) => {
    if error.code == "object_not_found" {
    // handle a missing page
    }
    @notionsdk.Json::null()
    }
    _ => @notionsdk.Json::null()
    }

    Helpers: is_notion_client_error, is_http_response_error, is_api_response_error, APIErrorCode::from_string, ClientErrorCode::to_string.

    #Pagination

    The JavaScript for await helpers collect into arrays here:

    ///|
    let blocks = @notionsdk.collect_paginated_api(
    args => (client.blocks().children_list)(args),
    { "block_id": parent },
    )

    collect_data_source_templates and collect_all_data_source_rows are also provided. The latter reproduces the created_time-window algorithm that walks past the per-query result limit.

    The response type guards from helpers.ts are available as well: is_full_page, is_full_block, is_full_database, is_full_data_source, is_full_user, is_full_comment, is_full_view, is_full_page_or_data_source.

    extract_notion_id, extract_page_id, extract_database_id and extract_block_id parse IDs out of URLs.

    #Webhooks

    ///|
    let ok = @notionsdk.verify_webhook_signature({
    body: raw_body,
    signature: Some(header_value),
    verification_token: token,
    })

    sign_webhook_payload produces the value Notion would send, so handlers can be tested without a live subscription. HMAC-SHA256 is implemented in sha256.mbt because MoonBit core ships no digest package.

    #Retries and timeouts

    The retry rules match the original: rate limits (rate_limited, 429) and service overloads (service_overload, 529) are retried for every method; server errors (internal_server_error, service_unavailable) only for idempotent get/delete requests. Delays use the retry-after header in delta-seconds form, otherwise exponential back-off with jitter. Configure with ClientOptions::new(retry=Some(false)), max_retries, initial_retry_delay_ms and max_retry_delay_ms.

    timeout_ms is passed to the transport (a synchronous Fetch cannot be interrupted from the outside). sleep and random are injectable so retry behavior can be tested without real waiting or nondeterminism.

    #Differences from the JavaScript SDK

    • No HTTP stack is bundled; supply fetch.
    • The transport is synchronous, so timeout_ms is a hint to the transport rather than a client-side timer.
    • Server-sent events from sessions().stream are buffered and returned as an array instead of yielded as an async iterator.
    • HTTP-date retry-after values are not parsed; delta-seconds are.
    • Browser detection is an explicit browser_environment option rather than runtime sniffing, so the token guard stays testable.

    #Tests

    moon test

    The suite covers request construction, retries, the browser token guard, path traversal validation, error parsing, ID extraction, pagination, and SHA-256, HMAC and webhook signatures against known vectors.

    Fetch

    type Fetch = (String, HttpRequestInit) -> HttpResponse raise

    A fetch-compatible function.

    The first argument is the absolute URL, the second the request options.

    Logger

    type Logger = (LogLevel, String, Json) -> Unit

    A logger receives a level, a message, and extra structured information.

    NotionClientError

    pub(all) suberror NotionClientError {
    NotionClientError(NotionError)
    }

    The error type that encompasses every failure the Notion client raises.

    APIErrorCode

    pub(all) enum APIErrorCode {
    Unauthorized
    RestrictedResource
    ObjectNotFound
    RateLimited
    InvalidJson
    InvalidRequestUrl
    InvalidRequest
    InvalidBeta
    ValidationError
    ConflictError
    InternalServerError
    ServiceOverload
    ServiceUnavailable
    GatewayTimeout
    }

    Error codes returned in responses from the API.

    APIErrorCode::from_string

    fn APIErrorCode::from_string(value : String) -> APIErrorCode?

    Parses an API error code from its wire value.

    APIErrorCode::to_string

    fn APIErrorCode::to_string(self : APIErrorCode) -> String

    The wire value of an API error code.

    AgentsEndpointMethods

    pub struct AgentsEndpointMethods {
    query : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    delete : (Json) -> Json raise
    retrieve_insights : (Json) -> Json raise
    update_status : (Json) -> Json raise
    update_credit_limit : (Json) -> Json raise
    batch : (Json) -> Json raise
    }

    Resource methods for agents.

    AsyncTasksEndpointMethods

    pub struct AsyncTasksEndpointMethods {
    retrieve : (Json) -> Json raise
    }

    Resource methods for asyncTasks.

    BlocksEndpointMethods

    pub struct BlocksEndpointMethods {
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    delete : (Json) -> Json raise
    children_list : (Json) -> Json raise
    children_append : (Json) -> Json raise
    meeting_notes_create : (Json) -> Json raise
    meeting_notes_query : (Json) -> Json raise
    }

    Resource methods for blocks.

    Client

    pub struct Client {
    // private fields
    }

    The Notion API client.

    Client::agents

    fn Client::agents(self : Client) -> AgentsEndpointMethods

    Client::async_tasks

    fn Client::async_tasks(self : Client) -> AsyncTasksEndpointMethods

    Client::blocks

    fn Client::blocks(self : Client) -> BlocksEndpointMethods

    Client::comments

    fn Client::comments(self : Client) -> CommentsEndpointMethods

    Client::data_sources

    fn Client::data_sources(self : Client) -> DataSourcesEndpointMethods

    Client::databases

    fn Client::databases(self : Client) -> DatabasesEndpointMethods

    Client::file_uploads

    fn Client::file_uploads(self : Client) -> FileUploadsEndpointMethods

    Client::new

    fn Client::new(options? : ClientOptions) -> Client

    Creates a client.

    Client::oauth

    fn Client::oauth(self : Client) -> OauthEndpointMethods

    Client::pages

    fn Client::pages(self : Client) -> PagesEndpointMethods

    Client::plugins

    fn Client::plugins(self : Client) -> PluginsEndpointMethods

    Client::request

    fn Client::request(self : Client, args : RequestParameters) -> Json raise

    Sends a request and returns the parsed JSON response body.

    Client::search

    fn Client::search(self : Client) -> SearchEndpointMethods

    Client::sessions

    fn Client::sessions(self : Client) -> SessionsEndpointMethods

    Client::skills

    fn Client::skills(self : Client) -> SkillsEndpointMethods

    Client::stream_request

    fn Client::stream_request(self : Client, args : RequestParameters, parse_event : (SseFrame) -> Json raise) -> Array[Json] raise

    Opens an SSE response and returns each parsed event.

    The TypeScript client streams frames as they arrive. This port reads the transport's full body first and then splits it, which is equivalent for the events the sessions stream delivers.

    Client::users

    fn Client::users(self : Client) -> UsersEndpointMethods

    The resource clients, each bound to this client.

    Client::views

    fn Client::views(self : Client) -> ViewsEndpointMethods

    ClientErrorCode

    pub(all) enum ClientErrorCode {
    RequestTimeout
    ResponseError
    InvalidPathParameter
    }

    Error codes generated for client errors.

    ClientErrorCode::to_string

    fn ClientErrorCode::to_string(self : ClientErrorCode) -> String

    The wire value of a client error code.

    ClientOptions

    pub(all) struct ClientOptions {
    auth : String?
    timeout_ms : Int
    base_url : String
    log_level : LogLevel
    logger : (LogLevel, String, Json) -> Unit?
    notion_version : String
    fetch : (String, HttpRequestInit) -> HttpResponse raise?
    retry : Bool?
    max_retries : Int
    initial_retry_delay_ms : Int
    max_retry_delay_ms : Int
    dangerously_allow_browser : Bool
    browser_environment : Bool
    sleep : (Int) -> Unit?
    random : () -> Double?
    }

    Options for configuring a Client.

    ClientOptions::new

    fn ClientOptions::new(auth? : String?, timeout_ms? : Int, base_url? : String, log_level? : LogLevel, logger? : (LogLevel, String, Json) -> Unit?, notion_version? : String, fetch? : (String, HttpRequestInit) -> HttpResponse raise?, retry? : Bool?, max_retries? : Int, initial_retry_delay_ms? : Int, max_retry_delay_ms? : Int, dangerously_allow_browser? : Bool, browser_environment? : Bool, sleep? : (Int) -> Unit?, random? : () -> Double?) -> ClientOptions

    Builds ClientOptions, applying the SDK defaults.

    CommentsEndpointMethods

    pub struct CommentsEndpointMethods {
    create : (Json) -> Json raise
    list : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    delete : (Json) -> Json raise
    }

    Resource methods for comments.

    DataSourcesEndpointMethods

    pub struct DataSourcesEndpointMethods {
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    query : (Json) -> Json raise
    create : (Json) -> Json raise
    list_templates : (Json) -> Json raise
    }

    Resource methods for dataSources.

    DatabasesEndpointMethods

    pub struct DatabasesEndpointMethods {
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    create : (Json) -> Json raise
    }

    Resource methods for databases.

    FileUploadsEndpointMethods

    pub struct FileUploadsEndpointMethods {
    create : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    list : (Json) -> Json raise
    send : (Json) -> Json raise
    complete : (Json) -> Json raise
    }

    Resource methods for fileUploads.

    HttpRequestInit

    pub(all) struct HttpRequestInit {
    http_method : String
    headers : Array[(String, String)]
    body : String?
    timeout_ms : Int
    agent : String?
    }

    Options passed to a Fetch implementation.

    HttpResponse

    pub(all) struct HttpResponse {
    ok : Bool
    status : Int
    headers : Array[(String, String)]
    text : () -> String
    }

    The response shape the client reads.

    text returns the response body. It is a function so a transport can defer reading the body until the caller decides to.

    HttpResponse::from_text

    fn HttpResponse::from_text(status~ : Int, headers~ : Array[(String, String)], body~ : String) -> HttpResponse

    Builds an HttpResponse from an already-read body.

    LogLevel

    pub(all) enum LogLevel {
    Debug
    Info
    Warn
    Error
    }

    Log levels, ordered by severity.

    LogLevel::from_string

    fn LogLevel::from_string(value : String) -> LogLevel?

    Parses a log level from its string form.

    LogLevel::to_string

    fn LogLevel::to_string(self : LogLevel) -> String

    The string form of a log level ("debug", "info", "warn", "error").

    NotionError

    pub(all) struct NotionError {
    kind : NotionErrorKind
    code : String
    message : String
    status : Int
    headers : Array[(String, String)]
    body : String
    additional_data : Json?
    request_id : String?
    ray_id : String?
    }

    The fields carried by every error the client raises.

    NotionError::name

    fn NotionError::name(self : NotionError) -> String

    The error class name, e.g. "APIResponseError".

    NotionError::new

    fn NotionError::new(kind~ : NotionErrorKind, code~ : String, message~ : String, status? : Int, headers? : Array[(String, String)], body? : String, additional_data? : Json?, request_id? : String?, ray_id? : String?) -> NotionError

    Builds a NotionError. status, headers and body default to the values used by errors that never reached the API.

    NotionErrorKind

    pub(all) enum NotionErrorKind {
    RequestTimeoutError
    UnknownHTTPResponseError
    ApiResponseError
    InvalidPathParameterError
    BrowserTokenNotAllowedError
    }

    The kind of error, mirroring the TypeScript SDK's error classes.

    NotionErrorKind::name

    fn NotionErrorKind::name(self : NotionErrorKind) -> String

    The name of the error class a kind corresponds to.

    OauthEndpointMethods

    pub struct OauthEndpointMethods {
    token : (Json) -> Json raise
    introspect : (Json) -> Json raise
    revoke : (Json) -> Json raise
    }

    Resource methods for oauth.

    PagesEndpointMethods

    pub struct PagesEndpointMethods {
    create : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    move_page : (Json) -> Json raise
    retrieve_markdown : (Json) -> Json raise
    update_markdown : (Json) -> Json raise
    properties_retrieve : (Json) -> Json raise
    }

    Resource methods for pages.

    PaginatedList

    pub(all) struct PaginatedList {
    results : Array[Json]
    next_cursor : String?
    has_more : Bool
    }

    A page of results from any paginated Notion API.

    ParsedAPIError

    pub(all) struct ParsedAPIError {
    code : APIErrorCode
    message : String
    additional_data : Json?
    request_id : String?
    }

    The structured shape of an API error response body.

    PluginsEndpointMethods

    pub struct PluginsEndpointMethods {
    list : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    }

    Resource methods for plugins.

    RequestAuth

    pub(all) enum RequestAuth {
    Bearer(String)
    Basic(client_id~ : String, client_secret~ : String)
    }

    Authentication for a single request.

    RequestParameters

    pub(all) struct RequestParameters {
    path : String
    http_method : String
    query : Json?
    body : Json?
    form_data_params : Json?
    headers : Array[(String, String)]
    auth : RequestAuth?
    }

    A request to send.

    RequestParameters::new

    fn RequestParameters::new(path~ : String, http_method~ : String, query? : Json?, body? : Json?, form_data_params? : Json?, headers? : Array[(String, String)], auth? : RequestAuth?) -> RequestParameters

    Builds RequestParameters.

    SearchEndpointMethods

    pub struct SearchEndpointMethods {
    search : (Json) -> Json raise
    }

    Arguments to search, exposed as its own resource in the TypeScript client.

    SessionsEndpointMethods

    pub struct SessionsEndpointMethods {
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    stream : (Json) -> Array[Json] raise
    cancel : (Json) -> Json raise
    query : (Json) -> Json raise
    query_events : (Json) -> Json raise
    }

    Resource methods for sessions.

    SkillsEndpointMethods

    pub struct SkillsEndpointMethods {
    retrieve : (Json) -> Json raise
    }

    Resource methods for skills.

    SseFrame

    pub(all) struct SseFrame {
    event_name : String
    data : String
    }

    A parsed server-sent event frame.

    SseFrames

    pub(all) struct SseFrames {
    frames : Array[SseFrame]
    remaining : String
    }

    The result of consuming an SSE buffer.

    UsersEndpointMethods

    pub struct UsersEndpointMethods {
    me : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    list : (Json) -> Json raise
    }

    Resource methods for users.

    VerifyWebhookSignatureArgs

    pub(all) struct VerifyWebhookSignatureArgs {
    body : String
    signature : String?
    verification_token : String
    }

    Arguments for verify_webhook_signature.

    ViewsEndpointMethods

    pub struct ViewsEndpointMethods {
    list : (Json) -> Json raise
    create : (Json) -> Json raise
    retrieve : (Json) -> Json raise
    update : (Json) -> Json raise
    delete : (Json) -> Json raise
    queries_create : (Json) -> Json raise
    queries_results : (Json) -> Json raise
    queries_delete : (Json) -> Json raise
    }

    Resource methods for views.

    api_response_error

    fn api_response_error(code~ : APIErrorCode, message~ : String, status~ : Int, headers~ : Array[(String, String)], body~ : String, additional_data? : Json?, request_id? : String?) -> NotionError

    A response from the API indicating a problem.

    browser_token_not_allowed_error

    fn browser_token_not_allowed_error() -> NotionError

    Error thrown when the client would send a token or client secret from a browser page without dangerouslyAllowBrowser: true.

    build_request_error

    fn build_request_error(response : HttpResponse, body_text : String) -> NotionClientError

    Builds the error to throw for a non-ok HTTP response, preferring the API's structured error body over a generic response error.

    build_unknown_response_message

    fn build_unknown_response_message(status~ : Int, content_type~ : String?, ray_id~ : String?, request_id~ : String?) -> String

    Builds the default message for an unrecognized HTTP response.

    A response with a Cloudflare Ray ID but no Notion request ID was answered before it reached the API.

    bytes_to_hex

    fn bytes_to_hex(bytes : BytesView) -> String

    Returns the lower-case hex encoding of a byte array.

    can_retry

    fn can_retry(error : NotionError, http_method : String) -> Bool

    Determines if an error can be retried based on its error code and method.

    Rate limits (429) and service overloads (529) are always retryable since the server explicitly asks us to retry. Server errors (500, 503) are only retried for idempotent methods (GET, DELETE) to avoid duplicate side effects.

    collect_all_data_source_rows

    fn collect_all_data_source_rows(client : Client, args : Json) -> Array[Json] raise

    Collects every row of a data source, including rows past the per-query result limit.

    A single query (one filter and sort) returns at most a fixed number of rows. Once that limit is reached, has_more becomes false and the response carries request_status.type === "incomplete"; plain pagination stops there and silently misses the rest.

    This helper partitions the data source into created_time windows. It sorts by created_time ascending; whenever a window reaches the limit, it starts a fresh query from the last row's created_time. Rows that share a boundary timestamp are de-duplicated by id, so every row is yielded exactly once.

    collect_data_source_templates

    fn collect_data_source_templates(client : Client, args : Json) -> Array[Json] raise

    Collects every data source template into an in-memory array.

    collect_paginated_api

    fn collect_paginated_api(list_fn : (Json) -> Json raise, first_page_args : Json) -> Array[Json] raise

    Collects all of the results of paginating an API into an in-memory array.

    default_base_url

    let default_base_url : String

    Default base URL for the Notion API.

    Port of DEFAULT_BASE_URL from src/constants.ts.

    default_fetch

    fn default_fetch(_url : String, _init : HttpRequestInit) -> HttpResponse raise

    The default transport. It fails loudly because the MoonBit SDK does not bundle an HTTP stack; pass fetch to ClientOptions to connect one.

    default_initial_retry_delay_ms

    let default_initial_retry_delay_ms : Int

    Default initial delay between retries in milliseconds (1 second). Used as the base for exponential back-off when the retry-after header is absent.

    default_max_retries

    let default_max_retries : Int

    Default maximum number of retry attempts for failed requests.

    default_max_retry_delay_ms

    let default_max_retry_delay_ms : Int

    Default maximum delay between retries in milliseconds (60 seconds). Caps both retry-after and exponential back-off delays.

    default_notion_version

    let default_notion_version : String

    The Notion-Version a client uses when none is configured.

    default_timeout_ms

    let default_timeout_ms : Int

    Default request timeout in milliseconds (60 seconds).

    encode_uri_component

    fn encode_uri_component(value : String) -> String

    Percent-encodes a string the way encodeURIComponent does.

    extract_block_id

    fn extract_block_id(url_with_block : String) -> String?

    Extracts a block ID from a Notion URL with a block fragment. Looks for #block-<id> or #<id> patterns.

    extract_database_id

    fn extract_database_id(database_url : String) -> String?

    Extracts a database ID from a Notion database URL.

    extract_notion_id

    fn extract_notion_id(url_or_id : String) -> String?

    Extracts a Notion ID from a Notion URL, or returns the input if it is already a valid ID. Path IDs are prioritized over query parameters to avoid extracting view IDs instead of database IDs.

    extract_page_id

    fn extract_page_id(page_url : String) -> String?

    Extracts a page ID from a Notion page URL.

    get_response_header

    fn get_response_header(headers : Array[(String, String)], name : String) -> String?

    Reads a header by name, case-insensitively per RFC 9110.

    get_unknown_params

    fn get_unknown_params(args : Json, endpoint :
    EndpointDefinition
    ) -> Array[String]

    Returns parameter names present in args that are not recognized by the endpoint definition. Useful for warning users about typos or parameters that have been renamed across API versions.

    hmac_sha256

    fn hmac_sha256(key : BytesView, message : BytesView) -> Bytes

    Computes HMAC-SHA256 over message using key, returning the 32-byte digest.

    invalid_path_parameter_error

    fn invalid_path_parameter_error(message? : String) -> NotionError

    Error thrown when a path parameter contains invalid characters such as path traversal sequences (..) that could alter the intended API endpoint.

    is_api_error_code

    fn is_api_error_code(value : String) -> Bool

    Whether a string is a known API error code.

    is_api_response_error

    fn is_api_response_error(error : Error) -> Bool

    true if the error is an APIResponseError.

    is_equation_rich_text_item_response

    fn is_equation_rich_text_item_response(rich_text : Json) -> Bool

    true if rich_text is an equation rich text item.

    is_full_block

    fn is_full_block(response : Json) -> Bool

    true if response is a full BlockObjectResponse.

    is_full_comment

    fn is_full_comment(response : Json) -> Bool

    true if response is a full CommentObjectResponse.

    is_full_data_source

    fn is_full_data_source(response : Json) -> Bool

    true if response is a full DataSourceObjectResponse.

    is_full_database

    fn is_full_database(response : Json) -> Bool

    true if response is a full DatabaseObjectResponse.

    is_full_page

    fn is_full_page(response : Json) -> Bool

    true if response is a full PageObjectResponse.

    is_full_page_or_data_source

    fn is_full_page_or_data_source(response : Json) -> Bool

    true if response is a full page or a full data source.

    is_full_user

    fn is_full_user(response : Json) -> Bool

    true if response is a full UserObjectResponse.

    is_full_view

    fn is_full_view(response : Json) -> Bool

    true if response is a full DataSourceViewObjectResponse.

    is_http_response_error

    fn is_http_response_error(error : Error) -> Bool

    true if the error is an HTTP response error (APIResponseError or UnknownHTTPResponseError).

    is_mention_rich_text_item_response

    fn is_mention_rich_text_item_response(rich_text : Json) -> Bool

    true if rich_text is a mention rich text item.

    is_notion_client_error

    fn is_notion_client_error(error : Error) -> Bool

    true if the error is a NotionClientError.

    is_object

    fn is_object(value : Json) -> Bool

    Returns true if value is a JSON object.

    is_text_rich_text_item_response

    fn is_text_rich_text_item_response(rich_text : Json) -> Bool

    true if rich_text is a text rich text item.

    iterate_all_data_source_rows

    fn iterate_all_data_source_rows(client : Client, args : Json) -> Array[Json] raise

    Alias for collect_all_data_source_rows.

    iterate_data_source_templates

    fn iterate_data_source_templates(client : Client, args : Json) -> Array[Json] raise

    Alias for collect_data_source_templates.

    iterate_paginated_api

    fn iterate_paginated_api(list_fn : (Json) -> Json raise, first_page_args : Json) -> Array[Json] raise

    Alias for collect_paginated_api. Present so callers porting TypeScript iteratePaginatedAPI calls have a matching name.

    log_level_severity

    fn log_level_severity(level : LogLevel) -> Int

    Transforms a log level into a comparable (numerical) value ordered by severity.

    make_console_logger

    fn make_console_logger(name : String) -> ((LogLevel, String, Json) -> Unit)

    A logger that writes to standard output.

    min_view_column_width

    let min_view_column_width : Int

    The minimum width of a view column in pixels, used with the views API to make a property column appear minimal / collapsed in the Notion app UI.

    parse_api_error_response_body

    fn parse_api_error_response_body(body : String) -> ParsedAPIError?

    Parses a Notion API error body. Returns None when the body is not JSON or does not carry a message and a known code.

    parse_paginated_list

    fn parse_paginated_list(response : Json) -> PaginatedList

    Reads the pagination fields out of a list response.

    parse_retry_after_header

    fn parse_retry_after_header(headers : Array[(String, String)]) -> Int?

    Parses the retry-after header value in delta-seconds form and returns the delay in milliseconds. HTTP-date values are not supported by this port.

    parse_session_stream_event

    fn parse_session_stream_event(frame : SseFrame) -> Json raise

    Parses a session stream event and checks it against its SSE event name.

    parse_sse_frame

    fn parse_sse_frame(content : String) -> SseFrame? raise

    Parses a single SSE frame. Returns None for frames without a data field, such as comments or keep-alives.

    pick

    fn pick(base : Json, keys : ArrayView[String]) -> Json

    Returns a JSON object with only the given keys from base.

    Mirrors pick from utils.ts: keys that are absent from base are skipped rather than copied as undefined.

    request_timeout_error

    fn request_timeout_error(message? : String) -> NotionError

    Error thrown by the client if a request times out.

    sdk_version

    let sdk_version : String

    A MoonBit port of the Notion SDK for JavaScript.

    The package mirrors the structure and behavior of @notionhq/client:

    • Client owns URL, header and body construction, authentication, logging, retries and server-sent event parsing.
    • api-endpoints/ holds one module per resource with the method, path and parameter lists of every endpoint.
    • errors, helpers, logging, utils, webhooks and constants correspond to the same-named TypeScript modules.

    The transport is injected. Callers connect fetch in ClientOptions, which keeps the SDK usable on any runtime and easy to test. Payload objects travel as Json, so no generated type definitions are needed.

    See README.mbt.md for a walked-through example.

    session_stream_event_types

    let session_stream_event_types : Array[String]

    Event types the sessions stream can carry.

    set_start_cursor

    fn set_start_cursor(args : Json, cursor : String?) -> Json

    Returns a copy of args with start_cursor set (or removed when absent), matching the client's treatment of a null cursor.

    sha256_bytes

    fn sha256_bytes(data : BytesView) -> Bytes

    Computes SHA-256 over the given bytes and returns the 32-byte digest.

    sign_webhook_payload

    fn sign_webhook_payload(body : String, verification_token : String) -> String

    Compute the value Notion would send in X-Notion-Signature for a given body and verification token. Use this to test webhook handlers without a live subscription.

    take_sse_frames

    fn take_sse_frames(content : String, complete : Bool) -> SseFrames raise

    Splits an SSE buffer into complete frames, returning any trailing partial frame so the caller can prepend it to the next chunk.

    unknown_http_response_error

    fn unknown_http_response_error(status~ : Int, headers~ : Array[(String, String)], body~ : String, message? : String?) -> NotionError

    Error thrown if an API call responds with an unknown error code, or does not respond with a property-formatted error.

    validate_request_path

    fn validate_request_path(path : String) -> Unit raise

    Validates that a request path does not contain path traversal sequences. Raises InvalidPathParameterError if the path contains .. segments, including URL-encoded variants like %2e%2e.

    verify_webhook_signature

    fn verify_webhook_signature(args : VerifyWebhookSignatureArgs) -> Bool

    Verify that a webhook delivery came from Notion and has not been tampered with.

    Returns true if the signature matches HMAC-SHA256 of the body using the verification token. Returns false for a missing or malformed signature.