├── .github ├── dependabot.yml └── workflows │ ├── ci.yml │ ├── close-issues.yml │ └── release.yml ├── .gitignore ├── LICENSE ├── README.md ├── build.mjs ├── bun.lockb ├── bunfig.toml ├── package-lock.json ├── package.json ├── src ├── client.test.ts ├── client.ts ├── domain.ts ├── http.ts └── index.ts └── tsconfig.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | 11 | strategy: 12 | matrix: 13 | os: [ubuntu-latest, macos-latest] 14 | fail-fast: false 15 | 16 | steps: 17 | - id: checkout 18 | name: Checkout 19 | uses: actions/checkout@v3 20 | - id: setup-bun 21 | name: Setup Bun 22 | uses: oven-sh/setup-bun@v1 23 | with: 24 | bun-version: latest 25 | - id: install-deps 26 | name: Install dependencies 27 | run: | 28 | bun install 29 | - id: test 30 | name: Run test 31 | run: | 32 | bun test 33 | -------------------------------------------------------------------------------- /.github/workflows/close-issues.yml: -------------------------------------------------------------------------------- 1 | name: Close inactive issues 2 | on: 3 | schedule: 4 | - cron: "30 1 * * *" 5 | 6 | jobs: 7 | close-issues: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | issues: write 11 | steps: 12 | - uses: actions/stale@v5 13 | with: 14 | days-before-issue-stale: 7 15 | days-before-issue-close: 7 16 | days-before-pr-close: -1 17 | days-before-pr-stale: -1 18 | stale-issue-message: "This issue is stale because it has been open for 7 days with no activity." 19 | close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale." 20 | stale-issue-label: "stale" 21 | exempt-all-assignees: true 22 | repo-token: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - id: checkout 12 | name: Checkout 13 | uses: actions/checkout@v3 14 | - id: setup-bun 15 | name: Setup Bun 16 | uses: oven-sh/setup-bun@v1 17 | with: 18 | bun-version: latest 19 | - id: install-deps 20 | name: Install dependencies 21 | run: | 22 | bun install 23 | - id: update-package-version 24 | name: Update package version 25 | run: | 26 | sed -i "s/\"version\": \".*\"/\"version\": \"${GITHUB_REF_NAME#v}\"/" package.json 27 | - id: build 28 | name: Build 29 | run: | 30 | bun run build 31 | - uses: actions/setup-node@v3 32 | with: 33 | registry-url: "https://registry.npmjs.org" 34 | - run: npm publish 35 | env: 36 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # File created using '.gitignore Generator' for Visual Studio Code: https://bit.ly/vscode-gig 2 | # Created by https://www.toptal.com/developers/gitignore/api/visualstudiocode,macos,linux,node,windows 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=visualstudiocode,macos,linux,node,windows 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### macOS ### 21 | # General 22 | .DS_Store 23 | .AppleDouble 24 | .LSOverride 25 | 26 | # Icon must end with two \r 27 | Icon 28 | 29 | 30 | # Thumbnails 31 | ._* 32 | 33 | # Files that might appear in the root of a volume 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | 49 | ### macOS Patch ### 50 | # iCloud generated files 51 | *.icloud 52 | 53 | ### Node ### 54 | # Logs 55 | logs 56 | *.log 57 | npm-debug.log* 58 | yarn-debug.log* 59 | yarn-error.log* 60 | lerna-debug.log* 61 | .pnpm-debug.log* 62 | 63 | # Diagnostic reports (https://nodejs.org/api/report.html) 64 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 65 | 66 | # Runtime data 67 | pids 68 | *.pid 69 | *.seed 70 | *.pid.lock 71 | 72 | # Directory for instrumented libs generated by jscoverage/JSCover 73 | lib-cov 74 | 75 | # Coverage directory used by tools like istanbul 76 | coverage 77 | *.lcov 78 | 79 | # nyc test coverage 80 | .nyc_output 81 | 82 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 83 | .grunt 84 | 85 | # Bower dependency directory (https://bower.io/) 86 | bower_components 87 | 88 | # node-waf configuration 89 | .lock-wscript 90 | 91 | # Compiled binary addons (https://nodejs.org/api/addons.html) 92 | build/Release 93 | 94 | # Dependency directories 95 | node_modules/ 96 | jspm_packages/ 97 | 98 | # Snowpack dependency directory (https://snowpack.dev/) 99 | web_modules/ 100 | 101 | # TypeScript cache 102 | *.tsbuildinfo 103 | 104 | # Optional npm cache directory 105 | .npm 106 | 107 | # Optional eslint cache 108 | .eslintcache 109 | 110 | # Optional stylelint cache 111 | .stylelintcache 112 | 113 | # Microbundle cache 114 | .rpt2_cache/ 115 | .rts2_cache_cjs/ 116 | .rts2_cache_es/ 117 | .rts2_cache_umd/ 118 | 119 | # Optional REPL history 120 | .node_repl_history 121 | 122 | # Output of 'npm pack' 123 | *.tgz 124 | 125 | # Yarn Integrity file 126 | .yarn-integrity 127 | 128 | # dotenv environment variable files 129 | .env 130 | .env.development.local 131 | .env.test.local 132 | .env.production.local 133 | .env.local 134 | 135 | # parcel-bundler cache (https://parceljs.org/) 136 | .cache 137 | .parcel-cache 138 | 139 | # Next.js build output 140 | .next 141 | out 142 | 143 | # Nuxt.js build / generate output 144 | .nuxt 145 | dist 146 | 147 | # Gatsby files 148 | .cache/ 149 | # Comment in the public line in if your project uses Gatsby and not Next.js 150 | # https://nextjs.org/blog/next-9-1#public-directory-support 151 | # public 152 | 153 | # vuepress build output 154 | .vuepress/dist 155 | 156 | # vuepress v2.x temp and cache directory 157 | .temp 158 | 159 | # Docusaurus cache and generated files 160 | .docusaurus 161 | 162 | # Serverless directories 163 | .serverless/ 164 | 165 | # FuseBox cache 166 | .fusebox/ 167 | 168 | # DynamoDB Local files 169 | .dynamodb/ 170 | 171 | # TernJS port file 172 | .tern-port 173 | 174 | # Stores VSCode versions used for testing VSCode extensions 175 | .vscode-test 176 | 177 | # yarn v2 178 | .yarn/cache 179 | .yarn/unplugged 180 | .yarn/build-state.yml 181 | .yarn/install-state.gz 182 | .pnp.* 183 | 184 | ### Node Patch ### 185 | # Serverless Webpack directories 186 | .webpack/ 187 | 188 | # Optional stylelint cache 189 | 190 | # SvelteKit build / generate output 191 | .svelte-kit 192 | 193 | ### VisualStudioCode ### 194 | .vscode/* 195 | !.vscode/settings.json 196 | !.vscode/tasks.json 197 | !.vscode/launch.json 198 | !.vscode/extensions.json 199 | !.vscode/*.code-snippets 200 | 201 | # Local History for Visual Studio Code 202 | .history/ 203 | 204 | # Built Visual Studio Code Extensions 205 | *.vsix 206 | 207 | ### VisualStudioCode Patch ### 208 | # Ignore all local history of files 209 | .history 210 | .ionide 211 | 212 | ### Windows ### 213 | # Windows thumbnail cache files 214 | Thumbs.db 215 | Thumbs.db:encryptable 216 | ehthumbs.db 217 | ehthumbs_vista.db 218 | 219 | # Dump file 220 | *.stackdump 221 | 222 | # Folder config file 223 | [Dd]esktop.ini 224 | 225 | # Recycle Bin used on file shares 226 | $RECYCLE.BIN/ 227 | 228 | # Windows Installer files 229 | *.cab 230 | *.msi 231 | *.msix 232 | *.msm 233 | *.msp 234 | 235 | # Windows shortcuts 236 | *.lnk 237 | 238 | # End of https://www.toptal.com/developers/gitignore/api/visualstudiocode,macos,linux,node,windows 239 | 240 | # Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option) 241 | 242 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📱 SMS Gateway for Android™ JS/TS API Client 2 | 3 | [![npm Version](https://img.shields.io/npm/v/android-sms-gateway.svg?style=for-the-badge)](https://www.npmjs.com/package/android-sms-gateway) 4 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=for-the-badge)](https://github.com/android-sms-gateway/client-ts/blob/master/LICENSE) 5 | [![Downloads](https://img.shields.io/npm/dw/android-sms-gateway.svg?style=for-the-badge)](https://www.npmjs.com/package/android-sms-gateway) 6 | [![GitHub Issues](https://img.shields.io/github/issues/android-sms-gateway/client-ts.svg?style=for-the-badge)](https://github.com/android-sms-gateway/client-ts/issues) 7 | [![GitHub Stars](https://img.shields.io/github/stars/android-sms-gateway/client-ts.svg?style=for-the-badge)](https://github.com/android-sms-gateway/client-ts/stargazers) 8 | [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg?style=for-the-badge)](https://www.typescriptlang.org/) 9 | 10 | A TypeScript-first client for seamless integration with the [SMS Gateway for Android](https://sms-gate.app) API. Programmatically send SMS messages through your Android devices with strict typing and modern JavaScript features. 11 | 12 | **Note**: The API doesn't provide CORS headers, so the library cannot be used in a browser environment directly. 13 | 14 | ## 📖 Table of Contents 15 | - [📱 SMS Gateway for Android™ JS/TS API Client](#-sms-gateway-for-android-jsts-api-client) 16 | - [📖 Table of Contents](#-table-of-contents) 17 | - [✨ Features](#-features) 18 | - [⚙️ Requirements](#️-requirements) 19 | - [📦 Installation](#-installation) 20 | - [🚀 Quickstart](#-quickstart) 21 | - [Basic Usage](#basic-usage) 22 | - [Webhook Management](#webhook-management) 23 | - [🤖 Client Guide](#-client-guide) 24 | - [Client Configuration](#client-configuration) 25 | - [Core Methods](#core-methods) 26 | - [Type Definitions](#type-definitions) 27 | - [🌐 HTTP Clients](#-http-clients) 28 | - [🔒 Security Notes](#-security-notes) 29 | - [📚 API Reference](#-api-reference) 30 | - [👥 Contributing](#-contributing) 31 | - [Development Setup](#development-setup) 32 | - [📄 License](#-license) 33 | 34 | ## ✨ Features 35 | - **TypeScript Ready**: Full type definitions out of the box 36 | - **Flexible HTTP Clients**: Works with any HTTP library (fetch, axios, node-fetch, etc.) 37 | - **Promise-based API**: Async/await ready 38 | - **Webhook Management**: Create, read, and delete webhooks 39 | - **Customizable Base URL**: Point to different API endpoints 40 | - **Server-Side Focus**: Designed for Node.js environments 41 | 42 | ## ⚙️ Requirements 43 | - Node.js v18+ 44 | - npm/yarn/bun package manager 45 | 46 | ## 📦 Installation 47 | 48 | ```bash 49 | npm install android-sms-gateway 50 | # or 51 | yarn add android-sms-gateway 52 | # or 53 | bun add android-sms-gateway 54 | ``` 55 | 56 | ## 🚀 Quickstart 57 | 58 | ### Basic Usage 59 | ```typescript 60 | import Client from 'android-sms-gateway'; 61 | 62 | // Create a fetch-based HTTP client 63 | const httpFetchClient = { 64 | get: async (url, headers) => { 65 | const response = await fetch(url, { 66 | method: "GET", 67 | headers 68 | }); 69 | 70 | return response.json(); 71 | }, 72 | post: async (url, body, headers) => { 73 | const response = await fetch(url, { 74 | method: "POST", 75 | headers, 76 | body: JSON.stringify(body) 77 | }); 78 | 79 | return response.json(); 80 | }, 81 | delete: async (url, headers) => { 82 | const response = await fetch(url, { 83 | method: "DELETE", 84 | headers 85 | }); 86 | 87 | return response.json(); 88 | } 89 | }; 90 | 91 | // Initialize client 92 | const api = new Client( 93 | process.env.ANDROID_SMS_GATEWAY_LOGIN!, 94 | process.env.ANDROID_SMS_GATEWAY_PASSWORD!, 95 | httpFetchClient 96 | ); 97 | 98 | // Send message 99 | const message = { 100 | phoneNumbers: ['+1234567890'], 101 | message: 'Secure OTP: 123456 🔐' 102 | }; 103 | 104 | async function sendSMS() { 105 | try { 106 | const state = await api.send(message); 107 | console.log('Message ID:', state.id); 108 | 109 | // Check status after 5 seconds 110 | setTimeout(async () => { 111 | const updatedState = await api.getState(state.id); 112 | console.log('Message status:', updatedState.status); 113 | }, 5000); 114 | } catch (error) { 115 | console.error('Sending failed:', error); 116 | } 117 | } 118 | 119 | sendSMS(); 120 | ``` 121 | 122 | ### Webhook Management 123 | ```typescript 124 | // Create webhook 125 | const webhook = { 126 | url: 'https://your-api.com/sms-callback', 127 | event: WebHookEventType.SmsReceived, 128 | }; 129 | 130 | api.registerWebhook(webhook) 131 | .then(created => console.log('Webhook created:', created.id)) 132 | .catch(console.error); 133 | 134 | // List webhooks 135 | api.getWebhooks() 136 | .then(webhooks => console.log('Active webhooks:', webhooks.length)); 137 | ``` 138 | 139 | ## 🤖 Client Guide 140 | 141 | ### Client Configuration 142 | 143 | The `Client` class accepts the following constructor arguments: 144 | 145 | | Argument | Description | Default | 146 | | ------------ | -------------------------- | ---------------------------------------- | 147 | | `login` | Username | **Required** | 148 | | `password` | Password | **Required** | 149 | | `httpClient` | HTTP client implementation | **Required** | 150 | | `baseUrl` | API base URL | `"https://api.sms-gate.app/3rdparty/v1"` | 151 | 152 | ### Core Methods 153 | | Method | Description | Returns | 154 | | -------------------------------------------------- | ------------------------ | ----------------------- | 155 | | `send(message: Message)` | Send SMS message | `Promise` | 156 | | `getState(messageId: string)` | Check message status | `Promise` | 157 | | `getWebhooks()` | List registered webhooks | `Promise` | 158 | | `registerWebhook(request: RegisterWebHookRequest)` | Register new webhook | `Promise` | 159 | | `deleteWebhook(webhookId: string)` | Remove webhook | `Promise` | 160 | 161 | ### Type Definitions 162 | ```typescript 163 | interface Message { 164 | id?: string | null; 165 | message: string; 166 | ttl?: number | null; 167 | phoneNumbers: string[]; 168 | simNumber?: number | null; 169 | withDeliveryReport?: boolean | null; 170 | } 171 | 172 | interface MessageState { 173 | id: string; 174 | state: ProcessState; 175 | recipients: RecipientState[]; 176 | } 177 | 178 | interface WebHook { 179 | id: string; 180 | event: WebHookEventType; 181 | url: string; 182 | } 183 | ``` 184 | 185 | For more details, see the [`domain.ts`](./src/domain.ts). 186 | 187 | ## 🌐 HTTP Clients 188 | 189 | The library doesn't come with built-in HTTP clients. Instead, you should provide your own implementation of the `HttpClient` interface: 190 | 191 | ```typescript 192 | interface HttpClient { 193 | get(url: string, headers?: Record): Promise; 194 | post(url: string, body: any, headers?: Record): Promise; 195 | delete(url: string, headers?: Record): Promise; 196 | } 197 | ``` 198 | 199 | ## 🔒 Security Notes 200 | 201 | ⚠️ **Important Security Practices** 202 | - Always store credentials in environment variables 203 | - Never expose credentials in client-side code 204 | - Use HTTPS for all production communications 205 | 206 | ## 📚 API Reference 207 | For complete API documentation including all available methods, request/response schemas, and error codes, visit: 208 | [📘 Official API Documentation](https://docs.sms-gate.app/integration/api/) 209 | 210 | ## 👥 Contributing 211 | 212 | We welcome contributions! Please follow these steps: 213 | 214 | 1. Fork the repository 215 | 2. Create a feature branch (`git checkout -b feature/AmazingFeature`) 216 | 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 217 | 4. Push to the branch (`git push origin feature/AmazingFeature`) 218 | 5. Open a Pull Request 219 | 220 | ### Development Setup 221 | ```bash 222 | git clone https://github.com/android-sms-gateway/client-ts.git 223 | cd client-ts 224 | bun install 225 | bun run build 226 | bun test 227 | ``` 228 | 229 | ## 📄 License 230 | Distributed under the Apache 2.0 License. See [LICENSE](LICENSE) for more information. 231 | 232 | --- 233 | 234 | **Note**: Android is a trademark of Google LLC. This project is not affiliated with or endorsed by Google. 235 | -------------------------------------------------------------------------------- /build.mjs: -------------------------------------------------------------------------------- 1 | import dts from 'bun-plugin-dts' 2 | 3 | await Bun.build({ 4 | entrypoints: ['./src/index.ts'], 5 | outdir: './dist', 6 | minify: false, 7 | plugins: [dts()] 8 | }) -------------------------------------------------------------------------------- /bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/android-sms-gateway/client-ts/c1308f485c24fa7568a2a2efc45bd56da5317965/bun.lockb -------------------------------------------------------------------------------- /bunfig.toml: -------------------------------------------------------------------------------- 1 | [test] 2 | 3 | # always enable coverage 4 | coverage = true 5 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "android-sms-gateway", 3 | "version": "2.0.0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "android-sms-gateway", 9 | "version": "2.0.0", 10 | "license": "Apache-2.0", 11 | "devDependencies": { 12 | "bun-plugin-dts": "^0.3.0", 13 | "bun-types": "latest" 14 | }, 15 | "peerDependencies": { 16 | "typescript": "^5.0.0" 17 | } 18 | }, 19 | "node_modules/@types/node": { 20 | "version": "22.14.1", 21 | "resolved": "https://registry.npmjs.org/@types/node/-/node-22.14.1.tgz", 22 | "integrity": "sha512-u0HuPQwe/dHrItgHHpmw3N2fYCR6x4ivMNbPHRkBVP4CvN+kiRrKHWk3i8tXiO/joPwXLMYvF9TTF0eqgHIuOw==", 23 | "dev": true, 24 | "license": "MIT", 25 | "dependencies": { 26 | "undici-types": "~6.21.0" 27 | } 28 | }, 29 | "node_modules/ansi-regex": { 30 | "version": "5.0.1", 31 | "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", 32 | "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", 33 | "dev": true, 34 | "engines": { 35 | "node": ">=8" 36 | } 37 | }, 38 | "node_modules/ansi-styles": { 39 | "version": "4.3.0", 40 | "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", 41 | "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", 42 | "dev": true, 43 | "dependencies": { 44 | "color-convert": "^2.0.1" 45 | }, 46 | "engines": { 47 | "node": ">=8" 48 | }, 49 | "funding": { 50 | "url": "https://github.com/chalk/ansi-styles?sponsor=1" 51 | } 52 | }, 53 | "node_modules/bun-plugin-dts": { 54 | "version": "0.3.0", 55 | "resolved": "https://registry.npmjs.org/bun-plugin-dts/-/bun-plugin-dts-0.3.0.tgz", 56 | "integrity": "sha512-QpiAOKfPcdOToxySOqRY8FwL+brTvyXEHWzrSCRKt4Pv7Z4pnUrhK9tFtM7Ndm7ED09B/0cGXnHJKqmekr/ERw==", 57 | "dev": true, 58 | "dependencies": { 59 | "common-path-prefix": "^3.0.0", 60 | "dts-bundle-generator": "^9.5.1", 61 | "get-tsconfig": "^4.8.1" 62 | } 63 | }, 64 | "node_modules/bun-types": { 65 | "version": "1.2.15", 66 | "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.2.15.tgz", 67 | "integrity": "sha512-NarRIaS+iOaQU1JPfyKhZm4AsUOrwUOqRNHY0XxI8GI8jYxiLXLcdjYMG9UKS+fwWasc1uw1htV9AX24dD+p4w==", 68 | "dev": true, 69 | "license": "MIT", 70 | "dependencies": { 71 | "@types/node": "*" 72 | } 73 | }, 74 | "node_modules/cliui": { 75 | "version": "8.0.1", 76 | "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", 77 | "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", 78 | "dev": true, 79 | "dependencies": { 80 | "string-width": "^4.2.0", 81 | "strip-ansi": "^6.0.1", 82 | "wrap-ansi": "^7.0.0" 83 | }, 84 | "engines": { 85 | "node": ">=12" 86 | } 87 | }, 88 | "node_modules/color-convert": { 89 | "version": "2.0.1", 90 | "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", 91 | "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", 92 | "dev": true, 93 | "dependencies": { 94 | "color-name": "~1.1.4" 95 | }, 96 | "engines": { 97 | "node": ">=7.0.0" 98 | } 99 | }, 100 | "node_modules/color-name": { 101 | "version": "1.1.4", 102 | "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", 103 | "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", 104 | "dev": true 105 | }, 106 | "node_modules/common-path-prefix": { 107 | "version": "3.0.0", 108 | "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", 109 | "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", 110 | "dev": true 111 | }, 112 | "node_modules/dts-bundle-generator": { 113 | "version": "9.5.1", 114 | "resolved": "https://registry.npmjs.org/dts-bundle-generator/-/dts-bundle-generator-9.5.1.tgz", 115 | "integrity": "sha512-DxpJOb2FNnEyOzMkG11sxO2dmxPjthoVWxfKqWYJ/bI/rT1rvTMktF5EKjAYrRZu6Z6t3NhOUZ0sZ5ZXevOfbA==", 116 | "dev": true, 117 | "dependencies": { 118 | "typescript": ">=5.0.2", 119 | "yargs": "^17.6.0" 120 | }, 121 | "bin": { 122 | "dts-bundle-generator": "dist/bin/dts-bundle-generator.js" 123 | }, 124 | "engines": { 125 | "node": ">=14.0.0" 126 | } 127 | }, 128 | "node_modules/emoji-regex": { 129 | "version": "8.0.0", 130 | "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", 131 | "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", 132 | "dev": true 133 | }, 134 | "node_modules/escalade": { 135 | "version": "3.1.2", 136 | "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", 137 | "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", 138 | "dev": true, 139 | "engines": { 140 | "node": ">=6" 141 | } 142 | }, 143 | "node_modules/get-caller-file": { 144 | "version": "2.0.5", 145 | "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", 146 | "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", 147 | "dev": true, 148 | "engines": { 149 | "node": "6.* || 8.* || >= 10.*" 150 | } 151 | }, 152 | "node_modules/get-tsconfig": { 153 | "version": "4.8.1", 154 | "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.8.1.tgz", 155 | "integrity": "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==", 156 | "dev": true, 157 | "dependencies": { 158 | "resolve-pkg-maps": "^1.0.0" 159 | }, 160 | "funding": { 161 | "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" 162 | } 163 | }, 164 | "node_modules/is-fullwidth-code-point": { 165 | "version": "3.0.0", 166 | "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", 167 | "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", 168 | "dev": true, 169 | "engines": { 170 | "node": ">=8" 171 | } 172 | }, 173 | "node_modules/require-directory": { 174 | "version": "2.1.1", 175 | "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", 176 | "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", 177 | "dev": true, 178 | "engines": { 179 | "node": ">=0.10.0" 180 | } 181 | }, 182 | "node_modules/resolve-pkg-maps": { 183 | "version": "1.0.0", 184 | "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", 185 | "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", 186 | "dev": true, 187 | "funding": { 188 | "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" 189 | } 190 | }, 191 | "node_modules/string-width": { 192 | "version": "4.2.3", 193 | "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", 194 | "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", 195 | "dev": true, 196 | "dependencies": { 197 | "emoji-regex": "^8.0.0", 198 | "is-fullwidth-code-point": "^3.0.0", 199 | "strip-ansi": "^6.0.1" 200 | }, 201 | "engines": { 202 | "node": ">=8" 203 | } 204 | }, 205 | "node_modules/strip-ansi": { 206 | "version": "6.0.1", 207 | "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", 208 | "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", 209 | "dev": true, 210 | "dependencies": { 211 | "ansi-regex": "^5.0.1" 212 | }, 213 | "engines": { 214 | "node": ">=8" 215 | } 216 | }, 217 | "node_modules/typescript": { 218 | "version": "5.3.3", 219 | "license": "Apache-2.0", 220 | "bin": { 221 | "tsc": "bin/tsc", 222 | "tsserver": "bin/tsserver" 223 | }, 224 | "engines": { 225 | "node": ">=14.17" 226 | } 227 | }, 228 | "node_modules/undici-types": { 229 | "version": "6.21.0", 230 | "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", 231 | "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", 232 | "dev": true, 233 | "license": "MIT" 234 | }, 235 | "node_modules/wrap-ansi": { 236 | "version": "7.0.0", 237 | "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", 238 | "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", 239 | "dev": true, 240 | "dependencies": { 241 | "ansi-styles": "^4.0.0", 242 | "string-width": "^4.1.0", 243 | "strip-ansi": "^6.0.0" 244 | }, 245 | "engines": { 246 | "node": ">=10" 247 | }, 248 | "funding": { 249 | "url": "https://github.com/chalk/wrap-ansi?sponsor=1" 250 | } 251 | }, 252 | "node_modules/y18n": { 253 | "version": "5.0.8", 254 | "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", 255 | "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", 256 | "dev": true, 257 | "engines": { 258 | "node": ">=10" 259 | } 260 | }, 261 | "node_modules/yargs": { 262 | "version": "17.7.2", 263 | "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", 264 | "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", 265 | "dev": true, 266 | "dependencies": { 267 | "cliui": "^8.0.1", 268 | "escalade": "^3.1.1", 269 | "get-caller-file": "^2.0.5", 270 | "require-directory": "^2.1.1", 271 | "string-width": "^4.2.3", 272 | "y18n": "^5.0.5", 273 | "yargs-parser": "^21.1.1" 274 | }, 275 | "engines": { 276 | "node": ">=12" 277 | } 278 | }, 279 | "node_modules/yargs-parser": { 280 | "version": "21.1.1", 281 | "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", 282 | "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", 283 | "dev": true, 284 | "engines": { 285 | "node": ">=12" 286 | } 287 | } 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "android-sms-gateway", 3 | "license": "Apache-2.0", 4 | "description": "A JS/TS client library for sending and managing SMS messages via the SMS Gateway for Android™", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/android-sms-gateway/client-ts.git" 8 | }, 9 | "homepage": "https://sms-gate.app", 10 | "keywords": [ 11 | "bun", 12 | "sms", 13 | "android", 14 | "sms-gateway", 15 | "api", 16 | "client", 17 | "typescript" 18 | ], 19 | "author": { 20 | "name": "Aleksandr Soloshenko", 21 | "email": "admin@sms-gate.app", 22 | "url": "https://github.com/capcom6" 23 | }, 24 | "bugs": { 25 | "url": "https://github.com/android-sms-gateway/client-ts/issues" 26 | }, 27 | "version": "2.0.0", 28 | "main": "dist/index.js", 29 | "types": "dist/index.d.ts", 30 | "files": [ 31 | "dist" 32 | ], 33 | "devDependencies": { 34 | "bun-plugin-dts": "^0.3.0", 35 | "bun-types": "latest" 36 | }, 37 | "peerDependencies": { 38 | "typescript": "^5.0.0" 39 | }, 40 | "scripts": { 41 | "build": "bun run build.mjs", 42 | "prepublishOnly": "bun run build" 43 | } 44 | } -------------------------------------------------------------------------------- /src/client.test.ts: -------------------------------------------------------------------------------- 1 | import { BASE_URL, Client } from './client'; 2 | import { Message, MessageState, RegisterWebHookRequest, ProcessState, WebHook, WebHookEventType } from './domain'; 3 | import { HttpClient } from './http'; 4 | 5 | import { beforeEach, describe, expect, it, jest } from "bun:test"; 6 | 7 | describe('Client', () => { 8 | let client: Client; 9 | let mockHttpClient: HttpClient; 10 | 11 | beforeEach(() => { 12 | mockHttpClient = { 13 | get: jest.fn(), 14 | post: jest.fn(), 15 | delete: jest.fn(), 16 | }; 17 | client = new Client('login', 'password', mockHttpClient); 18 | }); 19 | 20 | it('sends a message', async () => { 21 | const message: Message = { 22 | message: 'Hello', 23 | phoneNumbers: ['+1234567890'], 24 | }; 25 | const expectedState: MessageState = { 26 | id: '123', 27 | state: ProcessState.Pending, 28 | recipients: [ 29 | { 30 | phoneNumber: '+1234567890', 31 | state: ProcessState.Pending, 32 | } 33 | ] 34 | }; 35 | 36 | mockHttpClient.post.mockResolvedValue(expectedState); 37 | 38 | const result = await client.send(message); 39 | 40 | expect(mockHttpClient.post).toHaveBeenCalledWith( 41 | `${BASE_URL}/message`, 42 | message, 43 | { 44 | "Content-Type": "application/json", 45 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 46 | Authorization: expect.any(String), 47 | }, 48 | ); 49 | expect(result).toBe(expectedState); 50 | }); 51 | 52 | it('gets the state of a message', async () => { 53 | const messageId = '123'; 54 | const expectedState: MessageState = { 55 | id: '123', 56 | state: ProcessState.Pending, 57 | recipients: [ 58 | { 59 | phoneNumber: '+1234567890', 60 | state: ProcessState.Pending, 61 | } 62 | ] 63 | }; 64 | 65 | mockHttpClient.get.mockResolvedValue(expectedState); 66 | 67 | const result = await client.getState(messageId); 68 | 69 | expect(mockHttpClient.get).toHaveBeenCalledWith( 70 | `${BASE_URL}/message/${messageId}`, 71 | { 72 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 73 | Authorization: expect.any(String), 74 | }, 75 | ); 76 | expect(result).toBe(expectedState); 77 | }); 78 | 79 | it('gets webhooks', async () => { 80 | const expectedWebhooks: WebHook[] = [ 81 | { id: '1', url: 'https://example.com/webhook1', event: WebHookEventType.SmsReceived }, 82 | { id: '2', url: 'https://example.com/webhook2', event: WebHookEventType.SystemPing }, 83 | ]; 84 | 85 | mockHttpClient.get.mockResolvedValue(expectedWebhooks); 86 | 87 | const result = await client.getWebhooks(); 88 | 89 | expect(mockHttpClient.get).toHaveBeenCalledWith( 90 | `${BASE_URL}/webhooks`, 91 | { 92 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 93 | Authorization: expect.any(String), 94 | }, 95 | ); 96 | expect(result).toEqual(expectedWebhooks); 97 | }); 98 | 99 | it('register a webhook', async () => { 100 | const req: RegisterWebHookRequest = { 101 | url: 'https://example.com/webhook', 102 | event: WebHookEventType.SmsReceived, 103 | } 104 | const expectedRes: WebHook = { 105 | id: 'test', 106 | url: 'https://example.com/webhook', 107 | event: WebHookEventType.SmsReceived, 108 | }; 109 | 110 | mockHttpClient.post.mockResolvedValue(expectedRes); 111 | 112 | const result = await client.registerWebhook(req); 113 | 114 | expect(mockHttpClient.post).toHaveBeenCalledWith( 115 | `${BASE_URL}/webhooks`, 116 | req, 117 | { 118 | "Content-Type": "application/json", 119 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 120 | Authorization: expect.any(String), 121 | }, 122 | ); 123 | expect(result).toBe(expectedRes); 124 | }); 125 | 126 | it('delete a webhook', async () => { 127 | mockHttpClient.post.mockResolvedValue(undefined); 128 | 129 | const result = await client.deleteWebhook('test'); 130 | 131 | expect(mockHttpClient.delete).toHaveBeenCalledWith( 132 | `${BASE_URL}/webhooks/test`, 133 | { 134 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 135 | Authorization: expect.any(String), 136 | }, 137 | ); 138 | expect(result).toBe(undefined); 139 | }); 140 | }); -------------------------------------------------------------------------------- /src/client.ts: -------------------------------------------------------------------------------- 1 | import { Message, MessageState, RegisterWebHookRequest, WebHook } from "./domain"; 2 | import { HttpClient } from "./http"; 3 | 4 | export const BASE_URL = "https://api.sms-gate.app/3rdparty/v1"; 5 | 6 | export class Client { 7 | private baseUrl: string; 8 | private httpClient: HttpClient; 9 | private defaultHeaders: Record; 10 | 11 | constructor(login: string, password: string, httpClient: HttpClient, baseUrl = BASE_URL) { 12 | this.baseUrl = baseUrl; 13 | this.httpClient = httpClient; 14 | this.defaultHeaders = { 15 | "User-Agent": "android-sms-gateway/2.0 (client; js)", 16 | "Authorization": `Basic ${btoa(`${login}:${password}`)}`, 17 | } 18 | } 19 | 20 | async send(request: Message): Promise { 21 | const url = `${this.baseUrl}/message`; 22 | const headers = { 23 | "Content-Type": "application/json", 24 | ...this.defaultHeaders, 25 | }; 26 | 27 | return this.httpClient.post(url, request, headers); 28 | } 29 | 30 | async getState(messageId: string): Promise { 31 | const url = `${this.baseUrl}/message/${messageId}`; 32 | const headers = { 33 | ...this.defaultHeaders, 34 | }; 35 | 36 | return this.httpClient.get(url, headers); 37 | } 38 | 39 | async getWebhooks(): Promise { 40 | const url = `${this.baseUrl}/webhooks`; 41 | const headers = { 42 | ...this.defaultHeaders, 43 | }; 44 | 45 | return this.httpClient.get(url, headers); 46 | } 47 | 48 | async registerWebhook(request: RegisterWebHookRequest): Promise { 49 | const url = `${this.baseUrl}/webhooks`; 50 | const headers = { 51 | "Content-Type": "application/json", 52 | ...this.defaultHeaders, 53 | }; 54 | 55 | return this.httpClient.post(url, request, headers); 56 | } 57 | 58 | async deleteWebhook(webhookId: string): Promise { 59 | const url = `${this.baseUrl}/webhooks/${webhookId}`; 60 | const headers = { 61 | ...this.defaultHeaders, 62 | }; 63 | 64 | return this.httpClient.delete(url, headers); 65 | } 66 | } -------------------------------------------------------------------------------- /src/domain.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export enum ProcessState { 4 | Pending = "Pending", 5 | Processed = "Processed", 6 | Sent = "Sent", 7 | Delivered = "Delivered", 8 | Failed = "Failed", 9 | } 10 | 11 | /** 12 | * Represents the state of a recipient of an SMS message. 13 | */ 14 | export interface RecipientState { 15 | /** 16 | * The phone number of the recipient. 17 | */ 18 | phoneNumber: string; 19 | 20 | /** 21 | * The state of the recipient. 22 | */ 23 | state: ProcessState; 24 | 25 | /** 26 | * An optional error message, if the recipient failed to receive the message. 27 | */ 28 | error?: string | null; 29 | } 30 | 31 | /** 32 | * Represents the state of an SMS message. 33 | */ 34 | export interface MessageState { 35 | /** 36 | * The ID of the message. 37 | */ 38 | id: string; 39 | 40 | /** 41 | * The state of the message. 42 | */ 43 | state: ProcessState; 44 | 45 | /** 46 | * The list of recipients' states for the message. 47 | */ 48 | recipients: RecipientState[]; 49 | } 50 | 51 | /** 52 | * Represents an SMS message. 53 | */ 54 | export interface Message { 55 | /** 56 | * The ID of the message, will be generated if not provided. 57 | * @default null 58 | */ 59 | id?: string | null; 60 | 61 | /** 62 | * The message content. 63 | */ 64 | message: string; 65 | 66 | /** 67 | * The time-to-live (TTL) of the message in seconds. 68 | * If set to null, the message will not expire. 69 | * @default null 70 | */ 71 | ttl?: number | null; 72 | 73 | /** 74 | * The phone numbers to send the message to. 75 | */ 76 | phoneNumbers: string[]; 77 | 78 | /** 79 | * The SIM number to send the message from. 80 | * If not specified, the message will be sent from the default SIM. 81 | * @default null 82 | */ 83 | simNumber?: number | null; 84 | 85 | /** 86 | * Whether to include a delivery report for the message. 87 | * @default true 88 | */ 89 | withDeliveryReport?: boolean | null; 90 | } 91 | 92 | /** 93 | * Represents the type of events that can trigger a webhook. 94 | */ 95 | export enum WebHookEventType { 96 | /** 97 | * Indicates that a new SMS message has been received. 98 | */ 99 | SmsReceived = 'sms:received', 100 | 101 | /** 102 | * Indicates that a ping request has been sent. 103 | */ 104 | SystemPing = 'system:ping', 105 | } 106 | 107 | /** 108 | * Represents a request to create or update a webhook. 109 | */ 110 | export interface RegisterWebHookRequest { 111 | /** 112 | * The ID of the webhook. 113 | * If not specified, a new ID will be generated. 114 | * @default null 115 | */ 116 | id?: string | null; 117 | 118 | /** 119 | * The event type that triggers the webhook. 120 | */ 121 | event: WebHookEventType; 122 | 123 | /** 124 | * The URL to send the webhook request to. 125 | */ 126 | url: string; 127 | } 128 | 129 | /** 130 | * Represents a webhook configuration. 131 | * @see RegisterWebHookRequest 132 | */ 133 | export type WebHook = Required; 134 | 135 | export type WebHookEvent = { 136 | id: string; 137 | webhookId: string; 138 | deviceId: string; 139 | } & WebHookPayload 140 | 141 | /** 142 | * Represents the payload of a webhook event. 143 | */ 144 | export type WebHookPayload = 145 | /** 146 | * Represents the payload of a webhook event of type `SmsReceived`. 147 | */ 148 | { 149 | /** 150 | * The event type. 151 | */ 152 | event: WebHookEventType.SmsReceived; 153 | 154 | /** 155 | * The payload of the event. 156 | */ 157 | payload: { 158 | /** 159 | * The received message. 160 | */ 161 | message: string; 162 | 163 | /** 164 | * The phone number of the sender. 165 | */ 166 | phoneNumber: string; 167 | 168 | /** 169 | * The date and time of when the message was received. 170 | */ 171 | receivedAt: string; 172 | }; 173 | } | 174 | /** 175 | * Represents the payload of a webhook event of type `SystemPing`. 176 | */ 177 | { 178 | /** 179 | * The event type. 180 | */ 181 | event: WebHookEventType.SystemPing; 182 | 183 | /** 184 | * The payload of the event. 185 | * This is an empty object. 186 | */ 187 | payload: EmptyObject; 188 | }; 189 | 190 | type EmptyObject = { 191 | [K in any]: never 192 | } 193 | -------------------------------------------------------------------------------- /src/http.ts: -------------------------------------------------------------------------------- 1 | export interface HttpClient { 2 | get(url: string, headers?: Record): Promise; 3 | post(url: string, body: any, headers?: Record): Promise; 4 | delete(url: string, headers?: Record): Promise; 5 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Client } from "./client"; 2 | export * from "./domain"; 3 | 4 | export default Client; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": [ 4 | "ESNext" 5 | ], 6 | "module": "esnext", 7 | "target": "esnext", 8 | "moduleResolution": "bundler", 9 | "moduleDetection": "force", 10 | "allowImportingTsExtensions": true, 11 | "noEmit": true, 12 | "composite": true, 13 | "strict": true, 14 | "downlevelIteration": true, 15 | "skipLibCheck": true, 16 | "jsx": "react-jsx", 17 | "allowSyntheticDefaultImports": true, 18 | "forceConsistentCasingInFileNames": true, 19 | "allowJs": false, 20 | "types": [ 21 | "bun-types" // add Bun global 22 | ] 23 | } 24 | } --------------------------------------------------------------------------------