fix(mailgun): Normalize package scope and modernize Mailgun client: rename package to @apiclient.xyz/mailgun, update dependencies, refactor HTTP handling, fix types, update TS config and CI, refresh docs and tests

This commit is contained in:
2025-10-13 20:20:24 +00:00
parent 7a66f97700
commit cc62c24e7b
16 changed files with 10930 additions and 13401 deletions

View File

@@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: code.foss.global/host.today/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

7
.gitignore vendored
View File

@@ -3,7 +3,6 @@
# artifacts # artifacts
coverage/ coverage/
public/ public/
pages/
# installs # installs
node_modules/ node_modules/
@@ -17,4 +16,8 @@ node_modules/
dist/ dist/
dist_*/ dist_*/
# custom # AI
.claude/
.serena/
#------# custom

55
changelog.md Normal file
View File

@@ -0,0 +1,55 @@
# Changelog
## 2025-10-13 - 2.0.2 - fix(mailgun)
Normalize package scope and modernize Mailgun client: rename package to @apiclient.xyz/mailgun, update dependencies, refactor HTTP handling, fix types, update TS config and CI, refresh docs and tests
- Rename package and metadata to @apiclient.xyz/mailgun (package.json, npmextra.json, readme and commitinfo)
- Update dependency scopes and versions (@push.rocks packages and dev deps)
- Refactor smartrequest usage to SmartRequest fluent API, replace statusCode/body with status and async json() handling
- Adjust request/form types and attachment handling (FormField shape, filename field, SmartFile usage and Buffer conversion)
- Improve TypeScript configuration (NodeNext moduleResolution, emitDecoratorMetadata, verbatimModuleSyntax) and minor TS fixes in code
- Add Gitea CI workflows (.gitea/workflows) and pnpm workspace config
- Refresh README to reflect new package branding and usage examples
- Fix tests to await env var resolution and format calls, and update .gitignore to include AI artifacts
## 2022-08-07 - 2.0.0 - core
Major release with core updates.
- Core updates and fixes.
- Bumped major version to 2.0.0.
## 2022-08-07 - 1.0.32 - core (BREAKING)
Breaking change: module format change.
- BREAKING CHANGE: switched to ECMAScript modules (ESM). Consumers may need to update import/require usage.
## 2022-08-07 - 1.0.31 - core
Patch release with core fixes.
- Various small core fixes and maintenance updates.
## 2022-08-07 - 1.0.3..1.0.30 - patches
Series of patch releases containing routine fixes and updates.
- Multiple patch releases (1.0.3 through 1.0.30) delivering routine core fixes and minor improvements.
- No documented breaking API changes in these patch releases.
## 2022-08-07 - 2.0.1, 1.0.7, 1.0.2 - tags only
Version tags / metadata-only releases.
- These releases only included version tagging/packaging; no functional changes recorded.
## 2020-01-13 - 1.0.17 - interfaces
Export improvement.
- fix(interfaces): export interfaces so they are available to consumers.
## 2017-02-08 - 1.0.1 - packaging
Packaging fix.
- Fixed npmts error and packaging adjustments.
## 2017-02-08 - 1.0.0 - initial
Initial release.
- Initial commit ("mgun").

View File

@@ -2,17 +2,17 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "mojoio", "gitscope": "apiclient.xyz",
"gitrepo": "mailgun", "gitrepo": "mailgun",
"description": "an api abstraction package for mailgun", "description": "an api abstraction package for mailgun",
"npmPackagename": "@mojoio/mailgun", "npmPackagename": "@apiclient.xyz/mailgun",
"license": "MIT", "license": "MIT",
"projectDomain": "mojo.io" "projectDomain": "apiclient.xyz"
} }
}, },
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
} }
} }

