@tylix/mail 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.d.ts +34 -0
  2. package/package.json +32 -6
  3. package/SmtpClient.js +0 -249
package/index.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { Model } from '@tylix/orm'
2
+
3
+ export interface MailContent {
4
+ subject: string
5
+ view: string
6
+ data?: Record<string, unknown>
7
+ }
8
+
9
+ export interface MailConfig {
10
+ driver?: 'smtp' | 'log'
11
+ host?: string
12
+ port?: number
13
+ user?: string
14
+ password?: string
15
+ from?: string
16
+ [key: string]: unknown
17
+ }
18
+
19
+ export abstract class Mailable {
20
+ abstract build(): MailContent
21
+ send(to: string, config?: MailConfig): Promise<unknown>
22
+ }
23
+
24
+ export class MailLog extends Model {
25
+ id: number
26
+ recipient: string
27
+ subject: string
28
+ body: string
29
+ created_at?: string
30
+ }
31
+
32
+ export const Mail: {
33
+ send(to: string, mailable: Mailable, config?: MailConfig): Promise<unknown>
34
+ }
package/package.json CHANGED
@@ -1,12 +1,38 @@
1
1
  {
2
2
  "name": "@tylix/mail",
3
- "version": "0.3.5",
3
+ "version": "0.4.0",
4
+ "description": "Mail system for Tylix: Mailables, SMTP and log drivers, and mail logging",
4
5
  "type": "module",
5
- "keywords": ["tylix", "mail", "email", "smtp", "sendgrid"],
6
+ "keywords": [
7
+ "tylix",
8
+ "mail",
9
+ "email",
10
+ "smtp"
11
+ ],
6
12
  "main": "index.js",
13
+ "types": "index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./index.d.ts",
17
+ "import": "./index.js",
18
+ "default": "./index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "index.js",
23
+ "index.d.ts",
24
+ "Mailer.js",
25
+ "Mailable.js",
26
+ "models",
27
+ "drivers"
28
+ ],
7
29
  "dependencies": {
8
- "@tylix/shared": "^0.3.5",
9
- "@tylix/orm": "^0.3.5",
10
- "@tylix/generator": "^0.3.5"
30
+ "@tylix/shared": "^0.4.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@tylix/orm": "^0.4.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
11
37
  }
