npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ixo/matrixclient-sdk

v0.2.1

Published

An SDK to easily interact with Matrix servers

Downloads

223

Readme

IXO MATRIX CLIENT SDK

ixo GitHub GitHub repo size License: Apache 2.0

Twitter Medium

NodeJSTypeScript

The IXO Matrix Client SDK provides a set of tools for interacting with a Matrix server and associated bot services. With this SDK, developers can query and set Matrix account profiles, manage room details, and work with ACLs and room states using pre-configured or custom home server and bot URLs.

Installation

To install the SDK, add it to your project using npm or yarn:

npm install @ixo/matrixclient-sdk

or

yarn add @ixo/matrixclient-sdk

Getting Started

Once installed, import the SDK components into your project as follows:

import {
  createMatrixApiClient,
  createMatrixRoomBotClient,
  createMatrixStateBotClient,
  utils
} from '@ixo/matrixclient-sdk';

The SDK allows you to create individual clients to interact with different Matrix API and Matrix Bot services. It handles errors by throwing exceptions, so be sure to wrap requests in try...catch blocks.

Matrix API Client

To create a client for interacting with the Matrix API, use the createMatrixApiClient function. This client provides methods for uploading media, managing user profiles and room details.

const matrixApiClient = createMatrixApiClient({
  homeServerUrl: 'https://your-homeserver-url',
  accessToken: 'your-access-token' // optional
});

| Note: The access token is optional but required for protected endpoints. Omitting it will limit functionality to public endpoints.

Media

The media API allows you to upload files such as pdf or images. These files will be public on the homeserver content repository. Here are the main methods:

  • upload: Upload a file.
    const profile = await matrixApiClient.media.v1beta1.upload(
      'profile_image.png', // file name
      'media/png', // content type
      file // file
    );
    console.log(response.content_uri);

| Tip: Use the mxcUrlToHttp utility to convert an MXC URL to an HTTP URL.

Profile

The profile API allows you to retrieve and modify user profile details, including display names and avatar URLs. Here are the main methods:

  • queryProfile: Fetches the full profile of a user.
    const profile = await matrixApiClient.profile.v1beta1.queryProfile('@user:homeserver.url');
    console.log(profile.displayname, profile.avatar_url);
  • queryDisplayname: Fetches the display name of a user.
    const displayname = await matrixApiClient.profile.v1beta1.queryDisplayname('@user:homeserver.url');
    console.log(displayname);
  • setDisplayname: Sets the display name of a user.
    const displayname = await matrixApiClient.profile.v1beta1.setDisplayname('@user:homeserver.url', 'John Doe');
    console.log(displayname);
  • queryAvatarUrl: Fetches the avatar URL of a user.
    const avatarUrl = await matrixApiClient.profile.v1beta1.queryAvatarUrl('@user:homeserver.url');
    console.log(avatarUrl);
  • setAvatarUrl: Sets the avatar URL of a user.
    const avatarUrl = await matrixApiClient.profile.v1beta1.setAvatarUrl('@user:homeserver.url', 'mxc://matrix.org/abc123');
    console.log(avatarUrl);

| Tip: Use the mxcUrlToHttp utility to convert an MXC URL to an HTTP URL.

Room

The room API provides methods for retrieving and modifying room details and for managing membership:

  • queryId: Retrieves a room's ID using its alias.
    const roomInfo = await matrixApiClient.room.v1beta1.queryId('#roomAlias:homeserver.url');
    console.log(roomInfo.room_id, roomInfo.servers);
  • queryVisibility: Retrieves the visibility status of a room.
    const visibility = await matrixApiClient.room.v1beta1.queryVisibility('!roomId:homeserver.url');
    console.log(visibility);
  • setVisibility: Sets the visibility status of a room.
    const response = await matrixApiClient.room.v1beta1.setVisibility('!roomId:homeserver.url', 'private');
    console.log(response);
  • knock: Knocks on a room to request a join from the room admin.
    const knockResponse = await matrixApiClient.room.v1beta1.knock('!roomId:homeserver.url');
    console.log(knockResponse.room_id);
  • join: Joins a room (requires an invite).
    const joinResponse = await matrixApiClient.room.v1beta1.join('!roomId:homeserver.url');
    console.log(joinResponse.room_id);
  • listJoinedRooms: Lists all rooms the user has joined. This method checks the rooms associated with the provided access token and does not require a user ID or alias.
    const listJoinedRoomsResponse = await matrixApiClient.room.v1beta1.listJoinedRooms();
    console.log(listJoinedRoomsResponse.joined_rooms);
  • listJoinedMembers: Lists all members of a room along with their profile details (display name, avatar). The user making the request must be a member of the room.
    const listJoinedMembersResponse = await matrixApiClient.room.v1beta1.listJoinedMembers('!roomId:homeserver.url');
    console.log(listJoinedMembersResponse.joined);
  • leave: Leaves a room. The user can provide an optional reason.
    const leaveResponse = await matrixApiClient.room.v1beta1.leave('!roomId:homeserver.url', 'leaving');
    console.log(leaveResponse.room_id);
  • kick: Kicks a user from a room if the user issuing the request has the necessary power level.
    const kickResponse = await matrixApiClient.room.v1beta1.kick('!roomId:homeserver.url', '@user:homeserver.url', 'kicking');
    console.log(kickResponse.room_id);

Room Bot Client

The Room Bot client provides additional functionality for automating entity room management through bots. Use the createMatrixRoomBotClient function to create the bot client.

const matrixRoomBotClient = createMatrixRoomBotClient({
  homeServerUrl: 'https://your-homeserver-url',
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token'
});