13270
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
{ {
"name": "@mojoio/mailgun", "name": "@apiclient.xyz/mailgun",
"version": "2.0.1", "version": "2.0.1",
"private": false, "private": false,
"description": "an api abstraction package for mailgun", "description": "an api abstraction package for mailgun",
@@ -15,18 +15,18 @@
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.65", "@git.zone/tsbuild": "^2.1.65",
"@gitzone/tstest": "^1.0.73", "@git.zone/tstest": "^2.5.0",
"@pushrocks/qenv": "^5.0.2", "@push.rocks/qenv": "^6.1.3",
"@pushrocks/tapbundle": "^5.0.4", "@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^18.6.4" "@types/node": "^24.7.2"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartfile": "^10.0.4", "@push.rocks/smartfile": "^11.2.7",
"@pushrocks/smartmail": "^1.0.22", "@push.rocks/smartmail": "^2.1.0",
"@pushrocks/smartrequest": "^2.0.10", "@push.rocks/smartrequest": "^4.3.1",
"@pushrocks/smartsmtp": "^3.0.3", "@push.rocks/smartsmtp": "^3.0.3",
"@pushrocks/smartstring": "^4.0.2" "@push.rocks/smartstring": "^4.0.2"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@@ -42,5 +42,17 @@
], ],
"browserslist": [ "browserslist": [
"last 1 chrome versions" "last 1 chrome versions"
] ],
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34",
"repository": {
"type": "git",
"url": "https://gitlab.com/mojoio/mailgun.git"
},
"bugs": {
"url": "https://gitlab.com/mojoio/mailgun/issues"
},
"homepage": "https://gitlab.com/mojoio/mailgun#readme",
"pnpm": {
"overrides": {}
}
} }

10210
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,2 @@
onlyBuiltDependencies:
- esbuild

3
readme.hints.md Normal file
View File

@@ -0,0 +1,3 @@
# Project Readme Hints
This is the initial readme hints file.

370
readme.md
View File