12
- }
38
+ }
package/SmtpClient.js DELETED
@@ -1,249 +0,0 @@
1
- import net from 'node:net'
2
- import tls from 'node:tls'
3
-
4
- const DEFAULT_TIMEOUT_MS = 10_000
5
-
6
- /**
7
- * Buffers raw socket bytes and yields complete SMTP responses.
8
- * A single response can span multiple `data` events (partial line),
9
- * and can itself be multi-line (continuation lines use "250-", the
10
- * final line uses "250 "). This waits for both conditions before
11
- * resolving.
12
- */
13
- class SmtpResponseReader {
14
- constructor(socket) {
15
- this.socket = socket
16
- this.buffer = ''
17
- this.pending = []
18
- this.onData = (chunk) => {
19
- this.buffer += chunk.toString('utf-8')
20
- this.flush()
21
- }
22
- this.onError = (err) => {
23
- this.rejectAll(err)
24
- }
25
- socket.on('data', this.onData)
26
- socket.on('error', this.onError)
27
- }
28
-
29
- flush() {
30
- while (true) {
31
- const lines = this.buffer.split('\r\n')
32
- // Keep the last (possibly incomplete) fragment in the buffer.
33
- const complete = lines.slice(0, -1)
34
- if (complete.length === 0) return
35
-
36
- // Find the first fully-formed response: consecutive lines
37
- // sharing a 3-digit code, where "CODE-" continues and "CODE "
38
- // ends the response.
39
- let consumedLines = 0
40
- let done = false
41
- for (const line of complete) {
42
- consumedLines++
43
- if (/^\d{3} /.test(line)) {
44
- done = true
45
- break
46
- }
47
- if (!/^\d{3}-/.test(line)) {
48
- // Malformed line — bail and let the caller see the raw text.
49
- done = true
50
- break
51
- }
52
- }
53
-
54
- if (!done) return // waiting for more data to complete this response
55
-
56
- const responseLines = complete.slice(0, consumedLines)
57
- this.buffer = [...complete.slice(consumedLines), lines.at(-1)].join(
58
- '\r\n',
59
- )
60
-
61
- const waiter = this.pending.shift()
62
- if (waiter) waiter.resolve(responseLines.join('\r\n'))
63
- if (this.pending.length === 0) return
64
- }
65
- }
66
-
67
- read(timeoutMs = DEFAULT_TIMEOUT_MS) {
68
- return new Promise((resolve, reject) => {
69
- const timer = setTimeout(() => {
70
- const idx = this.pending.indexOf(entry)
71
- if (idx !== -1) this.pending.splice(idx, 1)
72
- reject(new Error(`SMTP response timed out after ${timeoutMs}ms`))
73
- }, timeoutMs)
74
-
75
- const entry = {
76
- resolve: (line) => {
77
- clearTimeout(timer)
78
- resolve(line)
79
- },
80
- reject,
81
- }
82
- this.pending.push(entry)
83
- this.flush()
84
- })
85
- }
86
-
87
- rejectAll(err) {
88
- for (const waiter of this.pending) waiter.reject(err)
89
- this.pending = []
90
- }
91
-
92
- detach() {
93
- this.socket.off('data', this.onData)
94
- this.socket.off('error', this.onError)
95
- }
96
- }
97
-
98
- function writeCommand(socket, command) {
99
- socket.write(`${command}\r\n`)
100
- }
101
-
102
- function checkCode(response, expected) {
103
- const code = Number(response.slice(0, 3))
104
- if (!expected.includes(code)) {
105
- throw new Error(
106
- `SMTP error: expected ${expected.join('/')}, got: ${response.trim()}`,
107
- )
108
- }
109
- return response
110
- }
111
-
112
- function connectSocket(options, timeoutMs) {
113
- return new Promise((resolve, reject) => {
114
- const socket = options.secure
115
- ? tls.connect({ host: options.host, port: options.port })
116
- : net.connect({ host: options.host, port: options.port })
117
-
118
- const timer = setTimeout(() => {
119
- socket.destroy()
120
- reject(
121
- new Error(`Connection to ${options.host}:${options.port} timed out`),
122
- )
123
- }, timeoutMs)
124
-
125
- socket.once('connect', () => {
126
- clearTimeout(timer)
127
- resolve(socket)
128
- })
129
- socket.once('secureConnect', () => {
130
- clearTimeout(timer)
131
- resolve(socket)
132
- })
133
- socket.once('error', (err) => {
134
- clearTimeout(timer)
135
- reject(err)
136
- })
137
- })
138
- }
139
-
140
- export class SmtpClient {
141
- constructor({
142
- host,
143
- port,
144
- secure = false,
145
- user,
146
- password,
147
- timeoutMs = DEFAULT_TIMEOUT_MS,
148
- }) {
149
- this.host = host
150
- this.port = port
151
- this.secure = secure
152
- this.user = user
153
- this.password = password
154
- this.timeoutMs = timeoutMs
155
- }
156
-
157
- async connect() {
158
- this.socket = await connectSocket(
159
- { host: this.host, port: this.port, secure: this.secure },
160
- this.timeoutMs,
161
- )
162
- this.reader = new SmtpResponseReader(this.socket)
163
-
164
- checkCode(await this.reader.read(this.timeoutMs), [220])
165
- writeCommand(this.socket, `EHLO ${this.host}`)
166
- checkCode(await this.reader.read(this.timeoutMs), [250])
167
-
168
- if (!this.secure && this.port === 587) {
169
- writeCommand(this.socket, 'STARTTLS')
170
- checkCode(await this.reader.read(this.timeoutMs), [220])
171
-
172
- this.reader.detach()
173
- this.socket = await new Promise((resolve, reject) => {
174
- const tlsSocket = tls.connect({ socket: this.socket })
175
- const timer = setTimeout(() => {
176
- tlsSocket.destroy()
177
- reject(new Error('STARTTLS upgrade timed out'))
178
- }, this.timeoutMs)
179
- tlsSocket.once('secureConnect', () => {
180
- clearTimeout(timer)
181
- resolve(tlsSocket)
182
- })
183
- tlsSocket.once('error', (err) => {
184
- clearTimeout(timer)
185
- reject(err)
186
- })
187
- })
188
- this.reader = new SmtpResponseReader(this.socket)
189
-
190
- writeCommand(this.socket, `EHLO ${this.host}`)
191
- checkCode(await this.reader.read(this.timeoutMs), [250])
192
- }
193
-
194
- if (this.user && this.password) {
195
- writeCommand(this.socket, 'AUTH LOGIN')
196
- checkCode(await this.reader.read(this.timeoutMs), [334])
197
- writeCommand(this.socket, Buffer.from(this.user).toString('base64'))
198
- checkCode(await this.reader.read(this.timeoutMs), [334])
199
- writeCommand(this.socket, Buffer.from(this.password).toString('base64'))
200
- checkCode(await this.reader.read(this.timeoutMs), [235])
201
- }
202
- }
203
-
204
- async send({ from, to, subject, html, text }) {
205
- try {
206
- await this.connect()
207
-
208
- writeCommand(this.socket, `MAIL FROM:<${from}>`)
209
- checkCode(await this.reader.read(this.timeoutMs), [250])
210
-
211
- const recipients = Array.isArray(to) ? to : [to]
212
- for (const recipient of recipients) {
213
- writeCommand(this.socket, `RCPT TO:<${recipient}>`)
214
- checkCode(await this.reader.read(this.timeoutMs), [250, 251])
215
- }
216
-
217
- writeCommand(this.socket, 'DATA')
218
- checkCode(await this.reader.read(this.timeoutMs), [354])
219
-
220
- const boundary = `tylix-${Date.now()}-${Math.random().toString(36).slice(2)}`
221
- const body = [
222
- `From: ${from}`,
223
- `To: ${recipients.join(', ')}`,
224
- `Subject: ${subject}`,
225
- 'MIME-Version: 1.0',
226
- `Content-Type: multipart/alternative; boundary="${boundary}"`,
227
- '',
228
- `--${boundary}`,
229
- 'Content-Type: text/plain; charset=utf-8',
230
- '',
231
- (text || '').replace(/^\./gm, '..'), // dot-stuffing per RFC 5321
232
- `--${boundary}`,
233
- 'Content-Type: text/html; charset=utf-8',
234
- '',
235
- (html || '').replace(/^\./gm, '..'),
236
- `--${boundary}--`,
237
- '.',
238
- ].join('\r\n')
239
-
240
- writeCommand(this.socket, body)
241
- checkCode(await this.reader.read(this.timeoutMs), [250])
242
-
243
- writeCommand(this.socket, 'QUIT')
244
- } finally {
245
- this.reader?.detach()
246
- this.socket?.end()
247
- }
248
- }
249
- }