Room

Room Bot methods include managing entity rooms and invitations:

  • sourceRoom: Sources an entity room by its IID document (DID). If the room does not exist, it will be created. This method will also invite the user to the entity room if they have not been invited before.
    const sourceRoomResponse = await matrixRoomBotClient.room.v1beta1.sourceRoom('did:ixo:entity:abc...xyz');
    console.log(sourceRoomResponse.room_id);
  • sourceRoomAndJoin: Similar to sourceRoom but also joins the entity room if the user is not already a member.
    const sourceRoomAndJoinResponse = await matrixRoomBotClient.room.v1beta1.sourceRoomAndJoin('did:ixo:entity:abc...xyz');
    console.log(sourceRoomAndJoinResponse.room_id);
  • roomInvite: Invites the user to the entity room if the room exists, regardless of whether the user has been invited to the room before.
    const roomInviteResponse = await matrixRoomBotClient.room.v1beta1.roomInvite('did:ixo:entity:abc...xyz');
    console.log(roomInviteResponse.room_id);
  • roomInviteAndJoin: Similar to roomInvite but also joins the room if the user is not already a member.
    const roomInviteAndJoinResponse = await matrixRoomBotClient.room.v1beta1.roomInviteAndJoin('did:ixo:entity:abc...xyz');
    console.log(roomInviteAndJoinResponse.room_id);

State Bot Client

The State Bot client allows managing room state and ACLs. Create the client using the createMatrixStateBotClient function:

const matrixStateBotClient = createMatrixStateBotClient({
  botUrl: 'https://your-bot-url',
  accessToken: 'your-access-token' // optional
});

ACL

The state bot ACL methods allow you to retrieve access control lists (ACLs) for rooms, which specify what users or groups can access or edit certain parts of the room. The state bot fetches the acl for a given key and optional path. If no path is provided (path = ''), the acl for the overall state object under the key is returned.

  • queryAcl: Fetches the ACL data for a room. Note that '*' means all users.
    const aclData = await matrixStateBotClient.acl.v1beta1.queryAcl(
      '!roomId:homeserver.url',
      'impactsX',
      'profile'
    );
    console.log(aclData.data);
  • setAcl: Sets the ACL data for a room. Note that '*' means all users.
    const setAclResponse = await matrixStateBotClient.acl.v1beta1.setAcl(
      '!roomId:homeserver.url',
      'impactsX',
      'profile',
      JSON.stringify({
        canAccess: ['*'],
        canEdit: [],
      })
    );
    console.log(setAclResponse.data);

Bot

The bot methods provide functionality to interact with the state bot such as inviting it to a room to manage state and ACLs.

  • invite: Invites the state bot to a specified room and adjusts its power level to ensure it has the necessary permissions to manage state events.
    const response = await matrixStateBotClient.bot.v1beta1.invite(
      '!roomId:homeserver.url',
    );
    console.log(response);

Note: This request will still succeed even if bot is already part of the room or has the necessary power levels, so it is safe to call in those cases.

State

The state methods provide functionality to query the state of a room. The state bot fetches the state for a given key and optional path. If no path is provided (path = ''), the entire state object under the key is returned.

  • queryState: Fetches the state data for a room.
    const stateData = await matrixStateBotClient.state.v1beta1.queryState(
      '!roomId:homeserver.url',
      'impactsX',
      'profile'
    );
    console.log(stateData.data);
  • setState: Sets the state data for a room.
    const setStateResponse = await matrixStateBotClient.state.v1beta1.setState(
      '!roomId:homeserver.url',
      'impactsX',
      'profile',
      JSON.stringify({
        displayName: 'John Doe',
        avatar_url: 'mxc://matrix.org/abc123',
      })
    );
    console.log(setStateResponse.data);

IMPORTANT: Always check whether a state object exists before setting and potentially overwriting it. This is especially important when setting important state values such as credentials or private information.

Utilities

The SDK includes several utility functions for handling MXC URLs and validating inputs.

MXC Utilities

The mxc utilities allow you to convert Matrix Content (MXC) URLs to standard HTTP URLs.

  • mxcUrlToHttp: Converts an MXC URL to an HTTP URL.
    const httpUrl = utils.mxc.mxcUrlToHttp(
      'https://your-homeserver-url', // homeServerUrl
      'mxc://matrix.org/abc123', // the mxc url
      300, // width
      300, // height
      'crop' // resizeMethod
    );
    console.log(httpUrl); // Outputs the HTTP URL

Validators

The validators namespace provides a set of utility functions for validating user IDs and room IDs.

  • isValidUserId: Validates whether a string is a properly formatted user ID. Note that all user IDs are prefixed with an '@'.
    const isValid = utils.validators.isValidUserId('@user:homeserver.url');
    console.log(isValid); // true or false
  • isValidRoomId: Validates whether a string is a properly formatted room ID. Note that all room IDs are prefixed with an '!'.
    const isValid = utils.validators.isValidRoomId('!roomId:homeserver.url');
    console.log(isValid); // true or false
  • isValidRoomAlias: Validates whether a string is a properly formatted room alias. Note that all room aliases are prefixed with an '#'.
    const isValid = utils.validators.isValidRoomAlias('#roomAlias:homeserver.url');
    console.log(isValid); // true or false
  • isValidMxcLink: Validates whether a string is a properly formatted mxc link. Note that all mxc links are prefixed with an 'mxc://'.
    const isValid = utils.validators.isValidMxcLink('mxc://matrix.org/abc123');
    console.log(isValid); // true or false