@@ -1,39 +1,351 @@
# @mojoio/mailgun # @apiclient.xyz/mailgun
an api abstraction package for mailgun
## Availabililty and Links > 🚀 A modern, TypeScript-first API wrapper for Mailgun with smart fallback mechanisms
* [npmjs.org (npm package)](https://www.npmjs.com/package/@mojoio/mailgun)
* [gitlab.com (source)](https://gitlab.com/mojoio/mailgun)
* [github.com (source mirror)](https://github.com/mojoio/mailgun)
* [docs (typedoc)](https://mojoio.gitlab.io/mailgun/)
## Status for master Send transactional emails through Mailgun's powerful API with an elegant, type-safe interface. This package seamlessly integrates with the [@push.rocks/smartmail](https://www.npmjs.com/package/@push.rocks/smartmail) ecosystem and provides automatic SMTP fallback for edge cases.
Status Category | Status Badge ## Why @apiclient.xyz/mailgun? 💡
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/mojoio/mailgun/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/mojoio/mailgun/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@mojoio/mailgun)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/mojoio/mailgun)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@mojoio/mailgun)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@mojoio/mailgun)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@mojoio/mailgun)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage - **🎯 TypeScript Native** - Full type safety with excellent IntelliSense support
- **🔄 Smart Fallback** - Automatically falls back to SMTP when API limitations are hit
- **📎 Attachment Support** - Hassle-free file attachments with built-in handling
- **🌍 Multi-Region** - Support for both EU and US Mailgun regions
- **📬 Message Retrieval** - Fetch stored messages from Mailgun's API
- **🔗 Webhook Integration** - Easy integration with Mailgun webhooks
- **⚡ Modern API** - Clean, fluent interface powered by smartrequest v4
Use TypeScript for best in class intellisense. ## Installation
## Contribution ```bash
npm install @apiclient.xyz/mailgun
# or
pnpm install @apiclient.xyz/mailgun
# or
yarn add @apiclient.xyz/mailgun
```
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) ## Quick Start 🚀
For further information read the linked docs at the top of this readme. ```typescript
import { MailgunAccount } from '@apiclient.xyz/mailgun';
import { Smartmail } from '@push.rocks/smartmail';
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) // Initialize your Mailgun account
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) const mailgun = new MailgunAccount({
apiToken: 'your-mailgun-api-token',
region: 'eu' // or 'us'
});
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com) // Create and send an email
const email = new Smartmail({
from: 'Your App <noreply@yourdomain.com>',
subject: 'Welcome to Our Service! 🎉',
body: '<h1>Hello!</h1><p>Thanks for signing up.</p>'
});
await mailgun.sendSmartMail(email, 'user@example.com');
```
## Core Features
### 📧 Sending Emails
The primary way to send emails is through the `sendSmartMail()` method, which accepts a `Smartmail` object:
```typescript
import { MailgunAccount } from '@apiclient.xyz/mailgun';
import { Smartmail } from '@push.rocks/smartmail';
const mailgun = new MailgunAccount({
apiToken: process.env.MAILGUN_API_TOKEN,
region: 'eu'
});
// Create a rich HTML email
const email = new Smartmail({
from: 'Team <hello@yourdomain.com>',
subject: 'Monthly Newsletter',
body: `
<html>
<body>
<h1>What's New This Month</h1>
<p>Check out our latest updates...</p>
</body>
</html>
`
});
// Send to a recipient
await mailgun.sendSmartMail(email, 'subscriber@example.com');
```
### 📎 Email Attachments
Add attachments seamlessly using the smartmail interface:
```typescript
import { SmartFile } from '@push.rocks/smartfile';
const email = new Smartmail({
from: 'Sales <sales@yourdomain.com>',
subject: 'Your Invoice',
body: '<p>Please find your invoice attached.</p>'
});
// Add attachment from file
const pdfFile = await SmartFile.fromFilePath('./invoice.pdf');
email.addAttachment(pdfFile);
await mailgun.sendSmartMail(email, 'customer@example.com');
```
### 🔄 SMTP Fallback
For edge cases where the Mailgun API has limitations (like empty email bodies), the package automatically falls back to SMTP:
```typescript
// Configure SMTP credentials for fallback
// Format: domain|username|password
await mailgun.addSmtpCredentials(
'yourdomain.com|postmaster@yourdomain.com|your-smtp-password'
);
// This email with empty body will automatically use SMTP
const emptyBodyEmail = new Smartmail({
from: 'System <system@yourdomain.com>',
subject: 'System Notification',
body: ''
});
await mailgun.sendSmartMail(emptyBodyEmail, 'admin@example.com');
// ✅ Automatically sent via SMTP instead of API
```
### 📬 Retrieving Messages
Fetch stored messages from Mailgun's API:
```typescript
// Retrieve by message URL (from Mailgun storage)
const message = await mailgun.retrieveSmartMailFromMessageUrl(
'https://sw.api.mailgun.net/v3/domains/yourdomain.com/messages/...'
);
if (message) {
console.log('Subject:', message.options.subject);
console.log('From:', message.options.from);
console.log('Body:', message.options.body);
// Attachments are automatically fetched
console.log('Attachments:', message.attachments.length);
}
```
### 🔔 Webhook Integration
Process Mailgun webhook notifications:
```typescript
// In your webhook handler
app.post('/webhooks/mailgun', async (req, res) => {
const payload = req.body;
// Retrieve the full message from the webhook payload
const message = await mailgun.retrieveSmartMailFromNotifyPayload(payload);
if (message) {
// Process the received email
console.log('Received email:', message.options.subject);
}
res.status(200).send('OK');
});
```
## API Reference
### MailgunAccount
#### Constructor
```typescript
new MailgunAccount(options: {
apiToken: string; // Your Mailgun API token
region: 'eu' | 'us'; // Mailgun region
})
```
#### Methods
##### `sendSmartMail(smartmail, recipient, data?)`
Send an email through Mailgun.
```typescript
await mailgun.sendSmartMail(
smartmailInstance,
'recipient@example.com',
{ customData: 'optional' } // Optional template data
);
```
##### `addSmtpCredentials(credentials)`
Configure SMTP fallback credentials.
```typescript
await mailgun.addSmtpCredentials('domain|username|password');
```
##### `retrieveSmartMailFromMessageUrl(url)`
Retrieve a stored message by its Mailgun URL.
```typescript
const message = await mailgun.retrieveSmartMailFromMessageUrl(messageUrl);
```
##### `retrieveSmartMailFromNotifyPayload(payload)`
Extract and retrieve a message from a Mailgun webhook payload.
```typescript
const message = await mailgun.retrieveSmartMailFromNotifyPayload(webhookPayload);
```
## Region Support 🌍
Mailgun operates in multiple regions. Choose the appropriate one for your needs:
- **`eu`** - European region (GDPR compliant, data stored in EU)
- **`us`** - US region (data stored in US)
```typescript
// EU region
const mailgunEU = new MailgunAccount({
apiToken: 'your-token',
region: 'eu'
});
// US region
const mailgunUS = new MailgunAccount({
apiToken: 'your-token',
region: 'us'
});
```
## Advanced Usage
### Template Variables with Smartmail
Use template variables in your emails:
```typescript
import { Smartmail } from '@push.rocks/smartmail';
const welcomeEmail = new Smartmail({
from: 'Welcome Team <welcome@yourdomain.com>',
subject: 'Welcome {{userName}}!',
body: '<h1>Hi {{userName}}</h1><p>Your account is ready!</p>'
});
// Pass template data
await mailgun.sendSmartMail(
welcomeEmail,
'newuser@example.com',
{ userName: 'John Doe' }
);
```
### Error Handling
```typescript
try {
await mailgun.sendSmartMail(email, 'user@example.com');
console.log('✅ Email sent successfully');
} catch (error) {
console.error('❌ Failed to send email:', error.message);
}
```
### Batch Sending
Send multiple emails efficiently:
```typescript
const recipients = [
'user1@example.com',
'user2@example.com',
'user3@example.com'
];
const email = new Smartmail({
from: 'Newsletter <news@yourdomain.com>',
subject: 'Weekly Update',
body: '<p>Here is your weekly update...</p>'
});
// Send to all recipients
await Promise.all(
recipients.map(recipient =>
mailgun.sendSmartMail(email, recipient)
)
);
```
## TypeScript Support 📘
This package is written in TypeScript and provides full type definitions out of the box:
```typescript
import {
MailgunAccount,
IMailgunAccountContructorOptions,
IMailgunMessage
} from '@apiclient.xyz/mailgun';
// Full IntelliSense support
const options: IMailgunAccountContructorOptions = {
apiToken: 'token',
region: 'eu'
};
const mailgun = new MailgunAccount(options);
```
## Dependencies
This package leverages the powerful @push.rocks ecosystem:
- **[@push.rocks/smartrequest](https://www.npmjs.com/package/@push.rocks/smartrequest)** - Modern HTTP client
- **[@push.rocks/smartmail](https://www.npmjs.com/package/@push.rocks/smartmail)** - Email composition
- **[@push.rocks/smartsmtp](https://www.npmjs.com/package/@push.rocks/smartsmtp)** - SMTP fallback
- **[@push.rocks/smartfile](https://www.npmjs.com/package/@push.rocks/smartfile)** - File handling
- **[@push.rocks/smartstring](https://www.npmjs.com/package/@push.rocks/smartstring)** - String utilities
## Links & Resources
- **📦 [NPM Package](https://www.npmjs.com/package/@apiclient.xyz/mailgun)**
- **💻 [GitLab Repository](https://gitlab.com/apiclient.xyz/mailgun)**
- **🪞 [GitHub Mirror](https://github.com/apiclient-xyz/mailgun)**
- **📚 [TypeDoc Documentation](https://apiclient.xyz/mailgun/docs/)**
- **🌐 [Mailgun API Docs](https://documentation.mailgun.com/)**
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -1,22 +1,22 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@push.rocks/tapbundle';
import { Qenv } from '@pushrocks/qenv'; import { Qenv } from '@push.rocks/qenv';
import * as smartmail from '@pushrocks/smartmail'; import * as smartmail from '@push.rocks/smartmail';
const testQenv = new Qenv('./', './.nogit'); const testQenv = new Qenv('./', './.nogit');
import * as mailgun from '../ts/index.js'; import * as mailgun from '../ts/index.js';
import { IMailgunMessage } from '../ts/index.js'; import { type IMailgunMessage } from '../ts/index.js';
let testMailgunAccount: mailgun.MailgunAccount; let testMailgunAccount: mailgun.MailgunAccount;
let testSmartmail: smartmail.Smartmail<IMailgunMessage>; let testSmartmail: smartmail.Smartmail<IMailgunMessage>;
tap.test('should create a mailgun account', async () => { tap.test('should create a mailgun account', async () => {
testMailgunAccount = new mailgun.MailgunAccount({ testMailgunAccount = new mailgun.MailgunAccount({
apiToken: testQenv.getEnvVarOnDemand('MAILGUN_API_TOKEN'), apiToken: await testQenv.getEnvVarOnDemand('MAILGUN_API_TOKEN'),
region: 'eu', region: 'eu',
}); });
await testMailgunAccount.addSmtpCredentials( await testMailgunAccount.addSmtpCredentials(
testQenv.getEnvVarOnDemand('MAILGUN_SMTP_CREDENTIALS') await testQenv.getEnvVarOnDemand('MAILGUN_SMTP_CREDENTIALS'),
); );
expect(testMailgunAccount).toBeInstanceOf(mailgun.MailgunAccount); expect(testMailgunAccount).toBeInstanceOf(mailgun.MailgunAccount);
}); });
@@ -31,7 +31,10 @@ tap.test('should create a smartmail', async () => {
}); });
tap.test('should send a smartmail', async () => { tap.test('should send a smartmail', async () => {
await testMailgunAccount.sendSmartMail(testSmartmail, 'Sandbox Team <sandbox@mail.git.zone>'); await testMailgunAccount.sendSmartMail(
testSmartmail,
'Sandbox Team <sandbox@mail.git.zone>',
);
}); });
tap.test('should send a smartmail with empty body', async () => { tap.test('should send a smartmail with empty body', async () => {
@@ -42,13 +45,13 @@ tap.test('should send a smartmail with empty body', async () => {
}); });
await testMailgunAccount.sendSmartMail( await testMailgunAccount.sendSmartMail(
emptyBodySmartmail, emptyBodySmartmail,
'Sandbox Team <sandbox@mail.git.zone>' 'Sandbox Team <sandbox@mail.git.zone>',
); );
}); });
tap.test('should retrieve a mail using a retrieval url', async () => { tap.test('should retrieve a mail using a retrieval url', async () => {
const result = await testMailgunAccount.retrieveSmartMailFromMessageUrl( const result = await testMailgunAccount.retrieveSmartMailFromMessageUrl(
'https://sw.api.mailgun.net/v3/domains/mail.lossless.one/messages/AgMFnnnAKC8xp_dDa79LyoxhloxtaVmnRA==' 'https://sw.api.mailgun.net/v3/domains/mail.lossless.one/messages/AgMFnnnAKC8xp_dDa79LyoxhloxtaVmnRA==',
); );
console.log(result); console.log(result);
@@ -56,7 +59,10 @@ tap.test('should retrieve a mail using a retrieval url', async () => {
if (false) { if (false) {
result.options.subject = 'hi there. This is a testmail with attachment'; result.options.subject = 'hi there. This is a testmail with attachment';
result.options.from = 'noreply@mail.lossless.com'; result.options.from = 'noreply@mail.lossless.com';
await testMailgunAccount.sendSmartMail(result, 'Sandbox Team <sandbox@mail.git.zone>'); await testMailgunAccount.sendSmartMail(
result,
'Sandbox Team <sandbox@mail.git.zone>',
);
} }
}); });

View File

@@ -1,8 +1,8 @@
/** /**
* autocreated commitinfo by @pushrocks/commitinfo * autocreated commitinfo by @push.rocks/commitinfo
*/ */
export const commitinfo = { export const commitinfo = {
name: '@mojoio/mailgun', name: '@apiclient.xyz/mailgun',
version: '2.0.1', version: '2.0.2',
description: 'an api abstraction package for mailgun' description: 'an api abstraction package for mailgun'
} }

View File

@@ -45,38 +45,33 @@ export class MailgunAccount {
requestUrl = `${this.apiBaseUrl}${routeArg}`; requestUrl = `${this.apiBaseUrl}${routeArg}`;
} }
console.log(requestUrl); console.log(requestUrl);
const requestOptions: plugins.smartrequest.ISmartRequestOptions = { const response = await plugins.smartrequest.SmartRequest.create()
method: 'GET', .url(requestUrl)
headers: { .headers({
Authorization: `Basic ${plugins.smartstring.base64.encode(`api:${this.options.apiToken}`)}`, Authorization: `Basic ${plugins.smartstring.base64.encode(`api:${this.options.apiToken}`)}`,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, })
keepAlive: false, .options({ keepAlive: false })
}; .get();
let response: plugins.smartrequest.IExtendedIncomingMessage;
if (!binaryArg) {
response = await plugins.smartrequest.request(requestUrl, requestOptions);
} else {
response = await plugins.smartrequest.getBinary(requestUrl, requestOptions);
}
return response; return response;
} }
public async postFormData(routeArg: string, formFields: plugins.smartrequest.IFormField[]) { public async postFormData(
routeArg: string,
formFields: plugins.smartrequest.FormField[],
) {
const requestUrl = `${this.apiBaseUrl}${routeArg}`; const requestUrl = `${this.apiBaseUrl}${routeArg}`;
console.log(requestUrl); console.log(requestUrl);
const response = await plugins.smartrequest.postFormData( const response = await plugins.smartrequest.SmartRequest.create()
requestUrl, .url(requestUrl)
{ .headers({
headers: { Authorization: `Basic ${plugins.smartstring.base64.encode(
Authorization: `Basic ${plugins.smartstring.base64.encode( `api:${this.options.apiToken}`,
`api:${this.options.apiToken}` )}`,
)}`, })
}, .options({ keepAlive: false })
keepAlive: false, .formData(formFields)
}, .post();
formFields
);
return response; return response;
} }
@@ -86,29 +81,25 @@ export class MailgunAccount {
public async sendSmartMail( public async sendSmartMail(
smartmailArg: plugins.smartmail.Smartmail<interfaces.IMailgunMessage>, smartmailArg: plugins.smartmail.Smartmail<interfaces.IMailgunMessage>,
toArg: string, toArg: string,
dataArg = {} dataArg = {},
) { ) {
const domain = smartmailArg.options.from.split('@')[1].replace('>', ''); const domain = smartmailArg.options.from.split('@')[1].replace('>', '');
const formFields: plugins.smartrequest.IFormField[] = [ const formFields: plugins.smartrequest.FormField[] = [
{ {
name: 'from', name: 'from',
type: 'string', value: smartmailArg.options.from,
payload: smartmailArg.options.from,
}, },
{ {
name: 'to', name: 'to',
type: 'string', value: toArg,
payload: toArg,
}, },
{ {
name: 'subject', name: 'subject',
type: 'string', value: smartmailArg.getSubject(dataArg),
payload: smartmailArg.getSubject(dataArg),
}, },
{ {
name: 'html', name: 'html',
type: 'string', value: smartmailArg.getBody(dataArg),
payload: smartmailArg.getBody(dataArg),
}, },
]; ];
@@ -117,29 +108,31 @@ export class MailgunAccount {
for (const attachment of smartmailArg.attachments) { for (const attachment of smartmailArg.attachments) {
formFields.push({ formFields.push({
name: 'attachment', name: 'attachment',
type: 'Buffer', value: attachment.contentBuffer,
payload: attachment.contentBuffer, filename: attachment.parsedPath.base,
fileName: attachment.parsedPath.base,
}); });
} }
if (smartmailArg.getBody(dataArg)) { if (smartmailArg.getBody(dataArg)) {
console.log('All requirements for API met'); console.log('All requirements for API met');
const response = await this.postFormData(`/${domain}/messages`, formFields); const response = await this.postFormData(
if (response.statusCode === 200) { `/${domain}/messages`,
formFields,
);
if (response.status === 200) {
console.log( console.log(
`Sent mail with subject ${smartmailArg.getSubject( `Sent mail with subject ${smartmailArg.getSubject(
dataArg dataArg,
)} to ${toArg} using the mailgun API` )} to ${toArg} using the mailgun API`,
); );
return response.body; return await response.json();
} else { } else {
console.log(response.body); console.log(await response.json());
throw new Error('could not send email'); throw new Error('could not send email');
} }
} else { } else {
console.log( console.log(
'An empty body was provided. This does not work via the API, but using SMTP instead.' 'An empty body was provided. This does not work via the API, but using SMTP instead.',
); );
const wantedSmartsmtp = this.smartSmtps[domain]; const wantedSmartsmtp = this.smartSmtps[domain];
if (!wantedSmartsmtp) { if (!wantedSmartsmtp) {
@@ -149,8 +142,8 @@ export class MailgunAccount {
await wantedSmartsmtp.sendSmartMail(smartmailArg, toArg); await wantedSmartsmtp.sendSmartMail(smartmailArg, toArg);
console.log( console.log(
`Sent mail with subject "${smartmailArg.getSubject( `Sent mail with subject "${smartmailArg.getSubject(
dataArg dataArg,
)}" to "${toArg}" using an smtp transport over Mailgun.` )}" to "${toArg}" using an smtp transport over Mailgun.`,
); );
} }
} }
@@ -158,29 +151,35 @@ export class MailgunAccount {
public async retrieveSmartMailFromMessageUrl(messageUrlArg: string) { public async retrieveSmartMailFromMessageUrl(messageUrlArg: string) {
console.log(`retrieving message for ${messageUrlArg}`); console.log(`retrieving message for ${messageUrlArg}`);
const response = await this.getRequest(messageUrlArg); const response = await this.getRequest(messageUrlArg);
if (response.statusCode === 404) { if (response.status === 404) {
console.log(response.body.message); const body: any = await response.json();
console.log(body.message);
return null; return null;
} }
const responseBody: interfaces.IMailgunMessage = response.body; const responseBody: interfaces.IMailgunMessage = await response.json();
const smartmail = new plugins.smartmail.Smartmail<interfaces.IMailgunMessage>({ const smartmail =
from: responseBody.From, new plugins.smartmail.Smartmail<interfaces.IMailgunMessage>({
body: responseBody['body-html'], from: responseBody.From,
subject: responseBody.Subject, body: responseBody['body-html'],
creationObjectRef: responseBody, subject: responseBody.Subject,
}); creationObjectRef: responseBody,
});
// lets care about attachments // lets care about attachments
if (responseBody.attachments && responseBody.attachments instanceof Array) { if (responseBody.attachments && responseBody.attachments instanceof Array) {
for (const attachmentInfo of responseBody.attachments) { for (const attachmentInfo of responseBody.attachments) {
const attachmentName = attachmentInfo.name; const attachmentName = attachmentInfo.name;
const attachmentContents = await this.getRequest(attachmentInfo.url, true); const attachmentContents = await this.getRequest(
attachmentInfo.url,
true,
);
const arrayBuffer = await attachmentContents.arrayBuffer();
smartmail.addAttachment( smartmail.addAttachment(
new plugins.smartfile.Smartfile({ new plugins.smartfile.SmartFile({
path: `./${attachmentName}`, path: `./${attachmentName}`,
base: `./${attachmentName}`, base: `./${attachmentName}`,
contentBuffer: attachmentContents.body, contentBuffer: Buffer.from(arrayBuffer),
}) }),
); );
} }
} }
@@ -189,6 +188,8 @@ export class MailgunAccount {
} }
public async retrieveSmartMailFromNotifyPayload(notifyPayloadArg: any) { public async retrieveSmartMailFromNotifyPayload(notifyPayloadArg: any) {
return await this.retrieveSmartMailFromMessageUrl(notifyPayloadArg['message-url']); return await this.retrieveSmartMailFromMessageUrl(
notifyPayloadArg['message-url'],
);
} }
} }

View File

@@ -1,8 +1,8 @@
// @pushrocks scope // @pushrocks scope
import * as smartfile from '@pushrocks/smartfile'; import * as smartfile from '@push.rocks/smartfile';
import * as smartmail from '@pushrocks/smartmail'; import * as smartmail from '@push.rocks/smartmail';
import * as smartrequest from '@pushrocks/smartrequest'; import * as smartrequest from '@push.rocks/smartrequest';
import * as smartsmtp from '@pushrocks/smartsmtp'; import * as smartsmtp from '@push.rocks/smartsmtp';
import * as smartstring from '@pushrocks/smartstring'; import * as smartstring from '@push.rocks/smartstring';
export { smartfile, smartmail, smartrequest, smartsmtp, smartstring }; export { smartfile, smartmail, smartrequest, smartsmtp, smartstring };

View File

@@ -1,10 +1,15 @@
{ {
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true, "experimentalDecorators": true,
"emitDecoratorMetadata": true,
"useDefineForClassFields": false, "useDefineForClassFields": false,
"target": "ES2022", "target": "ES2022",
"module": "ES2022", "module": "NodeNext",
"moduleResolution": "nodenext", "moduleResolution": "NodeNext",
"esModuleInterop": true "esModuleInterop": true,
} "verbatimModuleSyntax": true,
"baseUrl": ".",
"paths": {}
},
"exclude": ["dist_*/**/*.d.ts"]
} }