├── .ctiignore ├── .github ├── CODEOWNERS ├── FUNDING.yml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── main.yml │ └── release.yml ├── .gitignore ├── .husky ├── pre-commit └── pre-push ├── .prettierrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── jest.config.js ├── package.json ├── src ├── AjvContainer.ts ├── LazyValue.ts ├── NamespacedValue.ts ├── content_blocks │ ├── ArrayBlock.ts │ ├── BaseBlock.ts │ ├── BooleanBlock.ts │ ├── IntegerBlock.ts │ ├── InvalidBlockError.ts │ ├── ObjectBlock.ts │ ├── StringBlock.ts │ ├── m │ │ ├── EmoteBlock.ts │ │ ├── MarkupBlock.ts │ │ └── NoticeBlock.ts │ └── types_wire.ts ├── events │ ├── EventParser.ts │ ├── InvalidEventError.ts │ ├── RoomEvent.ts │ ├── m │ │ ├── EmoteEvent.ts │ │ ├── MessageEvent.ts │ │ └── NoticeEvent.ts │ └── types_wire.ts ├── index.ts └── types.ts ├── test ├── AjvContainer.test.ts ├── LazyValue.test.ts ├── NamespacedValue.test.ts ├── __snapshots__ │ └── AjvContainer.test.ts.snap ├── content_blocks │ ├── ArrayBlock.test.ts │ ├── BaseBlock.test.ts │ ├── BooleanBlock.test.ts │ ├── IntegerBlock.test.ts │ ├── InvalidBlockError.test.ts │ ├── ObjectBlock.test.ts │ ├── StringBlock.test.ts │ └── m │ │ ├── EmoteBlock.test.ts │ │ ├── MarkupBlock.test.ts │ │ ├── NoticeBlock.test.ts │ │ └── __snapshots__ │ │ └── MarkupBlock.test.ts.snap └── events │ ├── EventParser.test.ts │ ├── InvalidEventError.test.ts │ ├── RoomEvent.test.ts │ └── m │ ├── EmoteEvent.test.ts │ ├── MessageEvent.test.ts │ └── NoticeEvent.test.ts ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.ctiignore: -------------------------------------------------------------------------------- 1 | { 2 | "src/events/EventParser.ts": ["addInternalKnownEventParser", "addInternalUnknownEventParser", "InternalOrderCategorization"], 3 | "**/*.d.ts": "*", 4 | "test/**": "*" 5 | } 6 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @matrix-org/element-web 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: matrixdotorg 2 | liberapay: matrixdotorg 3 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Checklist 4 | 5 | * [ ] Tests written and pass 6 | * [ ] Linter and code format applied 7 | * [ ] Sign-off given on the changes (see [CONTRIBUTING.md](https://github.com/matrix-org/matrix-events-sdk/blob/main/CONTRIBUTING.md)) 8 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Main 2 | on: 3 | push: 4 | branches: [main] 5 | pull_request: 6 | branches: [main] 7 | jobs: 8 | # Global 9 | # ================================================ 10 | 11 | eslint-16: 12 | name: 'ESLint Node 18' 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v3 16 | - uses: actions/setup-node@v3 17 | with: 18 | node-version: '18' 19 | - run: yarn install 20 | - run: yarn lint 21 | 22 | # Node 16 23 | # ================================================ 24 | 25 | build-16: 26 | name: 'Build Node 16' 27 | runs-on: ubuntu-latest 28 | steps: 29 | - uses: actions/checkout@v3 30 | - uses: actions/setup-node@v3 31 | with: 32 | node-version: '16' 33 | - run: yarn install 34 | - run: yarn build 35 | 36 | tests-16: 37 | name: 'Tests Node 16' 38 | runs-on: ubuntu-latest 39 | steps: 40 | - uses: actions/checkout@v3 41 | - uses: actions/setup-node@v3 42 | with: 43 | node-version: '16' 44 | - run: yarn install 45 | - run: yarn test 46 | 47 | # Node 18 48 | # ================================================ 49 | 50 | build-14: 51 | name: 'Build Node 18' 52 | runs-on: ubuntu-latest 53 | steps: 54 | - uses: actions/checkout@v3 55 | - uses: actions/setup-node@v3 56 | with: 57 | node-version: '18' 58 | - run: yarn install 59 | - run: yarn build 60 | 61 | tests-14: 62 | name: 'Tests Node 18' 63 | runs-on: ubuntu-latest 64 | steps: 65 | - uses: actions/checkout@v3 66 | - uses: actions/setup-node@v3 67 | with: 68 | node-version: '18' 69 | - run: yarn install 70 | - run: yarn test 71 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release Automation 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | version-bump: 6 | description: The scale of the version bump required for semver compatibility 7 | required: true 8 | default: patch 9 | type: choice 10 | options: 11 | - patch 12 | - minor 13 | - major 14 | concurrency: release 15 | jobs: 16 | release: 17 | name: "Release & Publish" 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: 🧮 Checkout code 21 | uses: actions/checkout@v3 22 | with: 23 | token: ${{ secrets.ELEMENT_BOT_TOKEN }} 24 | 25 | - name: 🔧 Set up node environment 26 | uses: actions/setup-node@v3 27 | with: 28 | cache: 'yarn' 29 | 30 | - name: 🛠️ Setup 31 | run: yarn install --pure-lockfile 32 | 33 | - name: 👊 Bump version 34 | run: | 35 | yarn version --no-git-tag-version --${{ github.event.inputs.version-bump }} 36 | git config --global user.name 'ElementRobot' 37 | git config --global user.email 'releases@riot.im' 38 | git commit -am "${{ github.event.inputs.version-bump }} version bump" 39 | git push 40 | - name: 🚀 Publish to npm 41 | id: npm-publish 42 | uses: JS-DevTools/npm-publish@v1 43 | with: 44 | token: ${{ secrets.NPM_TOKEN }} 45 | access: public 46 | 47 | - name: 🧬 Create release 48 | uses: actions/create-release@v1 49 | env: 50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 51 | with: 52 | tag_name: v${{ steps.npm-publish.outputs.version }} 53 | release_name: Release ${{ steps.npm-publish.outputs.version }} 54 | body: ${{ steps.npm-publish.outputs.version }} Release 55 | draft: false 56 | prerelease: false 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Custom 2 | .idea/ 3 | lib/ 4 | .npmrc 5 | 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # TypeScript v1 declaration files 50 | typings/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Microbundle cache 62 | .rpt2_cache/ 63 | .rts2_cache_cjs/ 64 | .rts2_cache_es/ 65 | .rts2_cache_umd/ 66 | 67 | # Optional REPL history 68 | .node_repl_history 69 | 70 | # Output of 'npm pack' 71 | *.tgz 72 | 73 | # Yarn Integrity file 74 | .yarn-integrity 75 | 76 | # dotenv environment variables file 77 | .env 78 | .env.test 79 | 80 | # parcel-bundler cache (https://parceljs.org/) 81 | .cache 82 | 83 | # Next.js build output 84 | .next 85 | 86 | # Nuxt.js build / generate output 87 | .nuxt 88 | dist 89 | 90 | # Gatsby files 91 | .cache/ 92 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 93 | # https://nextjs.org/blog/next-9-1#public-directory-support 94 | # public 95 | 96 | # vuepress build output 97 | .vuepress/dist 98 | 99 | # Serverless directories 100 | .serverless/ 101 | 102 | # FuseBox cache 103 | .fusebox/ 104 | 105 | # DynamoDB Local files 106 | .dynamodb/ 107 | 108 | # TernJS port file 109 | .tern-port 110 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | yarn idx && yarn format 5 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | yarn lint && yarn test 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "trailingComma": "all", 4 | "singleQuote": false, 5 | "printWidth": 120, 6 | "tabWidth": 4, 7 | "bracketSpacing": false, 8 | "arrowParens": "avoid" 9 | } 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing code to matrix-events-sdk 2 | 3 | Everyone is welcome to contribute code to this project, provided that they are 4 | willing to license their contributions under the same license as the project 5 | itself. We follow a simple 'inbound=outbound' model for contributions: the act 6 | of submitting an 'inbound' contribution means that the contributor agrees to 7 | license the code under the same terms as the project's overall 'outbound' 8 | license - in this case, Apache Software License v2 (see [LICENSE](./LICENSE)). 9 | 10 | ## How to contribute 11 | 12 | The preferred and easiest way to contribute changes to the project is to fork 13 | it on github, and then create a pull request to ask us to pull your changes 14 | into our repo (https://help.github.com/articles/using-pull-requests/) 15 | 16 | We use the `main` branch as an unstable/development branch - users looking for 17 | a stable branch should use the release branches or a given release instead. 18 | 19 | The workflow is that contributors should fork the main branch to 20 | make a 'feature' branch for a particular contribution, and then make a pull 21 | request to merge this back into the matrix.org 'official' main branch. We 22 | use GitHub's pull request workflow to review the contribution, and either ask 23 | you to make any refinements needed or merge it and make them ourselves. The 24 | changes will then land on master when we next do a release. 25 | 26 | We use continuous integration, and all pull requests get automatically tested 27 | by it: if your change breaks the build, then the PR will show that there are 28 | failed checks, so please check back after a few minutes. 29 | 30 | ## Code style 31 | 32 | This project aims to target TypeScript with published versions having JS-compatible 33 | code. All files should be written in TypeScript. 34 | 35 | Members should not be exported as a default export in general - it causes problems 36 | with the architecture of the SDK (index file becomes less clear) and could 37 | introduce naming problems (as default exports get aliased upon import). In 38 | general, avoid using `export default`. 39 | 40 | The remaining code styles are automatically enforced by Prettier. Git hooks are 41 | used to automatically apply the format, though you can see if your changes will 42 | pass with `yarn lint`. To automatically apply code style fixes, run `yarn format`. 43 | 44 | Please ensure your changes match the cosmetic style of the existing project, 45 | and **never** mix cosmetic and functional changes in the same commit, as it 46 | makes it horribly hard to review otherwise. 47 | 48 | ## Sign off 49 | 50 | In order to have a concrete record that your contribution is intentional 51 | and you agree to license it under the same terms as the project's license, we've 52 | adopted the same lightweight approach that the Linux Kernel 53 | (https://www.kernel.org/doc/Documentation/SubmittingPatches), Docker 54 | (https://github.com/docker/docker/blob/master/CONTRIBUTING.md), and many other 55 | projects use: the DCO (Developer Certificate of Origin: 56 | http://developercertificate.org/). This is a simple declaration that you wrote 57 | the contribution or otherwise have the right to contribute it to Matrix: 58 | 59 | ``` 60 | Developer Certificate of Origin 61 | Version 1.1 62 | 63 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 64 | 660 York Street, Suite 102, 65 | San Francisco, CA 94110 USA 66 | 67 | Everyone is permitted to copy and distribute verbatim copies of this 68 | license document, but changing it is not allowed. 69 | 70 | Developer's Certificate of Origin 1.1 71 | 72 | By making a contribution to this project, I certify that: 73 | 74 | (a) The contribution was created in whole or in part by me and I 75 | have the right to submit it under the open source license 76 | indicated in the file; or 77 | 78 | (b) The contribution is based upon previous work that, to the best 79 | of my knowledge, is covered under an appropriate open source 80 | license and I have the right under that license to submit that 81 | work with modifications, whether created in whole or in part 82 | by me, under the same open source license (unless I am 83 | permitted to submit under a different license), as indicated 84 | in the file; or 85 | 86 | (c) The contribution was provided directly to me by some other 87 | person who certified (a), (b) or (c) and I have not modified 88 | it. 89 | 90 | (d) I understand and agree that this project and the contribution 91 | are public and that a record of the contribution (including all 92 | personal information I submit with it, including my sign-off) is 93 | maintained indefinitely and may be redistributed consistent with 94 | this project or the open source license(s) involved. 95 | ``` 96 | 97 | If you agree to this for your contribution, then all that's needed is to 98 | include the line in your commit or pull request comment: 99 | 100 | ``` 101 | Signed-off-by: Your Name 102 | ``` 103 | 104 | We accept contributions under a legally identifiable name, such as your name on 105 | government documentation or common-law names (names claimed by legitimate usage 106 | or repute). Unfortunately, we cannot accept anonymous contributions at this 107 | time. 108 | 109 | Git allows you to add this signoff automatically when using the `-s` flag to 110 | `git commit`, which uses the name and email set in your `user.name` and 111 | `user.email` git configs. 112 | 113 | If you forgot to sign off your commits before making your pull request and are 114 | on Git 2.17+ you can mass signoff using rebase: 115 | 116 | ``` 117 | git rebase --signoff origin/develop 118 | ``` 119 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # matrix-events-sdk 2 | 3 | JS/TS SDK for handling (extensible) events in Matrix 4 | 5 | ## 🚨🚨 Project is a work in progress 6 | 7 | The architecture and approach of this repo is still being considered and is subject to breaking 8 | changes. Use at your own risk. 9 | 10 | As a general guide, functionality which is foundational to events (such as text, images, etc) 11 | should be incorporated in this repo before the more complex types. This is to ensure that the 12 | architecture is up to the task of handling proper extensible events. 13 | 14 | ## Usage: Parsing events 15 | 16 | ```typescript 17 | const parser = new EventParser(); 18 | const parsed = parser.parse({ 19 | type: "org.matrix.msc1767.message", 20 | content: { 21 | "org.matrix.msc1767.markup": [ 22 | { "body": "this is my message text" }, 23 | ], 24 | }, 25 | // and other required fields 26 | }); 27 | 28 | if (parsed instanceof MessageEvent) { 29 | console.log(parsed.text); 30 | } 31 | ``` 32 | 33 | It is recommended to cache your `EventParser` instance for performance reasons, and for ease of use 34 | when adding custom events. 35 | 36 | Registering your own events is easy, and we recommend creating your own block objects for handling the 37 | contents of events: 38 | 39 | ```typescript 40 | // There are a number of built-in block types for simple primitives 41 | // BooleanBlock, IntegerBlock, StringBlock 42 | 43 | // For object-based blocks, the following can be used: 44 | type MyObjectBlockWireType = { 45 | my_property: string; // or whatever your block's properties are on the wire 46 | }; 47 | 48 | class MyObjectBlock extends ObjectBlock { 49 | public static readonly schema: Schema = { 50 | // This is a JSON Schema 51 | type: "object", 52 | properties: { 53 | my_property: { 54 | type: "string", 55 | nullable: false, 56 | }, 57 | }, 58 | required: ["my_property"], 59 | errorMessage: { 60 | properties: { 61 | my_property: "my_property should be a non-null string and is required", 62 | }, 63 | }, 64 | }; 65 | 66 | public static readonly validateFn = AjvContainer.ajv.compile(MyObjectBlock.schema); 67 | 68 | public static readonly type = new UnstableValue(null, "org.example.my_custom_block"); 69 | 70 | public constructor(raw: MyObjectBlockWireType) { 71 | super(MyObjectBlock.type.name, raw); 72 | if (!MyObjectBlock.validateFn(raw)) { 73 | throw new InvalidBlockError(this.name, MyObjectBlock.validateFn.errors); 74 | } 75 | } 76 | } 77 | 78 | // For array-based blocks, we define the contents (items) slightly differently: 79 | type MyArrayItemWireType = { 80 | my_property: string; // or whatever 81 | }; // your item type can also be a primitive, like integers, booleans, and strings. 82 | 83 | class MyArrayBlock extends ArrayBlock { 84 | public static readonly schema = ArrayBlock.schema; 85 | public static readonly validateFn = ArrayBlock.validateFn; 86 | 87 | public static readonly itemSchema: Schema = { 88 | // This is a JSON Schema 89 | type: "object", 90 | properties: { 91 | my_property: { 92 | type: "string", 93 | nullable: false, 94 | }, 95 | }, 96 | required: ["my_property"], 97 | errorMessage: { 98 | properties: { 99 | my_property: "my_property should be a non-null string and is required", 100 | }, 101 | }, 102 | }; 103 | public static readonly itemValidateFn = AjvContainer.ajv.compile(MyArrayBlock.itemSchema); 104 | 105 | public static readonly type = new UnstableValue(null, "org.example.my_custom_block"); 106 | 107 | public constructor(raw: MyArrayItemWireType[]) { 108 | super(MyArrayBlock.type.name, raw); 109 | this.raw = raw.filter(x => { 110 | const bool = MyArrayBlock.itemValidateFn(x); 111 | if (!bool) { 112 | // Do something with the error. It might be valid to throw, as we do here, or 113 | // use `.filter()`'s ability to exclude items from the final array. 114 | throw new InvalidBlockError(this.name, MyArrayBlock.itemValidateFn.errors); 115 | } 116 | return bool; 117 | }); 118 | } 119 | } 120 | ``` 121 | 122 | Then, we can define a custom event: 123 | 124 | ```typescript 125 | type MyWireContent = EitherAnd< 126 | { [MyObjectBlock.type.name]: MyObjectBlockWireType }, 127 | { [MyObjectBlock.type.altName]: MyObjectBlockWireType } 128 | >; 129 | 130 | class MyCustomEvent extends RoomEvent { 131 | public static readonly contentSchema: Schema = AjvContainer.eitherAnd(MyObjectBlock.type, MyObjectBlock.schema); 132 | public static readonly contentValidateFn = AjvContainer.ajv.compile(MyCustomEvent.contentSchema); 133 | 134 | public static readonly type = new UnstableValue(null, "org.example.my_custom_event"); 135 | 136 | public constructor(raw: WireEvent.RoomEvent) { 137 | super(MyCustomEvent.type.name, raw, false); // see docs 138 | if (!MyCustomEvent.contentValidateFn(this.content)) { 139 | throw new InvalidEventError(this.name, MyCustomEvent.contentValidateFn.errors); 140 | } 141 | } 142 | } 143 | ``` 144 | 145 | and finally we can register it in a parser instance: 146 | 147 | ```typescript 148 | const parser = new EventParser(); 149 | parser.addKnownType(MyCustomEvent.type, x => new MyCustomEvent(x)); 150 | ``` 151 | 152 | If you'd also like to register an "unknown event type" handler, that can be done like so: 153 | 154 | ```typescript 155 | const myParser: UnknownEventParser = x => { 156 | const possibleBlock = MyObjectBlock.type.findIn(x.content); 157 | if (!!possibleBlock) { 158 | const block = new MyObjectBlock(possibleBlock as MyObjectBlockWireType); 159 | return new MyCustomEvent({ 160 | ...x, 161 | type: MyCustomEvent.type.name, // required - override the event type 162 | content: { 163 | [MyObjectBlock.name]: block.raw, 164 | }, // technically optional, but good practice: clean up the event's content for handling. 165 | }); 166 | } 167 | return undefined; // else, we don't care about it 168 | }; 169 | parser.setUnknownParsers([myParser, ...parser.defaultUnknownEventParsers]); 170 | ``` 171 | 172 | Putting your parser at the start of the array will ensure it gets called first. Including the default parsers 173 | is also optional, though recommended. 174 | 175 | ## Usage: Making events 176 | 177 | 178 | ***TODO: This needs refactoring*** 179 | 180 | 181 | Most event objects have a `from` static function which takes common details of an event 182 | and returns an instance of that event for later serialization. 183 | 184 | ```typescript 185 | const userInput = "**hello**"; 186 | const htmlInput = "hello"; // might be after running through a markdown processor 187 | 188 | const message = MessageEvent.from(userInput, htmlInput).serialize(); 189 | 190 | // Finally, assuming your client instance is called `client`: 191 | client.sendEvent(message.type, message.content); 192 | ``` 193 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: "ts-jest", 4 | testEnvironment: "node", 5 | collectCoverage: true, 6 | collectCoverageFrom: ["./src/**"], 7 | coverageThreshold: { 8 | global: { 9 | lines: 100, 10 | branches: 100, 11 | functions: 100, 12 | statements: -1, 13 | }, 14 | }, 15 | }; 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "matrix-events-sdk", 3 | "version": "2.0.0", 4 | "description": "JS/TS SDK for interacting with Matrix events", 5 | "main": "lib/index.js", 6 | "types": "lib/index.d.ts", 7 | "repository": "git@github.com:matrix-org/matrix-events-sdk.git", 8 | "author": "The Matrix.org Foundation C.I.C.", 9 | "license": "Apache-2.0", 10 | "files": [ 11 | "lib", 12 | "README.md", 13 | "package.json", 14 | "yarn.lock", 15 | "LICENSE" 16 | ], 17 | "scripts": { 18 | "prepare": "husky install", 19 | "prepublishOnly": "yarn build", 20 | "clean": "rimraf lib", 21 | "idx": "ctix single -p tsconfig.build.json --startAt src --output src/index.ts --overwrite --noBackup --useComment && yarn format", 22 | "build": "yarn clean && yarn idx && tsc -p tsconfig.build.json", 23 | "start": "tsc -p tsconfig.build.json -w", 24 | "test": "jest", 25 | "format": "prettier --config .prettierrc \"{src,test}/**/*.ts\" --write", 26 | "lint": "tsc -p tsconfig.json --noEmit && prettier --config .prettierrc \"{src,test}/**/*.ts\" --check" 27 | }, 28 | "devDependencies": { 29 | "@types/jest": "^29.2.3", 30 | "@types/node": "^16", 31 | "ctix": "^1.7.0", 32 | "husky": "^8.0.2", 33 | "jest": "^29.3.1", 34 | "prettier": "^2.8.0", 35 | "rimraf": "^3.0.2", 36 | "ts-jest": "^29.0.3", 37 | "typescript": "^4.9.3" 38 | }, 39 | "dependencies": { 40 | "ajv": "^8.11.2", 41 | "ajv-errors": "^3.0.0" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/AjvContainer.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import Ajv, {Schema, SchemaObject} from "ajv"; 18 | import AjvErrors from "ajv-errors"; 19 | import {NamespacedValue} from "./NamespacedValue"; 20 | 21 | /** 22 | * Container for the ajv instance, the SDK's schema validator of choice. 23 | */ 24 | export class AjvContainer { 25 | public static readonly ajv = new Ajv({ 26 | allErrors: true, 27 | }); 28 | 29 | static { 30 | AjvErrors(AjvContainer.ajv); 31 | } 32 | 33 | /* istanbul ignore next */ 34 | // noinspection JSUnusedLocalSymbols 35 | private constructor() {} 36 | 37 | /** 38 | * Creates a JSON Schema representation of the EitherAnd<> TypeScript type. 39 | * @param ns The namespace to use in the EitherAnd<> type. 40 | * @param schema The schema to use as a value type for the namespace options. 41 | * @returns The EitherAnd<> type as a JSON Schema. 42 | */ 43 | public static eitherAnd( 44 | ns: NamespacedValue, 45 | schema: Schema, 46 | ): {anyOf: SchemaObject[]; errorMessage: string} { 47 | // Dev note: ajv currently doesn't have a useful type for this stuff, but ideally it'd be smart enough to 48 | // have an "anyOf" type we can return. 49 | // Also note that we don't use oneOf: we manually construct it through a Type A, or Type B, or Type A+B list. 50 | if (!ns.altName) { 51 | throw new Error("Cannot create an EitherAnd<> JSON schema type without both stable and unstable values"); 52 | } 53 | return { 54 | errorMessage: `schema does not apply to ${ns.stable} or ${ns.unstable}`, 55 | anyOf: [ 56 | { 57 | type: "object", 58 | properties: { 59 | [ns.name]: schema, 60 | }, 61 | required: [ns.name], 62 | errorMessage: { 63 | properties: { 64 | [ns.name]: `${ns.name} is required`, 65 | }, 66 | }, 67 | }, 68 | { 69 | type: "object", 70 | properties: { 71 | [ns.altName]: schema, 72 | }, 73 | required: [ns.altName], 74 | errorMessage: { 75 | properties: { 76 | [ns.altName]: `${ns.altName} is required`, 77 | }, 78 | }, 79 | }, 80 | { 81 | type: "object", 82 | properties: { 83 | [ns.name]: schema, 84 | [ns.altName]: schema, 85 | }, 86 | required: [ns.name, ns.altName], 87 | errorMessage: { 88 | properties: { 89 | [ns.name]: `${ns.name} is required`, 90 | [ns.altName]: `${ns.altName} is required`, 91 | }, 92 | }, 93 | }, 94 | ], 95 | }; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/LazyValue.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | /** 18 | * Represents a lazily-loaded value. When accessed for the first time, the 19 | * value will be cached for the lifetime of the object. The getter function 20 | * will be released when the value is cached. 21 | */ 22 | export class LazyValue { 23 | private cached: T | undefined; 24 | private getter: (() => T) | undefined; 25 | 26 | public constructor(getter: () => T) { 27 | // manually copy, so we don't expose the `undefined` type option 28 | this.getter = getter; 29 | } 30 | 31 | public get value(): T { 32 | if (this.getter !== undefined) { 33 | this.cached = this.getter(); 34 | this.getter = undefined; 35 | } 36 | // Force a cast rather than assert because it's possible for `T` to 37 | // be undefined or null (we don't stop people from making bad decisions 38 | // in this class). 39 | return this.cached as T; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/NamespacedValue.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {Optional} from "./types"; 18 | 19 | /** 20 | * Represents a simple Matrix namespaced value. This will assume that if a stable prefix 21 | * is provided that the stable prefix should be used when representing the identifier. 22 | */ 23 | export class NamespacedValue { 24 | // Stable is optional, but one of the two parameters is required, hence the weird-looking types. 25 | // Goal is to have developers explicitly say there is no stable value (if applicable). 26 | public constructor(public readonly stable: Optional, public readonly unstable?: Optional) { 27 | if (!this.unstable && !this.stable) { 28 | throw new Error("One of stable or unstable values must be supplied"); 29 | } 30 | } 31 | 32 | public get name(): U | S { 33 | if (this.stable) { 34 | return this.stable; 35 | } 36 | return this.unstable!; 37 | } 38 | 39 | public get altName(): U | S | null { 40 | if (!this.stable) { 41 | return null; 42 | } 43 | return this.unstable!; 44 | } 45 | 46 | public matches(val: string): boolean { 47 | return (!!this.name && this.name === val) || (!!this.altName && this.altName === val); 48 | } 49 | 50 | // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class 51 | // so we can instantiate `NamespacedValue` as a default type for that namespace. 52 | public findIn(obj: any): Optional { 53 | let val: Optional; 54 | if (this.name) { 55 | val = obj?.[this.name]; 56 | } 57 | if (!val && this.altName) { 58 | val = obj?.[this.altName]; 59 | } 60 | return val; 61 | } 62 | 63 | public includedIn(arr: any[]): boolean { 64 | let included = false; 65 | if (this.name) { 66 | included = arr.includes(this.name); 67 | } 68 | if (!included && this.altName) { 69 | included = arr.includes(this.altName); 70 | } 71 | return included; 72 | } 73 | } 74 | 75 | /** 76 | * Represents a namespaced value which prioritizes the unstable value over the stable 77 | * value. 78 | */ 79 | export class UnstableValue extends NamespacedValue { 80 | // Note: Constructor difference is that `unstable` is *required*. 81 | public constructor(stable: Optional, unstable: U) { 82 | super(stable, unstable); 83 | if (!this.unstable) { 84 | throw new Error("Unstable value must be supplied"); 85 | } 86 | } 87 | 88 | public get name(): U { 89 | return this.unstable!; 90 | } 91 | 92 | public get altName(): S { 93 | return this.stable!; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/content_blocks/ArrayBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "./InvalidBlockError"; 18 | import {BaseBlock} from "./BaseBlock"; 19 | import {WireContentBlock} from "./types_wire"; 20 | import {Schema} from "ajv"; 21 | import {AjvContainer} from "../AjvContainer"; 22 | 23 | /** 24 | * Represents an array-based content block. 25 | * @module Content Blocks 26 | */ 27 | export abstract class ArrayBlock extends BaseBlock { 28 | public static readonly schema: Schema = { 29 | type: "array", 30 | errorMessage: "should be an array value", 31 | }; 32 | 33 | public static readonly validateFn = AjvContainer.ajv.compile(ArrayBlock.schema); 34 | 35 | /** 36 | * Creates a new ArrayBlock. 37 | * @param name The name of the block, for error messages and debugging. 38 | * @param raw The block's value. 39 | * @protected 40 | */ 41 | protected constructor(name: string, raw: TItem[]) { 42 | super(name, raw); 43 | if (!ArrayBlock.validateFn(raw)) { 44 | throw new InvalidBlockError(name, ArrayBlock.validateFn.errors); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/content_blocks/BaseBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireContentBlock} from "./types_wire"; 18 | import {InvalidBlockError} from "./InvalidBlockError"; 19 | 20 | /** 21 | * The simplest form of a content block in its parsed form. 22 | * @module Content Blocks 23 | */ 24 | export abstract class BaseBlock { 25 | private _raw: T | undefined = undefined; 26 | 27 | public get raw(): T { 28 | return this._raw!; 29 | } 30 | 31 | protected set raw(val: T) { 32 | if (val === undefined || val === null) { 33 | throw new InvalidBlockError( 34 | this.name, 35 | "Block value must be defined. Use a null-capable parser instead of passing such a value.", 36 | ); 37 | } 38 | 39 | this._raw = val; 40 | } 41 | 42 | /** 43 | * Creates a new BaseBlock. 44 | * @param name The name of the block, for error messages and debugging. 45 | * @param raw The block's value. 46 | * @protected 47 | */ 48 | protected constructor(public readonly name: string, raw: T) { 49 | this.raw = raw; // reuse validation logic 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/content_blocks/BooleanBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "./InvalidBlockError"; 18 | import {BaseBlock} from "./BaseBlock"; 19 | import {Schema} from "ajv"; 20 | import {AjvContainer} from "../AjvContainer"; 21 | 22 | /** 23 | * Represents a boolean-based content block. 24 | * @module Content Blocks 25 | */ 26 | export abstract class BooleanBlock extends BaseBlock { 27 | public static readonly schema: Schema = { 28 | type: "boolean", 29 | errorMessage: "should be a boolean value", 30 | }; 31 | 32 | public static readonly validateFn = AjvContainer.ajv.compile(BooleanBlock.schema); 33 | 34 | /** 35 | * Creates a new IntegerBlock. 36 | * @param name The name of the block, for error messages and debugging. 37 | * @param raw The block's value. 38 | * @protected 39 | */ 40 | protected constructor(name: string, raw: boolean) { 41 | super(name, raw); 42 | if (!BooleanBlock.validateFn(raw)) { 43 | throw new InvalidBlockError(name, BooleanBlock.validateFn.errors); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/content_blocks/IntegerBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "./InvalidBlockError"; 18 | import {BaseBlock} from "./BaseBlock"; 19 | import {AjvContainer} from "../AjvContainer"; 20 | import {Schema} from "ajv"; 21 | 22 | /** 23 | * Represents an integer-based content block. 24 | * @module Content Blocks 25 | */ 26 | export abstract class IntegerBlock extends BaseBlock { 27 | public static readonly schema: Schema = { 28 | type: "integer", 29 | errorMessage: "should be an integer value", 30 | }; 31 | 32 | public static readonly validateFn = AjvContainer.ajv.compile(IntegerBlock.schema); 33 | 34 | /** 35 | * Creates a new IntegerBlock. 36 | * @param name The name of the block, for error messages and debugging. 37 | * @param raw The block's value. 38 | * @protected 39 | */ 40 | protected constructor(name: string, raw: number) { 41 | super(name, raw); 42 | if (!IntegerBlock.validateFn(raw)) { 43 | throw new InvalidBlockError(name, IntegerBlock.validateFn.errors); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/content_blocks/InvalidBlockError.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {ErrorObject} from "ajv"; 18 | 19 | /** 20 | * Thrown when a content block is unforgivably unparsable. 21 | * @module Content Blocks 22 | */ 23 | export class InvalidBlockError extends Error { 24 | public constructor(blockName: string, message: string | ErrorObject[] | null | undefined) { 25 | super( 26 | `${blockName}: ${ 27 | typeof message === "string" 28 | ? message 29 | : message?.map(m => (m.message ? m.message : JSON.stringify(m))).join(", ") ?? "Validation failed" 30 | }`, 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/content_blocks/ObjectBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "./InvalidBlockError"; 18 | import {BaseBlock} from "./BaseBlock"; 19 | import {Schema} from "ajv"; 20 | import {AjvContainer} from "../AjvContainer"; 21 | 22 | /** 23 | * Represents an object-based content block. 24 | * @module Content Blocks 25 | */ 26 | export abstract class ObjectBlock extends BaseBlock { 27 | public static readonly schema: Schema = { 28 | type: "object", 29 | errorMessage: "should be an object value", 30 | }; 31 | 32 | public static readonly validateFn = AjvContainer.ajv.compile(ObjectBlock.schema); 33 | 34 | /** 35 | * Creates a new ObjectBlock. 36 | * @param name The name of the block, for error messages and debugging. 37 | * @param raw The block's value. 38 | * @protected 39 | */ 40 | protected constructor(name: string, raw: T) { 41 | super(name, raw); 42 | if (!ObjectBlock.validateFn(raw)) { 43 | throw new InvalidBlockError(name, ObjectBlock.validateFn.errors); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/content_blocks/StringBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "./InvalidBlockError"; 18 | import {BaseBlock} from "./BaseBlock"; 19 | import {Schema} from "ajv"; 20 | import {AjvContainer} from "../AjvContainer"; 21 | 22 | /** 23 | * Represents a string-based content block. 24 | * @module Content Blocks 25 | */ 26 | export abstract class StringBlock extends BaseBlock { 27 | public static readonly schema: Schema = { 28 | type: "string", 29 | errorMessage: "should be a string value", 30 | }; 31 | 32 | public static readonly validateFn = AjvContainer.ajv.compile(StringBlock.schema); 33 | 34 | /** 35 | * Creates a new StringBlock. 36 | * @param name The name of the block, for error messages and debugging. 37 | * @param raw The block's value. 38 | * @protected 39 | */ 40 | protected constructor(name: string, raw: string) { 41 | super(name, raw); 42 | if (!StringBlock.validateFn(raw)) { 43 | throw new InvalidBlockError(name, StringBlock.validateFn.errors); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/content_blocks/m/EmoteBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {MarkupBlock, WireMarkupBlock} from "./MarkupBlock"; 18 | import {ObjectBlock} from "../ObjectBlock"; 19 | import {EitherAnd} from "../../types"; 20 | import {Schema} from "ajv"; 21 | import {AjvContainer} from "../../AjvContainer"; 22 | import {UnstableValue} from "../../NamespacedValue"; 23 | import {InvalidBlockError} from "../InvalidBlockError"; 24 | import {LazyValue} from "../../LazyValue"; 25 | 26 | /** 27 | * Types for emote blocks over the wire. 28 | * @module Matrix Content Blocks 29 | * @see EmoteBlock 30 | */ 31 | export module WireEmoteBlock { 32 | type Primary = {[MarkupBlock.type.name]: WireMarkupBlock.Representation[]}; 33 | type Secondary = {[MarkupBlock.type.altName]: WireMarkupBlock.Representation[]}; 34 | export type Value = EitherAnd; 35 | } 36 | 37 | /** 38 | * An "emote" block, or a block meant to represent that the surrounding event can 39 | * be rendered as an emote. Contains a MarkupBlock internally. 40 | * @module Matrix Content Blocks 41 | * @see MarkupBlock 42 | */ 43 | export class EmoteBlock extends ObjectBlock { 44 | public static readonly schema: Schema = AjvContainer.eitherAnd(MarkupBlock.type, MarkupBlock.schema); 45 | 46 | public static readonly validateFn = AjvContainer.ajv.compile(EmoteBlock.schema); 47 | 48 | public static readonly type = new UnstableValue("m.emote", "org.matrix.msc1767.emote"); 49 | 50 | private lazyMarkup = new LazyValue(() => new MarkupBlock(MarkupBlock.type.findIn(this.raw)!)); 51 | 52 | public constructor(raw: WireEmoteBlock.Value) { 53 | super(EmoteBlock.type.stable!, raw); 54 | if (!EmoteBlock.validateFn(raw)) { 55 | throw new InvalidBlockError(this.name, EmoteBlock.validateFn.errors); 56 | } 57 | } 58 | 59 | public get markup(): MarkupBlock { 60 | return this.lazyMarkup.value; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/content_blocks/m/MarkupBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {ArrayBlock} from "../ArrayBlock"; 18 | import {Schema} from "ajv"; 19 | import {AjvContainer} from "../../AjvContainer"; 20 | import {InvalidBlockError} from "../InvalidBlockError"; 21 | import {UnstableValue} from "../../NamespacedValue"; 22 | import {LazyValue} from "../../LazyValue"; 23 | 24 | /** 25 | * Types for markup blocks over the wire. 26 | * @module Matrix Content Blocks 27 | * @see MarkupBlock 28 | */ 29 | export module WireMarkupBlock { 30 | /** 31 | * A representation of text within a markup block. 32 | * @module Matrix Content Blocks 33 | */ 34 | export type Representation = { 35 | body: string; 36 | mimetype?: string; 37 | }; 38 | } 39 | 40 | /** 41 | * A "markup" block, or a block meant to communicate human-readable and human-rendered 42 | * text, with optional mimetype. 43 | * @module Matrix Content Blocks 44 | */ 45 | export class MarkupBlock extends ArrayBlock { 46 | public static readonly schema = ArrayBlock.schema; 47 | public static readonly validateFn = ArrayBlock.validateFn; 48 | 49 | public static readonly type = new UnstableValue("m.markup", "org.matrix.msc1767.markup"); 50 | 51 | /** 52 | * Schema definition for the markup representation (list item) specifically. 53 | * 54 | * Note: Schema for the whole markup value type is handled by the ArrayBlock class. 55 | */ 56 | public static readonly representationSchema: Schema = { 57 | type: "object", 58 | properties: { 59 | body: { 60 | type: "string", 61 | nullable: false, 62 | }, 63 | mimetype: { 64 | type: "string", 65 | nullable: false, 66 | }, 67 | }, 68 | required: ["body"], 69 | errorMessage: { 70 | properties: { 71 | body: "body should be a non-null string and is required", 72 | mimetype: "mimetype should be a non-null string, or undefined (field not required)", 73 | }, 74 | }, 75 | }; 76 | 77 | /** 78 | * Validation function for markup representations (list items) specifically. 79 | * 80 | * Note: Validation for the whole markup value type is handled by the ArrayBlock class. 81 | */ 82 | public static readonly representationValidateFn = AjvContainer.ajv.compile(MarkupBlock.representationSchema); 83 | 84 | /** 85 | * Parse errors for representations. Representations described here are *removed* from the 86 | * block's `raw` type, thus not being considered for rendering. 87 | */ 88 | public readonly representationErrors = new Map< 89 | {index: number; representation: WireMarkupBlock.Representation | unknown}, 90 | InvalidBlockError 91 | >(); 92 | 93 | private lazyText = new LazyValue( 94 | () => this.raw.find(m => m.mimetype === undefined || m.mimetype === "text/plain")?.body, 95 | ); 96 | private lazyHtml = new LazyValue(() => this.raw.find(m => m.mimetype === "text/html")?.body); 97 | 98 | /** 99 | * Creates a new MarkupBlock 100 | * 101 | * Invalid representations will be removed from the `raw` value, excluding them from rendering. 102 | * Errors can be found from representationErrors after creating the object. 103 | * @param raw The block's value. 104 | */ 105 | public constructor(raw: WireMarkupBlock.Representation[]) { 106 | super(MarkupBlock.type.stable!, raw); 107 | this.raw = raw.filter((r, i) => { 108 | const bool = MarkupBlock.representationValidateFn(r); 109 | if (!bool) { 110 | this.representationErrors.set( 111 | { 112 | index: i, 113 | representation: r, 114 | }, 115 | new InvalidBlockError(`m.markup[${i}]`, MarkupBlock.representationValidateFn.errors), 116 | ); 117 | } 118 | return bool; 119 | }); 120 | } 121 | 122 | /** 123 | * The text representation of the block, if one is present. 124 | */ 125 | public get text(): string | undefined { 126 | return this.lazyText.value; 127 | } 128 | 129 | /** 130 | * The HTML representation of the block, if one is present. 131 | */ 132 | public get html(): string | undefined { 133 | return this.lazyHtml.value; 134 | } 135 | 136 | /** 137 | * The ordered representations for this markup block. 138 | */ 139 | public get representations(): WireMarkupBlock.Representation[] { 140 | return [...this.raw]; // clone to prevent mutation 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/content_blocks/m/NoticeBlock.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {MarkupBlock, WireMarkupBlock} from "./MarkupBlock"; 18 | import {ObjectBlock} from "../ObjectBlock"; 19 | import {EitherAnd} from "../../types"; 20 | import {Schema} from "ajv"; 21 | import {AjvContainer} from "../../AjvContainer"; 22 | import {UnstableValue} from "../../NamespacedValue"; 23 | import {InvalidBlockError} from "../InvalidBlockError"; 24 | import {LazyValue} from "../../LazyValue"; 25 | 26 | /** 27 | * Types for notice blocks over the wire. 28 | * @module Matrix Content Blocks 29 | * @see NoticeBlock 30 | */ 31 | export module WireNoticeBlock { 32 | type Primary = {[MarkupBlock.type.name]: WireMarkupBlock.Representation[]}; 33 | type Secondary = {[MarkupBlock.type.altName]: WireMarkupBlock.Representation[]}; 34 | export type Value = EitherAnd; 35 | } 36 | 37 | /** 38 | * A "notice" block, or a block meant to represent that the surrounding event can 39 | * be rendered as a notice. Contains a MarkupBlock internally. 40 | * @module Matrix Content Blocks 41 | * @see MarkupBlock 42 | */ 43 | export class NoticeBlock extends ObjectBlock { 44 | public static readonly schema: Schema = AjvContainer.eitherAnd(MarkupBlock.type, MarkupBlock.schema); 45 | 46 | public static readonly validateFn = AjvContainer.ajv.compile(NoticeBlock.schema); 47 | 48 | public static readonly type = new UnstableValue("m.notice", "org.matrix.msc1767.notice"); 49 | 50 | private lazyMarkup = new LazyValue(() => new MarkupBlock(MarkupBlock.type.findIn(this.raw)!)); 51 | 52 | public constructor(raw: WireNoticeBlock.Value) { 53 | super(NoticeBlock.type.stable!, raw); 54 | if (!NoticeBlock.validateFn(raw)) { 55 | throw new InvalidBlockError(this.name, NoticeBlock.validateFn.errors); 56 | } 57 | } 58 | 59 | public get markup(): MarkupBlock { 60 | return this.lazyMarkup.value; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/content_blocks/types_wire.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | /** 18 | * The wire types for content blocks. 19 | * @module Content Blocks 20 | */ 21 | export module WireContentBlock { 22 | /** 23 | * Possible value types for a content block. 24 | * @module Content Blocks 25 | */ 26 | export type Value = string | boolean | number | object | Value[]; 27 | } 28 | -------------------------------------------------------------------------------- /src/events/EventParser.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireEvent} from "./types_wire"; 18 | import {RoomEvent} from "./RoomEvent"; 19 | import {NamespacedValue} from "../NamespacedValue"; 20 | import {InvalidEventError} from "./InvalidEventError"; 21 | import {InvalidBlockError} from "../content_blocks/InvalidBlockError"; 22 | 23 | /** 24 | * Represents an event factory for purposes of event parsing. 25 | * @module Event Parsing 26 | */ 27 | export type ParsedEventFactory = ( 28 | x: WireEvent.RoomEvent, 29 | ) => RoomEvent; 30 | 31 | /** 32 | * Represents a parser for unknown events, returning undefined if the event does 33 | * not apply. The parser should modify the `type` and `content` of the event before 34 | * returning the `RoomEvent<>` object, allowing consumers to see what the event got 35 | * interpreted as. 36 | * 37 | * Throwing InvalidBlockError and InvalidEventError are valid if the supplied event 38 | * *looks* compatible, but actually isn't. For example, an event containing a markup 39 | * block, but that markup block being invalid. 40 | * @module Event Parsing 41 | */ 42 | export type UnknownEventParser = ( 43 | x: WireEvent.RoomEvent, 44 | ) => RoomEvent | undefined; 45 | 46 | const internalKnownEvents = new Map>(); 47 | 48 | // For efficiency, we maintain two arrays instead of one with tuples. This allows 49 | // us to return the "default" parsers with ease (and without iterating the array). 50 | // The array isn't terribly large, though it has potential to be a visible performance 51 | // bottleneck over enough time. 52 | // 53 | // Note: We very carefully manage these arrays in addInternalUnknownEventParser() 54 | const internalOrderedUnknownParsers: UnknownEventParser[] = []; 55 | const internalOrderedUnknownCategories: InternalOrderCategorization[] = []; 56 | 57 | /** 58 | * Used internally by the events-sdk to determine how to group an unknown event 59 | * parser. 60 | * @internal 61 | */ 62 | export enum InternalOrderCategorization { 63 | // These are grouped by rough principles, ensuring that any event types 64 | // categorized at the same level are not conflicting (ie: an unknown event 65 | // with a file, image, and text block wouldn't get "incorrectly" deemed just 66 | // a plain file upload). 67 | // 68 | // The naming/grouping of these is very much arbitrary. The only consistent 69 | // piece is smaller numbers being considered first-checked. For example, a 70 | // parser at "level 10" would be tried before a "level 12" parser. 71 | OtherMedia = 0, // videos, audio 72 | ImageMedia = 1, 73 | RichTextOrFile = 2, // plain files, text with attributes (emotes, notices) 74 | TextOnly = 3, 75 | } 76 | 77 | /** 78 | * Add an internally-known event type to the parser. This should not be called outside 79 | * of the SDK itself. 80 | * @internal 81 | * @param namespace The namespace for the event. 82 | * @param factory The event creation factory. 83 | */ 84 | export function addInternalKnownEventParser< 85 | S extends string, 86 | U extends string, 87 | T extends object, 88 | C extends WireEvent.BlockBasedContent, 89 | >(namespace: NamespacedValue, factory: ParsedEventFactory): void { 90 | if (namespace.stable) { 91 | internalKnownEvents.set(namespace.stable, factory); 92 | } 93 | if (namespace.unstable) { 94 | internalKnownEvents.set(namespace.unstable, factory); 95 | } 96 | } 97 | 98 | /** 99 | * Add an unknown event parser for a known event type. This should not be called outside 100 | * of the SDK itself. 101 | * @param priority The priority of this parser. See InternalOrderCategorization 102 | * @param parser The parser function. 103 | * @see InternalOrderCategorization 104 | */ 105 | export function addInternalUnknownEventParser( 106 | priority: InternalOrderCategorization, 107 | parser: UnknownEventParser, 108 | ): void { 109 | // First, find the index we'll want to insert at using a binary search. 110 | // We use a binary search because it's empirically faster than more traditional 111 | // approaches for a set size of 10-100 entries. 112 | // Source: https://stackoverflow.com/a/21822316 113 | // Validation: https://gist.github.com/turt2live/1f7bdf75a0fb0923fe4bee577471841f 114 | let lowIdx = 0; 115 | let highIdx = internalOrderedUnknownCategories.length; 116 | while (lowIdx < highIdx) { 117 | const midIdx = (lowIdx + highIdx) >>> 1; // integer division by 2 118 | if (internalOrderedUnknownCategories[midIdx] < priority) { 119 | lowIdx = midIdx + 1; 120 | } else { 121 | highIdx = midIdx; 122 | } 123 | } 124 | 125 | // Splice the new elements into the arrays 126 | internalOrderedUnknownCategories.splice(lowIdx, 0, priority); 127 | internalOrderedUnknownParsers.splice(lowIdx, 0, parser); 128 | } 129 | 130 | /** 131 | * Parses known and unknown events to determine their validity. The SDK's internally 132 | * known events will always be included in the parser: there is no need to add them 133 | * explicitly. 134 | * 135 | * Consumers may wish to adjust the "unknown interpret order" to customize functionality 136 | * for when the parser encounters an event type it does not have a factory for. 137 | * @module Event Parsing 138 | */ 139 | export class EventParser { 140 | private typeMap = new Map>(internalKnownEvents); 141 | private unknownInterpretOrder: UnknownEventParser[] = [...internalOrderedUnknownParsers]; 142 | 143 | /** 144 | * All the known event types for this parser. 145 | */ 146 | public get knownEventTypes(): string[] { 147 | return Array.from(this.typeMap.keys()); 148 | } 149 | 150 | /** 151 | * The default unknown event type parse order. Custom events would normally 152 | * get prepended to this array to ensure they get checked first. 153 | */ 154 | public get defaultUnknownEventParsers(): UnknownEventParser[] { 155 | return [...internalOrderedUnknownParsers]; 156 | } 157 | 158 | /** 159 | * The unknown event type parsers currently known to this instance. 160 | */ 161 | public get unknownEventParsers(): UnknownEventParser[] { 162 | return [...this.unknownInterpretOrder]; 163 | } 164 | 165 | /** 166 | * Adds or overwrites a known type in the event parser. Does not affect the 167 | * "unknown event" parse order. 168 | * @param namespace The namespace for the event type. 169 | * @param factory The factory used to create the event object. 170 | */ 171 | public addKnownType( 172 | namespace: NamespacedValue, 173 | factory: ParsedEventFactory, 174 | ): void { 175 | if (namespace.stable) { 176 | this.typeMap.set(namespace.stable, factory); 177 | } 178 | if (namespace.unstable) { 179 | this.typeMap.set(namespace.unstable, factory); 180 | } 181 | } 182 | 183 | /** 184 | * Sets the "unknown event type" parser order, where the first element of the 185 | * provided array will be tried first. The first matching parser will be used. 186 | * 187 | * Note that this overwrites the parsers rather than appends/prepends: callers 188 | * should use the defaultUnknownEventParsers property to prepend their custom 189 | * events prior to calling this set function. 190 | * @param ordered The parsers, ordered by which parser should be tried first. 191 | * @see defaultUnknownEventParsers 192 | */ 193 | public setUnknownParsers( 194 | ordered: UnknownEventParser[], 195 | ): void { 196 | this.unknownInterpretOrder = ordered; 197 | } 198 | 199 | /** 200 | * Parses an event. If the event type is known to the parser, it will be parsed 201 | * as that type. If the event type is unknown, the "unknown event" parsers will 202 | * be used to return an appropriate type. If no parser applies after both sets 203 | * are checked, undefined is returned. 204 | * 205 | * An event returned by this function might have different attributes (event type, 206 | * content, etc) than the event supplied in the function: this is to allow callers 207 | * to check what type of event the parser is treating given type as. For example, 208 | * if an `org.example.sample` event type was given here, the function might return 209 | * an event type which matches `m.message`. 210 | * 211 | * Note that this function can throw InvalidBlockError and InvalidEventError, or 212 | * other errors, if the given event is unforgivably unable to be parsed. 213 | * @param event The event to try parsing. 214 | * @returns The parsed event, or undefined if unable. 215 | */ 216 | public parse(event: WireEvent.RoomEvent): RoomEvent | undefined { 217 | if (this.typeMap.has(event.type)) { 218 | return this.typeMap.get(event.type)!(event); 219 | } 220 | for (const parser of this.unknownInterpretOrder) { 221 | try { 222 | const ev = parser(event); 223 | if (ev !== undefined) return ev; 224 | } catch (e) { 225 | if (e instanceof InvalidEventError || e instanceof InvalidBlockError) { 226 | // consume these errors - we'll just try the next parser 227 | } else { 228 | throw e; // definitely re-throw everything else though 229 | } 230 | } 231 | } 232 | return undefined; // unknown event 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /src/events/InvalidEventError.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {ErrorObject} from "ajv"; 18 | 19 | /** 20 | * Thrown when an event is unforgivably unparsable. 21 | * @module Events 22 | */ 23 | export class InvalidEventError extends Error { 24 | public constructor(eventName: string, message: string | ErrorObject[] | null | undefined) { 25 | super( 26 | `${eventName}: ${ 27 | typeof message === "string" 28 | ? message 29 | : message?.map(m => (m.message ? m.message : JSON.stringify(m))).join(", ") ?? "Validation failed" 30 | }`, 31 | ); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/events/RoomEvent.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireEvent} from "./types_wire"; 18 | import {Schema} from "ajv"; 19 | import {AjvContainer} from "../AjvContainer"; 20 | import {InvalidEventError} from "./InvalidEventError"; 21 | 22 | /** 23 | * Minimum representation of a room (timeline or state) event in Matrix, for 24 | * consumption by a parser. 25 | * @module Events 26 | */ 27 | export abstract class RoomEvent> { 28 | public static readonly schema: Schema = { 29 | type: "object", 30 | properties: { 31 | room_id: { 32 | type: "string", 33 | minLength: 4, // sigil + colon + characters, in theory 34 | pattern: "^!.+:.+$", 35 | nullable: false, 36 | }, 37 | event_id: { 38 | type: "string", 39 | minLength: 2, // sigil + characters, in theory 40 | pattern: "^\\$.+$", // they are opaque strings 41 | nullable: false, 42 | }, 43 | type: { 44 | type: "string", 45 | nullable: false, 46 | }, 47 | state_key: { 48 | type: "string", 49 | nullable: false, 50 | }, 51 | sender: { 52 | type: "string", 53 | minLength: 4, // sigil + colon + characters, in theory 54 | pattern: "^@.+:.+$", 55 | nullable: false, 56 | }, 57 | content: { 58 | type: "object", 59 | nullable: false, 60 | additionalProperties: true, 61 | }, 62 | origin_server_ts: { 63 | type: "integer", 64 | // Ideally we'd specify our 2^56 limit here, but it's a bit too 65 | // weird for JSON Schema. 66 | nullable: false, 67 | }, 68 | unsigned: { 69 | type: "object", 70 | nullable: false, 71 | additionalProperties: true, 72 | }, 73 | }, 74 | required: ["room_id", "event_id", "type", "sender", "content", "origin_server_ts"], 75 | errorMessage: { 76 | properties: { 77 | room_id: "The room ID should be a string prefixed with `!` and contain a `:`, and is required", 78 | event_id: "The event ID should be a string prefixed with `$`, and is required", 79 | type: "The event type should be a string of zero or more characters, and is required", 80 | state_key: "The state key should be a string of zero or more characters", 81 | sender: "The sender should be a string prefixed with `@` and contain a `:`, and is required", 82 | content: "The event content should at least be a defined object, and is required", 83 | origin_server_ts: "The event timestamp should be a number, and is required", 84 | unsigned: "The event's unsigned content should be a defined object", 85 | }, 86 | }, 87 | }; 88 | 89 | public static readonly validateFn = AjvContainer.ajv.compile(RoomEvent.schema); 90 | 91 | /** 92 | * Creates a new MatrixEvent, validating the event object itself. Implementations of 93 | * this abstract class should only need to validate the content object rather than the 94 | * whole event schema. 95 | * @param name The name of the event. Used for debugging. 96 | * @param raw The raw event itself. 97 | * @param isStateEvent True (default: false) if the event type is expected to be a 98 | * state event. The event will be strictly checked to ensure compliance with this 99 | * field. 100 | * @protected 101 | */ 102 | protected constructor( 103 | public readonly name: string, 104 | public readonly raw: WireEvent.RoomEvent, 105 | isStateEvent = false, 106 | ) { 107 | if (raw === null || raw === undefined) { 108 | throw new InvalidEventError( 109 | this.name, 110 | "Event object must be defined. Use a null-capable parser instead of passing such a value.", 111 | ); 112 | } 113 | if (!RoomEvent.validateFn(raw)) { 114 | throw new InvalidEventError(this.name, RoomEvent.validateFn.errors); 115 | } 116 | if (!isStateEvent && raw.state_key !== undefined) { 117 | throw new InvalidEventError( 118 | this.name, 119 | "This event is not allowed to be a state event and must be converted accordingly.", 120 | ); 121 | } else if (isStateEvent && raw.state_key === undefined) { 122 | throw new InvalidEventError( 123 | this.name, 124 | "This event is only allowed to be a state event and must be converted accordingly.", 125 | ); 126 | } 127 | } 128 | 129 | /** 130 | * The room ID this event was sent in. 131 | */ 132 | public get roomId(): string { 133 | return this.raw.room_id; 134 | } 135 | 136 | /** 137 | * The event ID this event was sent as. 138 | */ 139 | public get eventId(): string { 140 | return this.raw.event_id; 141 | } 142 | 143 | /** 144 | * The raw, unparsed, content of this event. It is recommended to use the getters 145 | * on the event object instead to retrieve relevant parts of the event, such as 146 | * message text or image details. 147 | */ 148 | public get content(): Content { 149 | return this.raw.content; 150 | } 151 | 152 | /** 153 | * The type of this event. 154 | */ 155 | public get type(): string { 156 | return this.raw.type; 157 | } 158 | 159 | /** 160 | * The sender (user ID) of this event. 161 | */ 162 | public get sender(): string { 163 | return this.raw.sender; 164 | } 165 | 166 | /** 167 | * The state key for this event, if present. Note that an empty string is a 168 | * valid state key: check for undefined to determine presence of a state key. 169 | */ 170 | public get stateKey(): string | undefined { 171 | return this.raw.state_key; 172 | } 173 | 174 | /** 175 | * The reported timestamp this event was sent at. Note that this is supplied 176 | * by the sender, and will be zero if negative. 177 | */ 178 | public get timestamp(): number { 179 | return this.raw.origin_server_ts < 0 ? 0 : this.raw.origin_server_ts; 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/events/m/EmoteEvent.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireMessageEvent} from "./MessageEvent"; 18 | import {WireEvent} from "../types_wire"; 19 | import {UnstableValue} from "../../NamespacedValue"; 20 | import {MarkupBlock} from "../../content_blocks/m/MarkupBlock"; 21 | import {RoomEvent} from "../RoomEvent"; 22 | import {Schema} from "ajv"; 23 | import {AjvContainer} from "../../AjvContainer"; 24 | import {LazyValue} from "../../LazyValue"; 25 | import {InvalidEventError} from "../InvalidEventError"; 26 | import {addInternalKnownEventParser, addInternalUnknownEventParser, InternalOrderCategorization} from "../EventParser"; 27 | import {EmoteBlock, WireEmoteBlock} from "../../content_blocks/m/EmoteBlock"; 28 | 29 | /** 30 | * Types for emote events over the wire. 31 | * @module Matrix Events 32 | * @see EmoteEvent 33 | */ 34 | export module WireEmoteEvent { 35 | export type ContentValue = WireMessageEvent.ContentValue; 36 | } 37 | 38 | /** 39 | * An emote event, containing a MarkupBlock for content. 40 | * @module Matrix Events 41 | * @see MarkupBlock 42 | */ 43 | export class EmoteEvent extends RoomEvent { 44 | public static readonly contentSchema: Schema = AjvContainer.eitherAnd(MarkupBlock.type, MarkupBlock.schema); 45 | public static readonly contentValidateFn = AjvContainer.ajv.compile(EmoteEvent.contentSchema); 46 | public static readonly type = new UnstableValue("m.emote", "org.matrix.msc1767.emote"); 47 | 48 | private lazyMarkup = new LazyValue(() => new MarkupBlock(MarkupBlock.type.findIn(this.content)!)); 49 | 50 | static { 51 | // Register the event type as a default event type 52 | addInternalKnownEventParser( 53 | EmoteEvent.type, 54 | (x: WireEvent.RoomEvent) => new EmoteEvent(x), 55 | ); 56 | 57 | // Also register an unknown event parser for handling 58 | addInternalUnknownEventParser(InternalOrderCategorization.RichTextOrFile, x => { 59 | const possibleBlock = EmoteBlock.type.findIn(x.content); 60 | if (!!possibleBlock) { 61 | const block = new EmoteBlock(possibleBlock as WireEmoteBlock.Value); 62 | return new EmoteEvent({ 63 | ...x, 64 | type: EmoteEvent.type.name, 65 | content: block.raw, // extract the `m.markup` block out of the `m.emote` block 66 | }); 67 | } else { 68 | return undefined; // not likely to be parsable by us 69 | } 70 | }); 71 | } 72 | 73 | public constructor(raw: WireEvent.RoomEvent) { 74 | super(EmoteEvent.type.stable!, raw, false); 75 | if (!EmoteEvent.contentValidateFn(this.content)) { 76 | throw new InvalidEventError(this.name, EmoteEvent.contentValidateFn.errors); 77 | } 78 | } 79 | 80 | /** 81 | * The markup block for the event. 82 | */ 83 | public get markup(): MarkupBlock { 84 | return this.lazyMarkup.value; 85 | } 86 | 87 | /** 88 | The text representation of the event, if one is present. 89 | */ 90 | public get text(): string | undefined { 91 | return this.markup.text; 92 | } 93 | 94 | /** 95 | The HTML representation of the event, if one is present. 96 | */ 97 | public get html(): string | undefined { 98 | return this.markup.html; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/events/m/MessageEvent.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {RoomEvent} from "../RoomEvent"; 18 | import {MarkupBlock, WireMarkupBlock} from "../../content_blocks/m/MarkupBlock"; 19 | import {EitherAnd} from "../../types"; 20 | import {Schema} from "ajv"; 21 | import {AjvContainer} from "../../AjvContainer"; 22 | import {UnstableValue} from "../../NamespacedValue"; 23 | import {WireEvent} from "../types_wire"; 24 | import {InvalidEventError} from "../InvalidEventError"; 25 | import {LazyValue} from "../../LazyValue"; 26 | import {addInternalKnownEventParser, addInternalUnknownEventParser, InternalOrderCategorization} from "../EventParser"; 27 | 28 | /** 29 | * Types for message events over the wire. 30 | * @module Matrix Events 31 | * @see MessageEvent 32 | */ 33 | export module WireMessageEvent { 34 | type PrimaryContent = {[MarkupBlock.type.name]: WireMarkupBlock.Representation[]}; 35 | type SecondaryContent = {[MarkupBlock.type.altName]: WireMarkupBlock.Representation[]}; 36 | export type ContentValue = EitherAnd; 37 | } 38 | 39 | /** 40 | * A message event, containing a MarkupBlock for content. 41 | * @module Matrix Events 42 | * @see MarkupBlock 43 | */ 44 | export class MessageEvent extends RoomEvent { 45 | public static readonly contentSchema: Schema = AjvContainer.eitherAnd(MarkupBlock.type, MarkupBlock.schema); 46 | public static readonly contentValidateFn = AjvContainer.ajv.compile(MessageEvent.contentSchema); 47 | 48 | public static readonly type = new UnstableValue("m.message", "org.matrix.msc1767.message"); 49 | 50 | private lazyMarkup = new LazyValue(() => new MarkupBlock(MarkupBlock.type.findIn(this.content)!)); 51 | 52 | static { 53 | // Register the event type as a default event type 54 | addInternalKnownEventParser( 55 | MessageEvent.type, 56 | (x: WireEvent.RoomEvent) => new MessageEvent(x), 57 | ); 58 | 59 | // Also register an unknown event parser for handling 60 | addInternalUnknownEventParser(InternalOrderCategorization.TextOnly, x => { 61 | if (MarkupBlock.type.findIn(x.content)) { 62 | return new MessageEvent({ 63 | ...x, 64 | type: MessageEvent.type.name, 65 | }); 66 | } else { 67 | return undefined; // not likely to be parsable by us 68 | } 69 | }); 70 | } 71 | 72 | public constructor(raw: WireEvent.RoomEvent) { 73 | super(MessageEvent.type.stable!, raw, false); 74 | if (!MessageEvent.contentValidateFn(this.content)) { 75 | throw new InvalidEventError(this.name, MessageEvent.contentValidateFn.errors); 76 | } 77 | } 78 | 79 | /** 80 | * The markup block for the event. 81 | */ 82 | public get markup(): MarkupBlock { 83 | return this.lazyMarkup.value; 84 | } 85 | 86 | /** 87 | The text representation of the event, if one is present. 88 | */ 89 | public get text(): string | undefined { 90 | return this.markup.text; 91 | } 92 | 93 | /** 94 | The HTML representation of the event, if one is present. 95 | */ 96 | public get html(): string | undefined { 97 | return this.markup.html; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/events/m/NoticeEvent.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireMessageEvent} from "./MessageEvent"; 18 | import {WireEvent} from "../types_wire"; 19 | import {UnstableValue} from "../../NamespacedValue"; 20 | import {MarkupBlock} from "../../content_blocks/m/MarkupBlock"; 21 | import {RoomEvent} from "../RoomEvent"; 22 | import {Schema} from "ajv"; 23 | import {AjvContainer} from "../../AjvContainer"; 24 | import {LazyValue} from "../../LazyValue"; 25 | import {InvalidEventError} from "../InvalidEventError"; 26 | import {addInternalKnownEventParser, addInternalUnknownEventParser, InternalOrderCategorization} from "../EventParser"; 27 | import {NoticeBlock, WireNoticeBlock} from "../../content_blocks/m/NoticeBlock"; 28 | 29 | /** 30 | * Types for notice events over the wire. 31 | * @module Matrix Events 32 | * @see NoticeEvent 33 | */ 34 | export module WireNoticeEvent { 35 | export type ContentValue = WireMessageEvent.ContentValue; 36 | } 37 | 38 | /** 39 | * A notice event, containing a MarkupBlock for content. 40 | * @module Matrix Events 41 | * @see MarkupBlock 42 | */ 43 | export class NoticeEvent extends RoomEvent { 44 | public static readonly contentSchema: Schema = AjvContainer.eitherAnd(MarkupBlock.type, MarkupBlock.schema); 45 | public static readonly contentValidateFn = AjvContainer.ajv.compile(NoticeEvent.contentSchema); 46 | public static readonly type = new UnstableValue("m.notice", "org.matrix.msc1767.notice"); 47 | 48 | private lazyMarkup = new LazyValue(() => new MarkupBlock(MarkupBlock.type.findIn(this.content)!)); 49 | 50 | static { 51 | // Register the event type as a default event type 52 | addInternalKnownEventParser( 53 | NoticeEvent.type, 54 | (x: WireEvent.RoomEvent) => new NoticeEvent(x), 55 | ); 56 | 57 | // Also register an unknown event parser for handling 58 | addInternalUnknownEventParser(InternalOrderCategorization.RichTextOrFile, x => { 59 | const possibleBlock = NoticeBlock.type.findIn(x.content); 60 | if (!!possibleBlock) { 61 | const block = new NoticeBlock(possibleBlock as WireNoticeBlock.Value); 62 | return new NoticeEvent({ 63 | ...x, 64 | type: NoticeEvent.type.name, 65 | content: block.raw, // extract the `m.markup` block out of the `m.notice` block 66 | }); 67 | } else { 68 | return undefined; // not likely to be parsable by us 69 | } 70 | }); 71 | } 72 | 73 | public constructor(raw: WireEvent.RoomEvent) { 74 | super(NoticeEvent.type.stable!, raw, false); 75 | if (!NoticeEvent.contentValidateFn(this.content)) { 76 | throw new InvalidEventError(this.name, NoticeEvent.contentValidateFn.errors); 77 | } 78 | } 79 | 80 | /** 81 | * The markup block for the event. 82 | */ 83 | public get markup(): MarkupBlock { 84 | return this.lazyMarkup.value; 85 | } 86 | 87 | /** 88 | The text representation of the event, if one is present. 89 | */ 90 | public get text(): string | undefined { 91 | return this.markup.text; 92 | } 93 | 94 | /** 95 | The HTML representation of the event, if one is present. 96 | */ 97 | public get html(): string | undefined { 98 | return this.markup.html; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/events/types_wire.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {WireContentBlock} from "../content_blocks/types_wire"; 18 | 19 | /** 20 | * The wire types for Matrix events. 21 | * @module Events 22 | */ 23 | export module WireEvent { 24 | /** 25 | * A Matrix event. Also called a ClientEvent by the Matrix Specification. 26 | * @module Events 27 | */ 28 | export interface RoomEvent { 29 | room_id: string; 30 | event_id: string; 31 | type: string; 32 | state_key?: string; 33 | sender: string; 34 | content: Content; 35 | origin_server_ts: number; 36 | unsigned?: object; 37 | } 38 | 39 | /** 40 | * A simple `content` schema for content block-supporting events. 41 | * @module Events 42 | */ 43 | export type BlockBasedContent = { 44 | [k: string]: WireContentBlock.Value; 45 | }; 46 | 47 | /** 48 | * An event's specific `content`, preventing unexplained extensibility at the 49 | * type system level. 50 | * @module Events 51 | */ 52 | export type BlockSpecificContent = Blocks & {[k: string]: never}; 53 | } 54 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // created from ctix 2 | 3 | // created from ctix 4 | 5 | export * from "./content_blocks/m/EmoteBlock"; 6 | export * from "./content_blocks/m/MarkupBlock"; 7 | export * from "./content_blocks/m/NoticeBlock"; 8 | export * from "./events/m/EmoteEvent"; 9 | export * from "./events/m/MessageEvent"; 10 | export * from "./events/m/NoticeEvent"; 11 | export * from "./content_blocks/ArrayBlock"; 12 | export * from "./content_blocks/BaseBlock"; 13 | export * from "./content_blocks/BooleanBlock"; 14 | export * from "./content_blocks/IntegerBlock"; 15 | export * from "./content_blocks/InvalidBlockError"; 16 | export * from "./content_blocks/ObjectBlock"; 17 | export * from "./content_blocks/StringBlock"; 18 | export * from "./content_blocks/types_wire"; 19 | export {type ParsedEventFactory, type UnknownEventParser, EventParser} from "./events/EventParser"; 20 | export * from "./events/InvalidEventError"; 21 | export * from "./events/RoomEvent"; 22 | export * from "./events/types_wire"; 23 | export * from "./AjvContainer"; 24 | export * from "./LazyValue"; 25 | export * from "./NamespacedValue"; 26 | export * from "./types"; 27 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | /** 18 | * Represents an optional type: can either be T or a falsy value. 19 | */ 20 | export type Optional = T | null | undefined; 21 | 22 | /** 23 | * Represents either just T1, just T2, or T1 and T2 mixed. 24 | */ 25 | export type EitherAnd = (T1 & T2) | T1 | T2; 26 | -------------------------------------------------------------------------------- /test/AjvContainer.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {AjvContainer} from "../src/AjvContainer"; 18 | import {NamespacedValue} from "../src"; 19 | 20 | describe("AjvContainer", () => { 21 | describe("eitherAnd", () => { 22 | it("should reject a namespaced value missing an altName", () => { 23 | expect(() => { 24 | AjvContainer.eitherAnd(new NamespacedValue("stable", null), {type: "object"}); 25 | }).toThrow( 26 | new Error("Cannot create an EitherAnd<> JSON schema type without both stable and unstable values"), 27 | ); 28 | }); 29 | 30 | it("should generate an appropriate schema type", () => { 31 | const result = AjvContainer.eitherAnd(new NamespacedValue("stable", "unstable"), { 32 | type: "object", 33 | properties: {test: {type: "string"}}, 34 | }); 35 | expect(result).toMatchSnapshot(); 36 | }); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /test/LazyValue.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidEventError, LazyValue} from "../src"; 18 | 19 | // @ts-ignore - we know we're exposing private fields as public 20 | class TestableLazyValue extends LazyValue { 21 | public cached: T | undefined; 22 | public getter: (() => T) | undefined; 23 | } 24 | 25 | describe("LazyValue", () => { 26 | it("should cache the getter's value on read", () => { 27 | const val = new TestableLazyValue(() => 42); 28 | expect(val.cached).toBeUndefined(); 29 | expect(val.getter).toBeDefined(); 30 | 31 | const ret = val.value; 32 | expect(ret).toStrictEqual(42); 33 | expect(val.cached).toStrictEqual(42); 34 | expect(val.getter).toBeUndefined(); 35 | }); 36 | 37 | it.each([null, undefined])("should handle null and undefined as types: '%s'", x => { 38 | const val = new TestableLazyValue(() => x); 39 | expect(val.cached).toBeUndefined(); 40 | expect(val.getter).toBeDefined(); 41 | 42 | const ret = val.value; 43 | expect(ret).toStrictEqual(x); 44 | expect(val.cached).toStrictEqual(x); 45 | expect(val.getter).toBeUndefined(); 46 | }); 47 | 48 | it("should pass errors up normally", () => { 49 | expect(() => { 50 | new TestableLazyValue(() => { 51 | throw new InvalidEventError("TestEvent", "You should see me"); 52 | }); 53 | }).not.toThrow(); 54 | expect(() => { 55 | new TestableLazyValue(() => { 56 | throw new InvalidEventError("TestEvent", "You should see me"); 57 | }).value; 58 | }).toThrow(new InvalidEventError("TestEvent", "You should see me")); 59 | }); 60 | }); 61 | -------------------------------------------------------------------------------- /test/NamespacedValue.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {NamespacedValue, UnstableValue} from "../src"; 18 | 19 | export const STABLE_VALUE = "org.example.stable"; 20 | export const UNSTABLE_VALUE = "org.example.unstable"; 21 | 22 | describe("NamespacedValue", () => { 23 | it("should map stable and unstable", () => { 24 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 25 | expect(ns.stable).toBe(STABLE_VALUE); 26 | expect(ns.unstable).toBe(UNSTABLE_VALUE); 27 | expect(ns.name).toBe(STABLE_VALUE); 28 | expect(ns.altName).toBe(UNSTABLE_VALUE); 29 | }); 30 | 31 | it("should support optionally stable values", () => { 32 | const ns = new NamespacedValue(null, UNSTABLE_VALUE); 33 | expect(ns.stable).toBeNull(); 34 | expect(ns.unstable).toBe(UNSTABLE_VALUE); 35 | expect(ns.name).toBe(UNSTABLE_VALUE); 36 | expect(ns.altName).toBeNull(); 37 | }); 38 | 39 | it("should support optionally unstable values", () => { 40 | const ns = new NamespacedValue(STABLE_VALUE, null); 41 | expect(ns.stable).toBe(STABLE_VALUE); 42 | expect(ns.unstable).toBeNull(); 43 | expect(ns.name).toBe(STABLE_VALUE); 44 | expect(ns.altName).toBeNull(); 45 | }); 46 | 47 | it("should not support entirely optional values", () => { 48 | expect(() => new NamespacedValue(null, null)).toThrow("One of stable or unstable values must be supplied"); 49 | }); 50 | 51 | describe("matches", () => { 52 | it("should check both stable and unstable", () => { 53 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 54 | expect(ns.matches(STABLE_VALUE)).toBe(true); 55 | expect(ns.matches(UNSTABLE_VALUE)).toBe(true); 56 | expect(ns.matches("NEITHER")).toBe(false); 57 | }); 58 | 59 | it("should not try to match null to an optional value", () => { 60 | const ns = new NamespacedValue(STABLE_VALUE, null); 61 | expect(ns.matches(STABLE_VALUE)).toBe(true); 62 | expect(ns.matches(UNSTABLE_VALUE)).toBe(false); 63 | expect(ns.matches("NEITHER")).toBe(false); 64 | }); 65 | }); 66 | 67 | describe("findIn", () => { 68 | it("should locate stable values first", () => { 69 | const obj = { 70 | [UNSTABLE_VALUE]: 42, 71 | [STABLE_VALUE]: 41, 72 | NEITHER: "failed", 73 | }; 74 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 75 | expect(ns.findIn(obj)).toBe(41); 76 | }); 77 | 78 | it("should locate stable when required", () => { 79 | const obj = { 80 | // [UNSTABLE_VALUE]: 42, 81 | [STABLE_VALUE]: 41, 82 | NEITHER: "failed", 83 | }; 84 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 85 | expect(ns.findIn(obj)).toBe(41); 86 | }); 87 | 88 | it("should locate unstable when required", () => { 89 | const obj = { 90 | [UNSTABLE_VALUE]: 42, 91 | // [STABLE_VALUE]: 41, 92 | NEITHER: "failed", 93 | }; 94 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 95 | expect(ns.findIn(obj)).toBe(42); 96 | }); 97 | 98 | it("should not locate anything when not present", () => { 99 | const obj = { 100 | // [UNSTABLE_VALUE]: 42, 101 | // [STABLE_VALUE]: 41, 102 | NEITHER: "failed", 103 | }; 104 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 105 | expect(ns.findIn(obj)).toBeFalsy(); 106 | }); 107 | }); 108 | 109 | describe("includedIn", () => { 110 | it("should locate stable when required", () => { 111 | const arr = [STABLE_VALUE, /*UNSTABLE_VALUE,*/ "NEITHER"]; 112 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 113 | expect(ns.includedIn(arr)).toBe(true); 114 | }); 115 | 116 | it("should locate unstable when required", () => { 117 | const arr = [/*STABLE_VALUE,*/ UNSTABLE_VALUE, "NEITHER"]; 118 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 119 | expect(ns.includedIn(arr)).toBe(true); 120 | }); 121 | 122 | it("should not locate anything when not present", () => { 123 | const arr = [/*STABLE_VALUE, UNSTABLE_VALUE,*/ "NEITHER"]; 124 | const ns = new NamespacedValue(STABLE_VALUE, UNSTABLE_VALUE); 125 | expect(ns.includedIn(arr)).toBe(false); 126 | }); 127 | }); 128 | }); 129 | 130 | describe("UnstableValue", () => { 131 | it("should map stable and unstable", () => { 132 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 133 | expect(ns.stable).toBe(STABLE_VALUE); 134 | expect(ns.unstable).toBe(UNSTABLE_VALUE); 135 | expect(ns.name).toBe(UNSTABLE_VALUE); // note the swap from NamespacedValue 136 | expect(ns.altName).toBe(STABLE_VALUE); 137 | }); 138 | 139 | it("should support optionally stable values", () => { 140 | const ns = new UnstableValue(null, UNSTABLE_VALUE); 141 | expect(ns.stable).toBeNull(); 142 | expect(ns.unstable).toBe(UNSTABLE_VALUE); 143 | expect(ns.name).toBe(UNSTABLE_VALUE); 144 | expect(ns.altName).toBeNull(); 145 | }); 146 | 147 | it("should not support optionally unstable values", () => { 148 | // @ts-ignore 149 | expect(() => new UnstableValue(STABLE_VALUE, null)).toThrow("Unstable value must be supplied"); 150 | }); 151 | 152 | it("should not support entirely optional values", () => { 153 | // @ts-ignore 154 | expect(() => new UnstableValue(null, null)).toThrow("One of stable or unstable values must be supplied"); 155 | }); 156 | 157 | describe("matches", () => { 158 | it("should check both stable and unstable", () => { 159 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 160 | expect(ns.matches(STABLE_VALUE)).toBe(true); 161 | expect(ns.matches(UNSTABLE_VALUE)).toBe(true); 162 | expect(ns.matches("NEITHER")).toBe(false); 163 | }); 164 | 165 | it("should not try to match null to an optional value", () => { 166 | const ns = new UnstableValue(null, UNSTABLE_VALUE); 167 | expect(ns.matches(STABLE_VALUE)).toBe(false); 168 | expect(ns.matches(UNSTABLE_VALUE)).toBe(true); 169 | expect(ns.matches("NEITHER")).toBe(false); 170 | }); 171 | }); 172 | 173 | describe("findIn", () => { 174 | it("should locate unstable values first", () => { 175 | const obj = { 176 | [UNSTABLE_VALUE]: 42, 177 | [STABLE_VALUE]: 41, 178 | NEITHER: "failed", 179 | }; 180 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 181 | expect(ns.findIn(obj)).toBe(42); 182 | }); 183 | 184 | it("should locate stable when required", () => { 185 | const obj = { 186 | // [UNSTABLE_VALUE]: 42, 187 | [STABLE_VALUE]: 41, 188 | NEITHER: "failed", 189 | }; 190 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 191 | expect(ns.findIn(obj)).toBe(41); 192 | }); 193 | 194 | it("should locate unstable when required", () => { 195 | const obj = { 196 | [UNSTABLE_VALUE]: 42, 197 | // [STABLE_VALUE]: 41, 198 | NEITHER: "failed", 199 | }; 200 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 201 | expect(ns.findIn(obj)).toBe(42); 202 | }); 203 | 204 | it("should not locate anything when not present", () => { 205 | const obj = { 206 | // [UNSTABLE_VALUE]: 42, 207 | // [STABLE_VALUE]: 41, 208 | NEITHER: "failed", 209 | }; 210 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 211 | expect(ns.findIn(obj)).toBeFalsy(); 212 | }); 213 | 214 | it.each([null, undefined])("shouldn't explode when given a %s object", obj => { 215 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 216 | expect(ns.findIn(obj)).toBeFalsy(); 217 | }); 218 | }); 219 | 220 | describe("includedIn", () => { 221 | it("should locate stable when required", () => { 222 | const arr = [STABLE_VALUE, /*UNSTABLE_VALUE,*/ "NEITHER"]; 223 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 224 | expect(ns.includedIn(arr)).toBe(true); 225 | }); 226 | 227 | it("should locate unstable when required", () => { 228 | const arr = [/*STABLE_VALUE,*/ UNSTABLE_VALUE, "NEITHER"]; 229 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 230 | expect(ns.includedIn(arr)).toBe(true); 231 | }); 232 | 233 | it("should not locate anything when not present", () => { 234 | const arr = [/*STABLE_VALUE, UNSTABLE_VALUE,*/ "NEITHER"]; 235 | const ns = new UnstableValue(STABLE_VALUE, UNSTABLE_VALUE); 236 | expect(ns.includedIn(arr)).toBe(false); 237 | }); 238 | }); 239 | }); 240 | -------------------------------------------------------------------------------- /test/__snapshots__/AjvContainer.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`AjvContainer eitherAnd should generate an appropriate schema type 1`] = ` 4 | { 5 | "anyOf": [ 6 | { 7 | "errorMessage": { 8 | "properties": { 9 | "stable": "stable is required", 10 | }, 11 | }, 12 | "properties": { 13 | "stable": { 14 | "properties": { 15 | "test": { 16 | "type": "string", 17 | }, 18 | }, 19 | "type": "object", 20 | }, 21 | }, 22 | "required": [ 23 | "stable", 24 | ], 25 | "type": "object", 26 | }, 27 | { 28 | "errorMessage": { 29 | "properties": { 30 | "unstable": "unstable is required", 31 | }, 32 | }, 33 | "properties": { 34 | "unstable": { 35 | "properties": { 36 | "test": { 37 | "type": "string", 38 | }, 39 | }, 40 | "type": "object", 41 | }, 42 | }, 43 | "required": [ 44 | "unstable", 45 | ], 46 | "type": "object", 47 | }, 48 | { 49 | "errorMessage": { 50 | "properties": { 51 | "stable": "stable is required", 52 | "unstable": "unstable is required", 53 | }, 54 | }, 55 | "properties": { 56 | "stable": { 57 | "properties": { 58 | "test": { 59 | "type": "string", 60 | }, 61 | }, 62 | "type": "object", 63 | }, 64 | "unstable": { 65 | "properties": { 66 | "test": { 67 | "type": "string", 68 | }, 69 | }, 70 | "type": "object", 71 | }, 72 | }, 73 | "required": [ 74 | "stable", 75 | "unstable", 76 | ], 77 | "type": "object", 78 | }, 79 | ], 80 | "errorMessage": "schema does not apply to stable or unstable", 81 | } 82 | `; 83 | -------------------------------------------------------------------------------- /test/content_blocks/ArrayBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {ArrayBlock} from "../../src"; 18 | import {testSharedContentBlockInputs} from "./BaseBlock.test"; 19 | 20 | class TestArrayBlock extends ArrayBlock { 21 | public constructor(raw: any) { 22 | super("TestBlock", raw as any[]); // lie to TS 23 | } 24 | } 25 | 26 | describe("ArrayBlock", () => { 27 | testSharedContentBlockInputs("TestBlock", [1, 2], x => new TestArrayBlock(x)); 28 | 29 | it.each([["values"], []])("should accept arrays: '%s'", (...val) => { 30 | const block = new TestArrayBlock(val); 31 | expect(block.raw).toStrictEqual(val); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /test/content_blocks/BaseBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {BaseBlock, InvalidBlockError} from "../../src"; 18 | 19 | class TestBaseBlock extends BaseBlock { 20 | public constructor(raw: any) { 21 | super("TestBlock", raw as number); // lie to TS 22 | } 23 | } 24 | 25 | describe("BaseBlock", () => { 26 | testSharedContentBlockInputs("TestBlock", undefined, x => new TestBaseBlock(x)); 27 | 28 | it.each(["string", "", true, false, 42, 42.1, {hello: "world"}, [1, 2, 3], {}, []])( 29 | "should accept wire values: '%s'", 30 | val => { 31 | const block = new TestBaseBlock(val); 32 | expect(block.raw).toStrictEqual(val); 33 | }, 34 | ); 35 | }); 36 | 37 | type SafeValuesConditional = string | number | boolean | object | SafeValuesConditional[] | undefined; 38 | 39 | export function testSharedContentBlockInputs( 40 | blockName: string, 41 | safeValue: SafeValuesConditional, 42 | factory: (x: any) => BaseBlock, 43 | ) { 44 | describe("internal", () => { 45 | it("should have valid inputs", () => { 46 | expect(blockName).toBeDefined(); 47 | expect(typeof blockName).toStrictEqual("string"); 48 | expect(blockName.length).toBeGreaterThan(0); 49 | 50 | if (safeValue !== undefined) { 51 | expect(safeValue).not.toBeNull(); 52 | } 53 | 54 | expect(factory).toBeDefined(); 55 | expect(typeof factory).toStrictEqual("function"); 56 | }); 57 | 58 | it("should have a passing factory", () => { 59 | const ev = factory(safeValue ?? 42); 60 | expect(ev).toBeDefined(); 61 | // noinspection SuspiciousTypeOfGuard 62 | expect(ev instanceof BaseBlock).toStrictEqual(true); 63 | }); 64 | }); 65 | 66 | it("should retain the block name", () => { 67 | const block = factory(safeValue ?? 42); 68 | expect(block.name).toStrictEqual(blockName); 69 | }); 70 | 71 | it.each([null, undefined])("should reject null and undefined: %s", val => { 72 | expect(() => factory(val)).toThrow( 73 | new InvalidBlockError( 74 | blockName, 75 | "Block value must be defined. Use a null-capable parser instead of passing such a value.", 76 | ), 77 | ); 78 | }); 79 | 80 | if (safeValue !== undefined) { 81 | const toTest = ["string", "", true, false, 42, 42.1, {hello: "world"}, [1, 2, 3], {}, []].filter(x => 82 | Array.isArray(safeValue) ? !Array.isArray(x) : typeof x !== typeof safeValue, 83 | ); 84 | it.each(toTest)("should reject invalid base types: '%s'", val => { 85 | expect(() => factory(val as any)).toThrowError(InvalidBlockError); 86 | }); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /test/content_blocks/BooleanBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {BooleanBlock} from "../../src"; 18 | import {testSharedContentBlockInputs} from "./BaseBlock.test"; 19 | 20 | class TestBooleanBlock extends BooleanBlock { 21 | public constructor(raw: any) { 22 | super("TestBlock", raw as boolean); // lie to TS 23 | } 24 | } 25 | 26 | describe("BooleanBlock", () => { 27 | testSharedContentBlockInputs("TestBlock", true, x => new TestBooleanBlock(x)); 28 | 29 | it.each([true, false])("should accept booleans: '%s'", val => { 30 | const block = new TestBooleanBlock(val); 31 | expect(block.raw).toStrictEqual(val); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /test/content_blocks/IntegerBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {IntegerBlock, InvalidBlockError} from "../../src"; 18 | import {testSharedContentBlockInputs} from "./BaseBlock.test"; 19 | 20 | class TestIntegerBlock extends IntegerBlock { 21 | public constructor(raw: any) { 22 | super("TestBlock", raw as number); // lie to TS 23 | } 24 | } 25 | 26 | describe("IntegerBlock", () => { 27 | testSharedContentBlockInputs("TestBlock", -1, x => new TestIntegerBlock(x)); 28 | 29 | it("should accept integers", () => { 30 | const block = new TestIntegerBlock(42); 31 | expect(block.raw).toStrictEqual(42); 32 | }); 33 | 34 | it("should decline floats", () => { 35 | expect(() => new TestIntegerBlock(42.1)).toThrow( 36 | new InvalidBlockError("TestBlock", "should be an integer value"), 37 | ); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /test/content_blocks/InvalidBlockError.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError} from "../../src"; 18 | 19 | describe("InvalidBlockError", () => { 20 | it("should use the block name in the error", () => { 21 | const err = new InvalidBlockError("TestBlock", "my message"); 22 | expect(err.message).toEqual("TestBlock: my message"); 23 | }); 24 | 25 | it("should use error objects if given", () => { 26 | const err = new InvalidBlockError("TestBlock", [ 27 | { 28 | message: "test message", 29 | keyword: "test", 30 | params: [], 31 | instancePath: "#/unused", 32 | schemaPath: "#/unused", 33 | }, 34 | { 35 | // message: "test message", // this one has no message 36 | keyword: "test", 37 | params: [], 38 | instancePath: "#/unused", 39 | schemaPath: "#/unused", 40 | }, 41 | ]); 42 | expect(err.message).toEqual( 43 | 'TestBlock: test message, {"keyword":"test","params":[],"instancePath":"#/unused","schemaPath":"#/unused"}', 44 | ); 45 | }); 46 | 47 | it.each([null, undefined])("should use a default message when none is provided: '%s'", val => { 48 | const err = new InvalidBlockError("TestBlock", val); 49 | expect(err.message).toEqual("TestBlock: Validation failed"); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /test/content_blocks/ObjectBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {ObjectBlock} from "../../src"; 18 | import {testSharedContentBlockInputs} from "./BaseBlock.test"; 19 | 20 | class TestObjectBlock extends ObjectBlock { 21 | public constructor(raw: any) { 22 | super("TestBlock", raw); // lie to TS 23 | } 24 | } 25 | 26 | describe("ObjectBlock", () => { 27 | testSharedContentBlockInputs("TestBlock", {obj: true}, x => new TestObjectBlock(x)); 28 | 29 | it.each([{hello: "world"}, {}])("should accept objects: '%s'", val => { 30 | const block = new TestObjectBlock(val); 31 | expect(block.raw).toStrictEqual(val); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /test/content_blocks/StringBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {StringBlock} from "../../src"; 18 | import {testSharedContentBlockInputs} from "./BaseBlock.test"; 19 | 20 | class TestStringBlock extends StringBlock { 21 | public constructor(raw: any) { 22 | super("TestBlock", raw as string); // lie to TS 23 | } 24 | } 25 | 26 | describe("StringBlock", () => { 27 | testSharedContentBlockInputs("TestBlock", "nostring", x => new TestStringBlock(x)); 28 | 29 | it("should accept strings", () => { 30 | const block = new TestStringBlock("test"); 31 | expect(block.raw).toStrictEqual("test"); 32 | }); 33 | 34 | it("should accept empty strings", () => { 35 | const block = new TestStringBlock(""); 36 | expect(block.raw).toStrictEqual(""); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /test/content_blocks/m/EmoteBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {EmoteBlock, InvalidBlockError} from "../../../src"; 18 | import {testSharedContentBlockInputs} from "../BaseBlock.test"; 19 | 20 | describe("EmoteBlock", () => { 21 | testSharedContentBlockInputs("m.emote", {"m.markup": [{body: "test"}]}, x => new EmoteBlock(x)); 22 | 23 | it("should locate a stable markup block", () => { 24 | const block = new EmoteBlock({"m.markup": [{body: "test"}]}); 25 | expect(block.markup).toBeDefined(); 26 | expect(block.markup.text).toStrictEqual("test"); 27 | }); 28 | 29 | it("should locate an unstable markup block", () => { 30 | const block = new EmoteBlock({"org.matrix.msc1767.markup": [{body: "test"}]}); 31 | expect(block.markup).toBeDefined(); 32 | expect(block.markup.text).toStrictEqual("test"); 33 | }); 34 | 35 | it("should prefer the unstable markup block if both are provided", () => { 36 | // Dev note: this test will need updating when extensible events becomes stable 37 | const block = new EmoteBlock({ 38 | "m.markup": [{body: "stable text"}], 39 | "org.matrix.msc1767.markup": [{body: "unstable text"}], 40 | }); 41 | expect(block.markup).toBeDefined(); 42 | expect(block.markup.text).toStrictEqual("unstable text"); 43 | }); 44 | 45 | it("should error if a markup block is not present", () => { 46 | expect(() => new EmoteBlock({no_block: true} as any)).toThrow( 47 | new InvalidBlockError("m.emote", "schema does not apply to m.markup or org.matrix.msc1767.markup"), 48 | ); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /test/content_blocks/m/MarkupBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {MarkupBlock} from "../../../src"; 18 | import {testSharedContentBlockInputs} from "../BaseBlock.test"; 19 | 20 | describe("MarkupBlock", () => { 21 | testSharedContentBlockInputs("m.markup", [{body: "test"}], x => new MarkupBlock(x)); 22 | 23 | it("should be able to identify the text and HTML representations", () => { 24 | const block = new MarkupBlock([ 25 | {body: "neither", mimetype: "text/fail"}, 26 | {body: "text here", mimetype: "text/plain"}, 27 | {body: "html here", mimetype: "text/html"}, 28 | ]); 29 | // noinspection DuplicatedCode 30 | expect(block.text).toStrictEqual("text here"); 31 | expect(block.html).toStrictEqual("html here"); 32 | expect(block.representationErrors).toBeDefined(); 33 | expect(block.representationErrors.size).toStrictEqual(0); 34 | expect(block.representations).toBeDefined(); 35 | expect(block.representations.length).toStrictEqual(3); 36 | expect(block.representations).toStrictEqual(block.raw); 37 | }); 38 | 39 | it("should detect plain text as representations without mimetypes", () => { 40 | const block = new MarkupBlock([ 41 | {body: "fail", mimetype: "text/fail"}, 42 | {body: "text here"}, 43 | {body: "html here", mimetype: "text/html"}, 44 | ]); 45 | // noinspection DuplicatedCode 46 | expect(block.text).toStrictEqual("text here"); 47 | expect(block.html).toStrictEqual("html here"); 48 | expect(block.representationErrors).toBeDefined(); 49 | expect(block.representationErrors.size).toStrictEqual(0); 50 | expect(block.representations).toBeDefined(); 51 | expect(block.representations.length).toStrictEqual(3); 52 | expect(block.representations).toStrictEqual(block.raw); 53 | }); 54 | 55 | it("should be able to handle missing text", () => { 56 | const block = new MarkupBlock([ 57 | {body: "fail", mimetype: "text/fail"}, 58 | {body: "html here", mimetype: "text/html"}, 59 | ]); 60 | expect(block.text).toBeUndefined(); 61 | expect(block.html).toStrictEqual("html here"); 62 | expect(block.representationErrors).toBeDefined(); 63 | expect(block.representationErrors.size).toStrictEqual(0); 64 | expect(block.representations).toBeDefined(); 65 | expect(block.representations.length).toStrictEqual(2); 66 | expect(block.representations).toStrictEqual(block.raw); 67 | }); 68 | 69 | it("should be able to handle missing HTML", () => { 70 | const block = new MarkupBlock([ 71 | {body: "fail", mimetype: "text/fail"}, 72 | {body: "text here", mimetype: "text/plain"}, 73 | ]); 74 | expect(block.text).toStrictEqual("text here"); 75 | expect(block.html).toBeUndefined(); 76 | expect(block.representationErrors).toBeDefined(); 77 | expect(block.representationErrors.size).toStrictEqual(0); 78 | expect(block.representations).toBeDefined(); 79 | expect(block.representations.length).toStrictEqual(2); 80 | expect(block.representations).toStrictEqual(block.raw); 81 | }); 82 | 83 | it("should be able to handle neither text or HTML", () => { 84 | const block = new MarkupBlock([{body: "nothing of use", mimetype: "text/fail"}]); 85 | expect(block.text).toBeUndefined(); 86 | expect(block.html).toBeUndefined(); 87 | expect(block.representationErrors).toBeDefined(); 88 | expect(block.representationErrors.size).toStrictEqual(0); 89 | expect(block.representations).toBeDefined(); 90 | expect(block.representations.length).toStrictEqual(1); 91 | expect(block.representations).toStrictEqual(block.raw); 92 | }); 93 | 94 | it("should use the first text representation", () => { 95 | let block = new MarkupBlock([{body: "text here"}, {body: "not this text", mimetype: "text/plain"}]); 96 | // noinspection DuplicatedCode 97 | expect(block.text).toStrictEqual("text here"); 98 | expect(block.representationErrors).toBeDefined(); 99 | expect(block.representationErrors.size).toStrictEqual(0); 100 | expect(block.representations).toBeDefined(); 101 | expect(block.representations.length).toStrictEqual(2); 102 | expect(block.representations).toStrictEqual(block.raw); 103 | 104 | // The same test, but inverting the undefined mimetype for safety 105 | block = new MarkupBlock([{body: "text here", mimetype: "text/plain"}, {body: "not this text"}]); 106 | // noinspection DuplicatedCode 107 | expect(block.text).toStrictEqual("text here"); 108 | expect(block.representationErrors).toBeDefined(); 109 | expect(block.representationErrors.size).toStrictEqual(0); 110 | expect(block.representations).toBeDefined(); 111 | expect(block.representations.length).toStrictEqual(2); 112 | expect(block.representations).toStrictEqual(block.raw); 113 | }); 114 | 115 | it("should handle having no representations provided", () => { 116 | const block = new MarkupBlock([]); 117 | expect(block.text).toBeUndefined(); 118 | expect(block.html).toBeUndefined(); 119 | expect(block.representationErrors).toBeDefined(); 120 | expect(block.representationErrors.size).toStrictEqual(0); 121 | expect(block.representations).toBeDefined(); 122 | expect(block.representations.length).toStrictEqual(0); 123 | expect(block.representations).toStrictEqual(block.raw); 124 | }); 125 | 126 | it("should validate each representation has a defined body", () => { 127 | const block = new MarkupBlock([{mimetype: "text/plain"} as any]); 128 | // noinspection DuplicatedCode 129 | expect(block.text).toBeUndefined(); 130 | expect(block.html).toBeUndefined(); 131 | expect(block.representationErrors).toBeDefined(); 132 | expect(block.representationErrors.size).toStrictEqual(1); 133 | expect(Array.from(block.representationErrors.entries())[0]).toMatchSnapshot(); 134 | expect(block.representations).toBeDefined(); 135 | expect(block.representations.length).toStrictEqual(0); 136 | expect(block.representations).toStrictEqual(block.raw); 137 | }); 138 | 139 | it("should validate each representation has a valid body", () => { 140 | const block = new MarkupBlock([{body: true as any, mimetype: "text/plain"}]); 141 | // noinspection DuplicatedCode 142 | expect(block.text).toBeUndefined(); 143 | expect(block.html).toBeUndefined(); 144 | expect(block.representationErrors).toBeDefined(); 145 | expect(block.representationErrors.size).toStrictEqual(1); 146 | expect(Array.from(block.representationErrors.entries())[0]).toMatchSnapshot(); 147 | expect(block.representations).toBeDefined(); 148 | expect(block.representations.length).toStrictEqual(0); 149 | expect(block.representations).toStrictEqual(block.raw); 150 | }); 151 | 152 | it("should validate each representation has a valid mimetype", () => { 153 | const block = new MarkupBlock([{body: "text here", mimetype: true as any}]); 154 | // noinspection DuplicatedCode 155 | expect(block.text).toBeUndefined(); 156 | expect(block.html).toBeUndefined(); 157 | expect(block.representationErrors).toBeDefined(); 158 | expect(block.representationErrors.size).toStrictEqual(1); 159 | expect(Array.from(block.representationErrors.entries())[0]).toMatchSnapshot(); 160 | expect(block.representations).toBeDefined(); 161 | expect(block.representations.length).toStrictEqual(0); 162 | expect(block.representations).toStrictEqual(block.raw); 163 | }); 164 | 165 | it("should validate each representation is an object", () => { 166 | const block = new MarkupBlock([true as any]); 167 | // noinspection DuplicatedCode 168 | expect(block.text).toBeUndefined(); 169 | expect(block.html).toBeUndefined(); 170 | expect(block.representationErrors).toBeDefined(); 171 | expect(block.representationErrors.size).toStrictEqual(1); 172 | expect(Array.from(block.representationErrors.entries())[0]).toMatchSnapshot(); 173 | expect(block.representations).toBeDefined(); 174 | expect(block.representations.length).toStrictEqual(0); 175 | expect(block.representations).toStrictEqual(block.raw); 176 | }); 177 | 178 | it("should remove representations mid-array if they are invalid", () => { 179 | const block = new MarkupBlock([ 180 | {body: "valid text"}, 181 | {body: "more valid text", mimetype: "text/html"}, 182 | {body: "text here", mimetype: true as any}, 183 | {body: "even more text", mimetype: "text/plain"}, 184 | ]); 185 | expect(block.text).toStrictEqual("valid text"); 186 | expect(block.html).toStrictEqual("more valid text"); 187 | expect(block.representationErrors).toBeDefined(); 188 | expect(block.representationErrors.size).toStrictEqual(1); 189 | expect(Array.from(block.representationErrors.entries())[0]).toMatchSnapshot(); 190 | expect(block.representations).toBeDefined(); 191 | expect(block.representations.length).toStrictEqual(3); 192 | expect(block.representations).toStrictEqual(block.raw); 193 | }); 194 | }); 195 | -------------------------------------------------------------------------------- /test/content_blocks/m/NoticeBlock.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidBlockError, NoticeBlock} from "../../../src"; 18 | import {testSharedContentBlockInputs} from "../BaseBlock.test"; 19 | 20 | describe("NoticeBlock", () => { 21 | testSharedContentBlockInputs("m.notice", {"m.markup": [{body: "test"}]}, x => new NoticeBlock(x)); 22 | 23 | it("should locate a stable markup block", () => { 24 | const block = new NoticeBlock({"m.markup": [{body: "test"}]}); 25 | expect(block.markup).toBeDefined(); 26 | expect(block.markup.text).toStrictEqual("test"); 27 | }); 28 | 29 | it("should locate an unstable markup block", () => { 30 | const block = new NoticeBlock({"org.matrix.msc1767.markup": [{body: "test"}]}); 31 | expect(block.markup).toBeDefined(); 32 | expect(block.markup.text).toStrictEqual("test"); 33 | }); 34 | 35 | it("should prefer the unstable markup block if both are provided", () => { 36 | // Dev note: this test will need updating when extensible events becomes stable 37 | const block = new NoticeBlock({ 38 | "m.markup": [{body: "stable text"}], 39 | "org.matrix.msc1767.markup": [{body: "unstable text"}], 40 | }); 41 | expect(block.markup).toBeDefined(); 42 | expect(block.markup.text).toStrictEqual("unstable text"); 43 | }); 44 | 45 | it("should error if a markup block is not present", () => { 46 | expect(() => new NoticeBlock({no_block: true} as any)).toThrow( 47 | new InvalidBlockError("m.notice", "schema does not apply to m.markup or org.matrix.msc1767.markup"), 48 | ); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /test/content_blocks/m/__snapshots__/MarkupBlock.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`MarkupBlock should remove representations mid-array if they are invalid 1`] = ` 4 | [ 5 | { 6 | "index": 2, 7 | "representation": { 8 | "body": "text here", 9 | "mimetype": true, 10 | }, 11 | }, 12 | [Error: m.markup[2]: mimetype should be a non-null string, or undefined (field not required)], 13 | ] 14 | `; 15 | 16 | exports[`MarkupBlock should validate each representation has a defined body 1`] = ` 17 | [ 18 | { 19 | "index": 0, 20 | "representation": { 21 | "mimetype": "text/plain", 22 | }, 23 | }, 24 | [Error: m.markup[0]: must have required property 'body'], 25 | ] 26 | `; 27 | 28 | exports[`MarkupBlock should validate each representation has a valid body 1`] = ` 29 | [ 30 | { 31 | "index": 0, 32 | "representation": { 33 | "body": true, 34 | "mimetype": "text/plain", 35 | }, 36 | }, 37 | [Error: m.markup[0]: body should be a non-null string and is required], 38 | ] 39 | `; 40 | 41 | exports[`MarkupBlock should validate each representation has a valid mimetype 1`] = ` 42 | [ 43 | { 44 | "index": 0, 45 | "representation": { 46 | "body": "text here", 47 | "mimetype": true, 48 | }, 49 | }, 50 | [Error: m.markup[0]: mimetype should be a non-null string, or undefined (field not required)], 51 | ] 52 | `; 53 | 54 | exports[`MarkupBlock should validate each representation is an object 1`] = ` 55 | [ 56 | { 57 | "index": 0, 58 | "representation": true, 59 | }, 60 | [Error: m.markup[0]: must be object], 61 | ] 62 | `; 63 | -------------------------------------------------------------------------------- /test/events/EventParser.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import { 18 | EitherAnd, 19 | EmoteBlock, 20 | EmoteEvent, 21 | EventParser, 22 | InvalidBlockError, 23 | InvalidEventError, 24 | MessageEvent, 25 | NamespacedValue, 26 | NoticeBlock, 27 | NoticeEvent, 28 | ParsedEventFactory, 29 | RoomEvent, 30 | UnstableValue, 31 | WireEmoteBlock, 32 | WireEvent, 33 | WireMessageEvent, 34 | WireNoticeBlock, 35 | } from "../../src"; 36 | 37 | type TestCustomEventContent = { 38 | "org.example.custom": { 39 | hello: string; 40 | is_test: boolean; 41 | }; 42 | }; 43 | class TestCustomEvent extends RoomEvent { 44 | public static readonly type = new UnstableValue(null, "org.example.custom"); 45 | 46 | public constructor(raw: WireEvent.RoomEvent) { 47 | super(TestCustomEvent.type.name, raw); 48 | // DANGER: We do NOT validate content schema like we're supposed to! 49 | } 50 | } 51 | 52 | describe("EventParser", () => { 53 | it("should have the built-in types defined as known event types", () => { 54 | const expected = [MessageEvent.type, EmoteEvent.type, NoticeEvent.type] 55 | .map(ns => [ns.stable, ns.unstable]) 56 | .reduce((p, c) => [...p, ...c], []) 57 | .filter(x => !!x) 58 | .sort(); 59 | const parser = new EventParser(); 60 | expect(parser.knownEventTypes.sort()).toStrictEqual(expected); 61 | }); 62 | 63 | it("should have some unknown event parsers for built-in types", () => { 64 | const parser = new EventParser(); 65 | expect(parser.defaultUnknownEventParsers.length).toBeGreaterThan(0); 66 | 67 | // Unfortunately we can't realistically check to see if the actual parsers 68 | // have the correct values, but it shows that we registered *something* if 69 | // there's at least one available. 70 | }); 71 | 72 | describe("known event types", () => { 73 | it("should parse a known message event as a message", () => { 74 | const ev: WireEvent.RoomEvent = { 75 | room_id: "!room:example.org", 76 | event_id: "$test", 77 | type: "m.message", 78 | state_key: undefined, 79 | sender: "@user:example.org", 80 | origin_server_ts: 1671145380506, 81 | content: { 82 | "m.markup": [{body: "test"}], 83 | }, 84 | }; 85 | const parser = new EventParser(); 86 | const parsed = parser.parse(ev); 87 | expect(parsed).toBeDefined(); 88 | expect(parsed!.type).toStrictEqual("m.message"); 89 | // noinspection SuspiciousTypeOfGuard 90 | expect(parsed instanceof MessageEvent).toStrictEqual(true); 91 | expect((parsed as unknown as MessageEvent).text).toStrictEqual("test"); 92 | }); 93 | 94 | it("should parse a known emote event as an emote", () => { 95 | const ev: WireEvent.RoomEvent = { 96 | room_id: "!room:example.org", 97 | event_id: "$test", 98 | type: "m.emote", 99 | state_key: undefined, 100 | sender: "@user:example.org", 101 | origin_server_ts: 1671145380506, 102 | content: { 103 | "m.markup": [{body: "test"}], 104 | }, 105 | }; 106 | const parser = new EventParser(); 107 | const parsed = parser.parse(ev); 108 | expect(parsed).toBeDefined(); 109 | expect(parsed!.type).toStrictEqual("m.emote"); 110 | // noinspection SuspiciousTypeOfGuard 111 | expect(parsed instanceof EmoteEvent).toStrictEqual(true); 112 | expect((parsed as unknown as EmoteEvent).text).toStrictEqual("test"); 113 | }); 114 | 115 | it("should parse a known notice event as a notice", () => { 116 | const ev: WireEvent.RoomEvent = { 117 | room_id: "!room:example.org", 118 | event_id: "$test", 119 | type: "m.notice", 120 | state_key: undefined, 121 | sender: "@user:example.org", 122 | origin_server_ts: 1671145380506, 123 | content: { 124 | "m.markup": [{body: "test"}], 125 | }, 126 | }; 127 | const parser = new EventParser(); 128 | const parsed = parser.parse(ev); 129 | expect(parsed).toBeDefined(); 130 | expect(parsed!.type).toStrictEqual("m.notice"); 131 | // noinspection SuspiciousTypeOfGuard 132 | expect(parsed instanceof NoticeEvent).toStrictEqual(true); 133 | expect((parsed as unknown as NoticeEvent).text).toStrictEqual("test"); 134 | }); 135 | 136 | describe("custom", () => { 137 | it("should parse a custom event as that custom event", () => { 138 | const factory: ParsedEventFactory = x => 139 | new TestCustomEvent(x); 140 | const parser1 = new EventParser(); 141 | const parser2 = new EventParser(); 142 | parser1.addKnownType(TestCustomEvent.type, factory); 143 | 144 | // check to make sure the known type didn't leak across instances 145 | expect(parser1.knownEventTypes.includes(TestCustomEvent.type.name)).toStrictEqual(true); 146 | expect(parser2.knownEventTypes.includes(TestCustomEvent.type.name)).toStrictEqual(false); 147 | 148 | // Try parsing the custom event 149 | const ev: WireEvent.RoomEvent = { 150 | room_id: "!room:example.org", 151 | event_id: "$test", 152 | type: "org.example.custom", 153 | state_key: undefined, 154 | sender: "@user:example.org", 155 | origin_server_ts: 1671145380506, 156 | content: { 157 | "org.example.custom": { 158 | hello: "world", 159 | is_test: true, 160 | }, 161 | }, 162 | }; 163 | const parsed = parser1.parse(ev); 164 | expect(parsed).toBeDefined(); 165 | expect(parsed!.type).toStrictEqual("org.example.custom"); 166 | // noinspection SuspiciousTypeOfGuard 167 | expect(parsed instanceof TestCustomEvent).toStrictEqual(true); 168 | 169 | // And to be doubly sure, the other parser fails to find anything useful: 170 | const unknownParsed = parser2.parse(ev); 171 | expect(unknownParsed).toBeUndefined(); 172 | }); 173 | }); 174 | }); 175 | 176 | describe("unknown event types", () => { 177 | it("should parse an unknown, message-like, event as a message", () => { 178 | const ev: WireEvent.RoomEvent = { 179 | room_id: "!room:example.org", 180 | event_id: "$test", 181 | type: "org.example.custom", 182 | state_key: undefined, 183 | sender: "@user:example.org", 184 | origin_server_ts: 1671145380506, 185 | content: { 186 | "m.markup": [{body: "test"}], 187 | }, 188 | }; 189 | // noinspection DuplicatedCode 190 | const parser = new EventParser(); 191 | const parsed = parser.parse(ev); 192 | expect(parsed).toBeDefined(); 193 | expect(parsed!.type).toStrictEqual(MessageEvent.type.name); 194 | // noinspection SuspiciousTypeOfGuard 195 | expect(parsed instanceof MessageEvent).toStrictEqual(true); 196 | expect((parsed as unknown as MessageEvent).text).toStrictEqual("test"); 197 | }); 198 | 199 | it("should parse an unknown, emote-like, event as an emote", () => { 200 | const ev: WireEvent.RoomEvent< 201 | EitherAnd< 202 | {[EmoteBlock.type.name]: WireEmoteBlock.Value}, 203 | {[EmoteBlock.type.altName]: WireEmoteBlock.Value} 204 | > 205 | > = { 206 | room_id: "!room:example.org", 207 | event_id: "$test", 208 | type: "org.example.custom", 209 | state_key: undefined, 210 | sender: "@user:example.org", 211 | origin_server_ts: 1671145380506, 212 | content: { 213 | "m.emote": { 214 | "m.markup": [{body: "test"}], 215 | }, 216 | }, 217 | }; 218 | // noinspection DuplicatedCode 219 | const parser = new EventParser(); 220 | const parsed = parser.parse(ev); 221 | expect(parsed).toBeDefined(); 222 | expect(parsed!.type).toStrictEqual(EmoteEvent.type.name); 223 | // noinspection SuspiciousTypeOfGuard 224 | expect(parsed instanceof EmoteEvent).toStrictEqual(true); 225 | expect((parsed as unknown as EmoteEvent).text).toStrictEqual("test"); 226 | }); 227 | 228 | it("should parse an unknown, notice-like, event as a notice", () => { 229 | const ev: WireEvent.RoomEvent< 230 | EitherAnd< 231 | {[NoticeBlock.type.name]: WireNoticeBlock.Value}, 232 | {[NoticeBlock.type.altName]: WireNoticeBlock.Value} 233 | > 234 | > = { 235 | room_id: "!room:example.org", 236 | event_id: "$test", 237 | type: "org.example.custom", 238 | state_key: undefined, 239 | sender: "@user:example.org", 240 | origin_server_ts: 1671145380506, 241 | content: { 242 | "m.notice": { 243 | "m.markup": [{body: "test"}], 244 | }, 245 | }, 246 | }; 247 | // noinspection DuplicatedCode 248 | const parser = new EventParser(); 249 | const parsed = parser.parse(ev); 250 | expect(parsed).toBeDefined(); 251 | expect(parsed!.type).toStrictEqual(NoticeEvent.type.name); 252 | // noinspection SuspiciousTypeOfGuard 253 | expect(parsed instanceof NoticeEvent).toStrictEqual(true); 254 | expect((parsed as unknown as NoticeEvent).text).toStrictEqual("test"); 255 | }); 256 | 257 | describe("custom", () => { 258 | it("should respect the custom unknown event parser order", () => { 259 | const customParser = (x: WireEvent.RoomEvent) => 260 | new TestCustomEvent({ 261 | ...x, 262 | type: TestCustomEvent.type.name, 263 | content: { 264 | "org.example.custom": (x.content as any)["org.example.custom"] ?? { 265 | hello: "wrong", 266 | is_test: true, 267 | }, 268 | }, 269 | }); 270 | const ev: WireEvent.RoomEvent = { 271 | room_id: "!room:example.org", 272 | event_id: "$test", 273 | type: "org.example.custom", 274 | state_key: undefined, 275 | sender: "@user:example.org", 276 | origin_server_ts: 1671145380506, 277 | content: { 278 | "m.notice": { 279 | "m.markup": [{body: "parsed as notice"}], 280 | }, 281 | "m.markup": [{body: "parsed as plain"}], 282 | "org.example.custom": { 283 | hello: "parsed as custom", 284 | is_test: true, 285 | }, 286 | }, 287 | }; 288 | const parser = new EventParser(); 289 | 290 | // Should parse the event as a notice first 291 | let parsed = parser.parse(ev); 292 | expect(parsed).toBeDefined(); 293 | expect(parsed!.type).toStrictEqual(NoticeEvent.type.name); 294 | // noinspection SuspiciousTypeOfGuard 295 | expect(parsed instanceof NoticeEvent).toStrictEqual(true); 296 | expect((parsed as unknown as NoticeEvent).text).toStrictEqual("parsed as notice"); 297 | 298 | // If we reverse the order, it should parse as text 299 | parser.setUnknownParsers(parser.defaultUnknownEventParsers.reverse()); 300 | parsed = parser.parse(ev); 301 | expect(parsed).toBeDefined(); 302 | expect(parsed!.type).toStrictEqual(MessageEvent.type.name); 303 | // noinspection SuspiciousTypeOfGuard 304 | expect(parsed instanceof MessageEvent).toStrictEqual(true); 305 | expect((parsed as unknown as MessageEvent).text).toStrictEqual("parsed as plain"); 306 | 307 | // Similarly, if we add our custom parser to the front then it should parse as that 308 | parser.setUnknownParsers([customParser, ...parser.defaultUnknownEventParsers]); 309 | parsed = parser.parse(ev); 310 | expect(parsed!.type).toStrictEqual(TestCustomEvent.type.name); 311 | // noinspection SuspiciousTypeOfGuard 312 | expect(parsed instanceof TestCustomEvent).toStrictEqual(true); 313 | expect((parsed as unknown as TestCustomEvent).content["org.example.custom"].hello).toStrictEqual( 314 | "parsed as custom", 315 | ); 316 | 317 | // also similarly, it should parse it as a notice if we put our custom parser last 318 | parser.setUnknownParsers([...parser.defaultUnknownEventParsers, customParser]); 319 | parsed = parser.parse(ev); 320 | expect(parsed).toBeDefined(); 321 | expect(parsed!.type).toStrictEqual(NoticeEvent.type.name); 322 | // noinspection SuspiciousTypeOfGuard 323 | expect(parsed instanceof NoticeEvent).toStrictEqual(true); 324 | expect((parsed as unknown as NoticeEvent).text).toStrictEqual("parsed as notice"); 325 | 326 | // final check: did any of this affect other instances of parsers? (it shouldn't) 327 | const parser2 = new EventParser(); 328 | expect(parser2.unknownEventParsers).toStrictEqual(parser2.defaultUnknownEventParsers); 329 | }); 330 | }); 331 | }); 332 | 333 | it("should throw if the known event parser throws", () => { 334 | const ev: WireEvent.RoomEvent = { 335 | room_id: "!room:example.org", 336 | event_id: "$test", 337 | type: TestCustomEvent.type.name, 338 | state_key: undefined, 339 | sender: "@user:example.org", 340 | origin_server_ts: 1671145380506, 341 | content: {}, // shouldn't matter what the content is: it should explode before we get there 342 | }; 343 | 344 | const parser = new EventParser(); 345 | 346 | parser.addKnownType(TestCustomEvent.type, () => { 347 | throw new InvalidEventError("TestEvent", "Test Case Throw"); 348 | }); 349 | expect(() => parser.parse(ev)).toThrow(new InvalidEventError("TestEvent", "Test Case Throw")); 350 | 351 | parser.addKnownType(TestCustomEvent.type, () => { 352 | throw new InvalidBlockError("TestEvent", "Test Case Throw"); 353 | }); 354 | expect(() => parser.parse(ev)).toThrow(new InvalidBlockError("TestEvent", "Test Case Throw")); 355 | 356 | parser.addKnownType(TestCustomEvent.type, () => { 357 | throw new Error("Test Case Throw"); 358 | }); 359 | expect(() => parser.parse(ev)).toThrow(new Error("Test Case Throw")); 360 | }); 361 | 362 | it("should throw when the unknown event parser throws unexpectedly", () => { 363 | const ev: WireEvent.RoomEvent = { 364 | room_id: "!room:example.org", 365 | event_id: "$test", 366 | type: TestCustomEvent.type.name, 367 | state_key: undefined, 368 | sender: "@user:example.org", 369 | origin_server_ts: 1671145380506, 370 | content: {}, // shouldn't matter what the content is: it should explode before we get there 371 | }; 372 | 373 | const parser = new EventParser(); 374 | 375 | parser.setUnknownParsers([ 376 | () => { 377 | throw new InvalidEventError("TestEvent", "Test Case Throw"); 378 | }, 379 | ]); 380 | expect(parser.parse(ev)).toBeUndefined(); // no throw 381 | 382 | parser.setUnknownParsers([ 383 | () => { 384 | throw new InvalidBlockError("TestEvent", "Test Case Throw"); 385 | }, 386 | ]); 387 | expect(parser.parse(ev)).toBeUndefined(); // no throw 388 | 389 | parser.setUnknownParsers([ 390 | () => { 391 | throw new Error("Test Case Throw"); 392 | }, 393 | ]); 394 | expect(() => parser.parse(ev)).toThrow(new Error("Test Case Throw")); 395 | }); 396 | 397 | it("should not parse events that don't match any criteria", () => { 398 | const ev: WireEvent.RoomEvent = { 399 | room_id: "!room:example.org", 400 | event_id: "$test", 401 | type: "org.example.custom", 402 | state_key: undefined, 403 | sender: "@user:example.org", 404 | origin_server_ts: 1671145380506, 405 | content: {}, 406 | }; 407 | const parser = new EventParser(); 408 | expect(parser.parse(ev)).toBeUndefined(); 409 | }); 410 | 411 | it("should not return a mutable copy of the default unknown parsers", () => { 412 | const parser = new EventParser(); 413 | const firstParser = parser.defaultUnknownEventParsers[0]; 414 | parser.defaultUnknownEventParsers.reverse(); 415 | expect(parser.defaultUnknownEventParsers[0]).toStrictEqual(firstParser); 416 | }); 417 | 418 | it("should not return a mutable copy of the known unknown parsers", () => { 419 | const parser = new EventParser(); 420 | const firstParser = parser.unknownEventParsers[0]; 421 | parser.unknownEventParsers.reverse(); 422 | expect(parser.unknownEventParsers[0]).toStrictEqual(firstParser); 423 | }); 424 | 425 | it.each([ 426 | ["stable", null], 427 | [null, "unstable"], 428 | ["stable", "unstable"], 429 | ])("should register stable and unstable values as known: s='%s', u='%s'", (stable, unstable) => { 430 | const ns = new NamespacedValue(stable, unstable); 431 | const parser = new EventParser(); 432 | parser.addKnownType(ns, () => { 433 | throw new Error("unused"); 434 | }); 435 | 436 | if (stable !== null) { 437 | expect(parser.knownEventTypes).toContain(stable); 438 | } 439 | if (unstable !== null) { 440 | expect(parser.knownEventTypes).toContain(unstable); 441 | } 442 | }); 443 | }); 444 | -------------------------------------------------------------------------------- /test/events/InvalidEventError.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidEventError} from "../../src"; 18 | 19 | describe("InvalidEventError", () => { 20 | it("should use the block name in the error", () => { 21 | const err = new InvalidEventError("org.example.test", "my message"); 22 | expect(err.message).toEqual("org.example.test: my message"); 23 | }); 24 | 25 | it("should use error objects if given", () => { 26 | const err = new InvalidEventError("org.example.test", [ 27 | { 28 | message: "test message", 29 | keyword: "test", 30 | params: [], 31 | instancePath: "#/unused", 32 | schemaPath: "#/unused", 33 | }, 34 | { 35 | // message: "test message", // this one has no message 36 | keyword: "test", 37 | params: [], 38 | instancePath: "#/unused", 39 | schemaPath: "#/unused", 40 | }, 41 | ]); 42 | expect(err.message).toEqual( 43 | 'org.example.test: test message, {"keyword":"test","params":[],"instancePath":"#/unused","schemaPath":"#/unused"}', 44 | ); 45 | }); 46 | 47 | it.each([null, undefined])("should use a default message when none is provided: '%s'", val => { 48 | const err = new InvalidEventError("org.example.test", val); 49 | expect(err.message).toEqual("org.example.test: Validation failed"); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /test/events/RoomEvent.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidEventError, RoomEvent, WireEvent} from "../../src"; 18 | 19 | class TestEvent extends RoomEvent { 20 | public constructor(raw: any, isState: boolean) { 21 | super("TestEvent", raw, isState); // lie to TS 22 | } 23 | } 24 | 25 | describe("RoomEvent", () => { 26 | testSharedRoomEventInputs("TestEvent", undefined, x => new TestEvent(x, false), {hello: "world"}); 27 | testSharedRoomEventInputs("TestEvent", "non-empty", x => new TestEvent(x, true), {hello: "world"}); 28 | testSharedRoomEventInputs("TestEvent", "", x => new TestEvent(x, true), {hello: "world"}); 29 | }); 30 | 31 | /** 32 | * Runs all the validation tests which can be shared across all event type classes. 33 | * @param eventName The event name, for error matching. 34 | * @param safeStateKey Undefined to denote the event cannot be a state event, a 35 | * string otherwise. 36 | * @param factory The factory to create a RoomEvent. 37 | * @param safeContentInput The content to supply on an event during a non-throwing 38 | * test. This should be the minimum to construct the event, not ideal conditions. 39 | */ 40 | export function testSharedRoomEventInputs( 41 | eventName: string, 42 | safeStateKey: undefined | string, 43 | factory: (raw: WireEvent.RoomEvent) => RoomEvent, 44 | safeContentInput: W, 45 | ) { 46 | testStateEventCharacteristics(eventName, safeStateKey, factory, safeContentInput); 47 | 48 | describe("internal", () => { 49 | it("should have valid inputs", () => { 50 | expect(eventName).toBeDefined(); 51 | expect(typeof eventName).toStrictEqual("string"); 52 | expect(eventName.length).toBeGreaterThan(0); 53 | 54 | expect(factory).toBeDefined(); 55 | expect(typeof factory).toStrictEqual("function"); 56 | 57 | expect(safeContentInput).toBeDefined(); 58 | expect(typeof safeContentInput).toStrictEqual("object"); 59 | }); 60 | 61 | it("should have a passing factory", () => { 62 | const ev = factory({ 63 | room_id: "!test:example.org", 64 | event_id: "$event", 65 | type: "org.example.test_event", 66 | sender: "@user:example.org", 67 | content: safeContentInput, 68 | origin_server_ts: 1670894499800, 69 | state_key: safeStateKey, 70 | }); 71 | expect(ev).toBeDefined(); 72 | // noinspection SuspiciousTypeOfGuard 73 | expect(ev instanceof RoomEvent).toStrictEqual(true); 74 | }); 75 | }); 76 | 77 | it.each([null, undefined])("should throw if given null or undefined: '%s'", val => { 78 | expect(() => factory(val as any)).toThrow( 79 | new InvalidEventError( 80 | eventName, 81 | "Event object must be defined. Use a null-capable parser instead of passing such a value.", 82 | ), 83 | ); 84 | }); 85 | 86 | it("should retain the event name", () => { 87 | const raw: WireEvent.RoomEvent = { 88 | room_id: "!test:example.org", 89 | event_id: "$event", 90 | type: "org.example.test_event", 91 | sender: "@user:example.org", 92 | content: safeContentInput, 93 | origin_server_ts: 1670894499800, 94 | state_key: safeStateKey, 95 | }; 96 | const ev = factory(raw); 97 | expect(ev.name).toStrictEqual(eventName); 98 | }); 99 | 100 | it.each([ 101 | "", 102 | "!wrong", 103 | ":wrong!example", 104 | "!:example", 105 | "!:", 106 | "!wrong:", 107 | "$wrong", 108 | "$wrong:example", 109 | "#wrong", 110 | "#wrong:example", 111 | "@wrong", 112 | "@wrong:example", 113 | true, 114 | null, 115 | 42, 116 | {hello: "world"}, 117 | [1, 2, 3], 118 | ])("should reject invalid room IDs: '%s'", val => { 119 | expect(() => 120 | factory({ 121 | room_id: val as any, 122 | event_id: "$event", 123 | type: "org.example.test_event", 124 | sender: "@user:example.org", 125 | content: safeContentInput, 126 | origin_server_ts: 1670894499800, 127 | state_key: safeStateKey, 128 | }), 129 | ).toThrow( 130 | new InvalidEventError( 131 | eventName, 132 | "The room ID should be a string prefixed with `!` and contain a `:`, and is required", 133 | ), 134 | ); 135 | }); 136 | 137 | it.each([ 138 | "", 139 | "wrong$", 140 | "!wrong", 141 | "!wrong:example", 142 | "#wrong", 143 | "#wrong:example", 144 | "@wrong", 145 | "@wrong:example", 146 | true, 147 | null, 148 | 42, 149 | {hello: "world"}, 150 | [1, 2, 3], 151 | ])("should reject invalid event IDs: '%s'", val => { 152 | expect(() => 153 | factory({ 154 | room_id: "!room:example.org", 155 | event_id: val as any, 156 | type: "org.example.test_event", 157 | sender: "@user:example.org", 158 | content: safeContentInput, 159 | origin_server_ts: 1670894499800, 160 | state_key: safeStateKey, 161 | }), 162 | ).toThrow( 163 | new InvalidEventError(eventName, "The event ID should be a string prefixed with `$`, and is required"), 164 | ); 165 | }); 166 | 167 | it.each([true, null, 42, {hello: "world"}, [1, 2, 3]])("should reject invalid event types: '%s'", val => { 168 | expect(() => 169 | factory({ 170 | room_id: "!room:example.org", 171 | event_id: "$event", 172 | type: val as any, 173 | sender: "@user:example.org", 174 | content: safeContentInput, 175 | origin_server_ts: 1670894499800, 176 | state_key: safeStateKey, 177 | }), 178 | ).toThrow( 179 | new InvalidEventError( 180 | eventName, 181 | "The event type should be a string of zero or more characters, and is required", 182 | ), 183 | ); 184 | }); 185 | 186 | it.each([true, null, 42, {hello: "world"}, [1, 2, 3]])("should reject invalid state keys: '%s'", val => { 187 | expect(() => 188 | factory({ 189 | room_id: "!room:example.org", 190 | event_id: "$event", 191 | type: "org.example.test_event", 192 | state_key: val as any, 193 | sender: "@user:example.org", 194 | content: safeContentInput, 195 | origin_server_ts: 1670894499800, 196 | }), 197 | ).toThrow(new InvalidEventError(eventName, "The state key should be a string of zero or more characters")); 198 | }); 199 | 200 | it.each([ 201 | "", 202 | "@wrong", 203 | ":wrong@example", 204 | "@:example", 205 | "@:", 206 | "@wrong:", 207 | "$wrong", 208 | "$wrong:example", 209 | "#wrong", 210 | "#wrong:example", 211 | "!wrong", 212 | "!wrong:example", 213 | true, 214 | null, 215 | 42, 216 | {hello: "world"}, 217 | [1, 2, 3], 218 | ])("should reject invalid senders (user IDs): '%s'", val => { 219 | expect(() => 220 | factory({ 221 | room_id: "!room:example.org", 222 | event_id: "$event", 223 | type: "org.example.test_event", 224 | sender: val as any, 225 | content: safeContentInput, 226 | origin_server_ts: 1670894499800, 227 | state_key: safeStateKey, 228 | }), 229 | ).toThrow( 230 | new InvalidEventError( 231 | eventName, 232 | "The sender should be a string prefixed with `@` and contain a `:`, and is required", 233 | ), 234 | ); 235 | }); 236 | 237 | it.each([true, null, "test", 42.3, {hello: "world"}, [1, 2, 3]])("should reject invalid timestamps: '%s'", val => { 238 | expect(() => 239 | factory({ 240 | room_id: "!room:example.org", 241 | event_id: "$event", 242 | type: "org.example.test_event", 243 | sender: "@user:example.org", 244 | content: safeContentInput, 245 | origin_server_ts: val as any, 246 | state_key: safeStateKey, 247 | }), 248 | ).toThrow(new InvalidEventError(eventName, "The event timestamp should be a number, and is required")); 249 | }); 250 | 251 | it.each([true, null, "test", 42, [1, 2, 3]])("should reject invalid unsigned content: '%s'", val => { 252 | expect(() => 253 | factory({ 254 | room_id: "!room:example.org", 255 | event_id: "$event", 256 | type: "org.example.test_event", 257 | sender: "@user:example.org", 258 | content: safeContentInput, 259 | origin_server_ts: 1670894499800, 260 | unsigned: val as any, 261 | state_key: safeStateKey, 262 | }), 263 | ).toThrow(new InvalidEventError(eventName, "The event's unsigned content should be a defined object")); 264 | }); 265 | 266 | it.each([true, null, "test", 42, [1, 2, 3]])("should reject invalid regular content: '%s'", val => { 267 | expect(() => 268 | factory({ 269 | room_id: "!room:example.org", 270 | event_id: "$event", 271 | type: "org.example.test_event", 272 | sender: "@user:example.org", 273 | content: val as any, 274 | origin_server_ts: 1670894499800, 275 | state_key: safeStateKey, 276 | }), 277 | ).toThrow( 278 | new InvalidEventError(eventName, "The event content should at least be a defined object, and is required"), 279 | ); 280 | }); 281 | 282 | it.each([-1670894499800, -1, 0])("should return a zero timestamp for negative timestamps: '%s'", val => { 283 | const raw: WireEvent.RoomEvent = { 284 | room_id: "!test:example.org", 285 | event_id: "$event", 286 | type: "org.example.test_event", 287 | sender: "@user:example.org", 288 | content: safeContentInput, 289 | origin_server_ts: val, 290 | state_key: safeStateKey, 291 | }; 292 | const ev = factory(raw); 293 | expect(ev).toBeDefined(); 294 | expect(ev.timestamp).toStrictEqual(0); 295 | }); 296 | 297 | it("should support events with more information than requested", () => { 298 | const raw: WireEvent.RoomEvent = { 299 | room_id: "!test:example.org", 300 | event_id: "$event", 301 | type: "org.example.test_event", 302 | sender: "@user:example.org", 303 | content: { 304 | ...safeContentInput, 305 | "org.matrix.sdk.events.test_value": 42, 306 | }, 307 | origin_server_ts: 1670894499800, 308 | state_key: safeStateKey, 309 | }; 310 | const ev = factory(raw); 311 | expect(ev).toBeDefined(); 312 | expect(ev.raw).toStrictEqual(raw); 313 | }); 314 | } 315 | 316 | function testStateEventCharacteristics( 317 | eventName: string, 318 | safeStateKey: undefined | string, 319 | factory: (raw: WireEvent.RoomEvent) => RoomEvent, 320 | safeContentInput: W, 321 | ) { 322 | describe("internal", () => { 323 | it("should have valid inputs", () => { 324 | expect(eventName).toBeDefined(); 325 | expect(typeof eventName).toStrictEqual("string"); 326 | expect(eventName.length).toBeGreaterThan(0); 327 | 328 | expect(factory).toBeDefined(); 329 | expect(typeof factory).toStrictEqual("function"); 330 | }); 331 | 332 | // Note: unlike other repeatable tests, we don't validate that the factory actually works 333 | // because we expect it to end up throwing for the values we give it. 334 | }); 335 | 336 | it.each(safeStateKey !== undefined ? [safeStateKey] : [undefined])( 337 | "should handle valid event structures with state key of '%s'", 338 | skey => { 339 | const raw: WireEvent.RoomEvent = { 340 | room_id: "!test:example.org", 341 | event_id: "$event", 342 | type: "org.example.test_event", 343 | state_key: skey, 344 | sender: "@user:example.org", 345 | content: safeContentInput, 346 | origin_server_ts: 1670894499800, 347 | }; 348 | const ev = factory(raw); 349 | expect(ev).toBeDefined(); 350 | expect(ev.raw).toStrictEqual(raw); 351 | expect(ev.roomId).toStrictEqual(raw.room_id); 352 | expect(ev.eventId).toStrictEqual(raw.event_id); 353 | expect(ev.type).toStrictEqual(raw.type); 354 | expect(ev.stateKey).toStrictEqual(raw.state_key); 355 | expect(ev.sender).toStrictEqual(raw.sender); 356 | expect(ev.timestamp).toStrictEqual(raw.origin_server_ts); 357 | expect(ev.content).toStrictEqual(raw.content); 358 | }, 359 | ); 360 | 361 | if (safeStateKey !== undefined) { 362 | it("should reject events without a state key", () => { 363 | const ev: WireEvent.RoomEvent = { 364 | room_id: "!test:example.org", 365 | event_id: "$event", 366 | type: "org.example.not_used", 367 | sender: "@user:example.org", 368 | content: {}, 369 | origin_server_ts: 1670894499800, 370 | }; 371 | expect(() => factory(ev)).toThrow( 372 | new InvalidEventError( 373 | eventName, 374 | "This event is only allowed to be a state event and must be converted accordingly.", 375 | ), 376 | ); 377 | }); 378 | } else { 379 | it.each(["", "not_empty"])("should reject state events with state key: '%s'", val => { 380 | const ev: WireEvent.RoomEvent = { 381 | room_id: "!test:example.org", 382 | event_id: "$event", 383 | type: "org.example.not_used", 384 | state_key: val, 385 | sender: "@user:example.org", 386 | content: {}, 387 | origin_server_ts: 1670894499800, 388 | }; 389 | expect(() => factory(ev)).toThrow( 390 | new InvalidEventError( 391 | eventName, 392 | "This event is not allowed to be a state event and must be converted accordingly.", 393 | ), 394 | ); 395 | }); 396 | } 397 | } 398 | -------------------------------------------------------------------------------- /test/events/m/EmoteEvent.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {EmoteEvent, InvalidEventError, WireEvent} from "../../../src"; 18 | import {testSharedRoomEventInputs} from "../RoomEvent.test"; 19 | 20 | describe("EmoteEvent", () => { 21 | testSharedRoomEventInputs("m.emote", undefined, x => new EmoteEvent(x), {"m.markup": [{body: "test"}]}); 22 | 23 | const templateEvent: WireEvent.RoomEvent = { 24 | room_id: "!test:example.org", 25 | event_id: "$event", 26 | type: "m.emote", 27 | sender: "@user:example.org", 28 | content: {}, 29 | origin_server_ts: 1670894499800, 30 | }; 31 | 32 | it("should locate a stable markup block", () => { 33 | const block = new EmoteEvent({...templateEvent, content: {"m.markup": [{body: "test"}]}}); 34 | expect(block.markup).toBeDefined(); 35 | expect(block.markup.text).toStrictEqual("test"); 36 | expect(block.text).toStrictEqual("test"); 37 | }); 38 | 39 | it("should locate an unstable markup block", () => { 40 | const event = new EmoteEvent({...templateEvent, content: {"org.matrix.msc1767.markup": [{body: "test"}]}}); 41 | expect(event.markup).toBeDefined(); 42 | expect(event.markup.text).toStrictEqual("test"); 43 | expect(event.text).toStrictEqual("test"); 44 | }); 45 | 46 | it("should prefer the unstable markup block if both are provided", () => { 47 | // Dev note: this test will need updating when extensible events becomes stable 48 | const event = new EmoteEvent({ 49 | ...templateEvent, 50 | content: { 51 | "m.markup": [{body: "stable text"}], 52 | "org.matrix.msc1767.markup": [{body: "unstable text"}], 53 | }, 54 | }); 55 | expect(event.markup).toBeDefined(); 56 | expect(event.markup.text).toStrictEqual("unstable text"); 57 | expect(event.text).toStrictEqual("unstable text"); 58 | }); 59 | 60 | it("should proxy the text and html from the markup block", () => { 61 | const block = new EmoteEvent({ 62 | ...templateEvent, 63 | content: { 64 | "m.markup": [ 65 | {body: "test plain", mimetype: "text/plain"}, 66 | {body: "test html", mimetype: "text/html"}, 67 | ], 68 | }, 69 | }); 70 | expect(block.markup).toBeDefined(); 71 | expect(block.markup.text).toStrictEqual("test plain"); 72 | expect(block.text).toStrictEqual("test plain"); 73 | expect(block.markup.html).toStrictEqual("test html"); 74 | expect(block.html).toStrictEqual("test html"); 75 | }); 76 | 77 | it("should error if a markup block is not present", () => { 78 | expect(() => new EmoteEvent({...templateEvent, content: {no_block: true} as any})).toThrow( 79 | new InvalidEventError("m.emote", "schema does not apply to m.markup or org.matrix.msc1767.markup"), 80 | ); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /test/events/m/MessageEvent.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidEventError, MessageEvent, WireEvent} from "../../../src"; 18 | import {testSharedRoomEventInputs} from "../RoomEvent.test"; 19 | 20 | describe("MessageEvent", () => { 21 | testSharedRoomEventInputs("m.message", undefined, x => new MessageEvent(x), {"m.markup": [{body: "test"}]}); 22 | 23 | const templateEvent: WireEvent.RoomEvent = { 24 | room_id: "!test:example.org", 25 | event_id: "$event", 26 | type: "m.message", 27 | sender: "@user:example.org", 28 | content: {}, 29 | origin_server_ts: 1670894499800, 30 | }; 31 | 32 | it("should locate a stable markup block", () => { 33 | const block = new MessageEvent({...templateEvent, content: {"m.markup": [{body: "test"}]}}); 34 | expect(block.markup).toBeDefined(); 35 | expect(block.markup.text).toStrictEqual("test"); 36 | expect(block.text).toStrictEqual("test"); 37 | }); 38 | 39 | it("should locate an unstable markup block", () => { 40 | const event = new MessageEvent({...templateEvent, content: {"org.matrix.msc1767.markup": [{body: "test"}]}}); 41 | expect(event.markup).toBeDefined(); 42 | expect(event.markup.text).toStrictEqual("test"); 43 | expect(event.text).toStrictEqual("test"); 44 | }); 45 | 46 | it("should prefer the unstable markup block if both are provided", () => { 47 | // Dev note: this test will need updating when extensible events becomes stable 48 | const event = new MessageEvent({ 49 | ...templateEvent, 50 | content: { 51 | "m.markup": [{body: "stable text"}], 52 | "org.matrix.msc1767.markup": [{body: "unstable text"}], 53 | }, 54 | }); 55 | expect(event.markup).toBeDefined(); 56 | expect(event.markup.text).toStrictEqual("unstable text"); 57 | expect(event.text).toStrictEqual("unstable text"); 58 | }); 59 | 60 | it("should proxy the text and html from the markup block", () => { 61 | const block = new MessageEvent({ 62 | ...templateEvent, 63 | content: { 64 | "m.markup": [ 65 | {body: "test plain", mimetype: "text/plain"}, 66 | {body: "test html", mimetype: "text/html"}, 67 | ], 68 | }, 69 | }); 70 | expect(block.markup).toBeDefined(); 71 | expect(block.markup.text).toStrictEqual("test plain"); 72 | expect(block.text).toStrictEqual("test plain"); 73 | expect(block.markup.html).toStrictEqual("test html"); 74 | expect(block.html).toStrictEqual("test html"); 75 | }); 76 | 77 | it("should error if a markup block is not present", () => { 78 | expect(() => new MessageEvent({...templateEvent, content: {no_block: true} as any})).toThrow( 79 | new InvalidEventError("m.message", "schema does not apply to m.markup or org.matrix.msc1767.markup"), 80 | ); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /test/events/m/NoticeEvent.test.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2022 The Matrix.org Foundation C.I.C. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | import {InvalidEventError, NoticeEvent, WireEvent} from "../../../src"; 18 | import {testSharedRoomEventInputs} from "../RoomEvent.test"; 19 | 20 | describe("NoticeEvent", () => { 21 | testSharedRoomEventInputs("m.notice", undefined, x => new NoticeEvent(x), {"m.markup": [{body: "test"}]}); 22 | 23 | const templateEvent: WireEvent.RoomEvent = { 24 | room_id: "!test:example.org", 25 | event_id: "$event", 26 | type: "m.notice", 27 | sender: "@user:example.org", 28 | content: {}, 29 | origin_server_ts: 1670894499800, 30 | }; 31 | 32 | it("should locate a stable markup block", () => { 33 | const block = new NoticeEvent({...templateEvent, content: {"m.markup": [{body: "test"}]}}); 34 | expect(block.markup).toBeDefined(); 35 | expect(block.markup.text).toStrictEqual("test"); 36 | expect(block.text).toStrictEqual("test"); 37 | }); 38 | 39 | it("should locate an unstable markup block", () => { 40 | const event = new NoticeEvent({...templateEvent, content: {"org.matrix.msc1767.markup": [{body: "test"}]}}); 41 | expect(event.markup).toBeDefined(); 42 | expect(event.markup.text).toStrictEqual("test"); 43 | expect(event.text).toStrictEqual("test"); 44 | }); 45 | 46 | it("should prefer the unstable markup block if both are provided", () => { 47 | // Dev note: this test will need updating when extensible events becomes stable 48 | const event = new NoticeEvent({ 49 | ...templateEvent, 50 | content: { 51 | "m.markup": [{body: "stable text"}], 52 | "org.matrix.msc1767.markup": [{body: "unstable text"}], 53 | }, 54 | }); 55 | expect(event.markup).toBeDefined(); 56 | expect(event.markup.text).toStrictEqual("unstable text"); 57 | expect(event.text).toStrictEqual("unstable text"); 58 | }); 59 | 60 | it("should proxy the text and html from the markup block", () => { 61 | const block = new NoticeEvent({ 62 | ...templateEvent, 63 | content: { 64 | "m.markup": [ 65 | {body: "test plain", mimetype: "text/plain"}, 66 | {body: "test html", mimetype: "text/html"}, 67 | ], 68 | }, 69 | }); 70 | expect(block.markup).toBeDefined(); 71 | expect(block.markup.text).toStrictEqual("test plain"); 72 | expect(block.text).toStrictEqual("test plain"); 73 | expect(block.markup.html).toStrictEqual("test html"); 74 | expect(block.html).toStrictEqual("test html"); 75 | }); 76 | 77 | it("should error if a markup block is not present", () => { 78 | expect(() => new NoticeEvent({...templateEvent, content: {no_block: true} as any})).toThrow( 79 | new InvalidEventError("m.notice", "schema does not apply to m.markup or org.matrix.msc1767.markup"), 80 | ); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": [ 4 | "./src/**/*.ts" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2016", 4 | "experimentalDecorators": false, 5 | "esModuleInterop": true, 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "noUnusedLocals": true, 9 | "sourceMap": true, 10 | "declaration": true, 11 | "outDir": "./lib", 12 | "strict": true, 13 | }, 14 | "include": [ 15 | "./src/**/*.ts", 16 | "./test/**/*.ts" 17 | ] 18 | } 19 | --------------------------------------------------------------------------------