@yaks/mail 0.0.0-stage → 0.2.36

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 (131) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +676 -2
  3. package/_dist/addr.d.ts +40 -0
  4. package/_dist/addr.d.ts.map +1 -0
  5. package/_dist/answers.d.ts +18 -0
  6. package/_dist/answers.d.ts.map +1 -0
  7. package/_dist/arrive.d.ts +64 -0
  8. package/_dist/arrive.d.ts.map +1 -0
  9. package/_dist/capture.d.ts +22 -0
  10. package/_dist/capture.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +27 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/effects.d.ts +9 -0
  14. package/_dist/effects.d.ts.map +1 -0
  15. package/_dist/gmail.d.ts +16 -0
  16. package/_dist/gmail.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +9 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/inbound.d.ts +105 -0
  20. package/_dist/inbound.d.ts.map +1 -0
  21. package/_dist/invite.d.ts +69 -0
  22. package/_dist/invite.d.ts.map +1 -0
  23. package/_dist/md.d.ts +34 -0
  24. package/_dist/md.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +109 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/options.d.ts +38 -0
  28. package/_dist/options.d.ts.map +1 -0
  29. package/_dist/plugin.d.ts +38 -0
  30. package/_dist/plugin.d.ts.map +1 -0
  31. package/_dist/pull.d.ts +99 -0
  32. package/_dist/pull.d.ts.map +1 -0
  33. package/_dist/receipts.d.ts +8 -0
  34. package/_dist/receipts.d.ts.map +1 -0
  35. package/_dist/recipient.d.ts +24 -0
  36. package/_dist/recipient.d.ts.map +1 -0
  37. package/_dist/routes.d.ts +19 -0
  38. package/_dist/routes.d.ts.map +1 -0
  39. package/_dist/send.d.ts +80 -0
  40. package/_dist/send.d.ts.map +1 -0
  41. package/_dist/service.d.ts +14 -0
  42. package/_dist/service.d.ts.map +1 -0
  43. package/_dist/stash.d.ts +23 -0
  44. package/_dist/stash.d.ts.map +1 -0
  45. package/_dist/tools.d.ts +27 -0
  46. package/_dist/tools.d.ts.map +1 -0
  47. package/_dist/transport.d.ts +6 -0
  48. package/_dist/transport.d.ts.map +1 -0
  49. package/_dist/vocab.d.ts +7 -0
  50. package/_dist/vocab.d.ts.map +1 -0
  51. package/addr.js +92 -0
  52. package/addr.js.map +1 -0
  53. package/addr.ts +106 -0
  54. package/answers.js +71 -0
  55. package/answers.js.map +1 -0
  56. package/answers.ts +95 -0
  57. package/arrive.js +122 -0
  58. package/arrive.js.map +1 -0
  59. package/arrive.ts +198 -0
  60. package/capture.js +21 -0
  61. package/capture.js.map +1 -0
  62. package/capture.ts +43 -0
  63. package/comp.js +76 -0
  64. package/comp.js.map +1 -0
  65. package/comp.ts +91 -0
  66. package/deno.json +1 -0
  67. package/effects.js +90 -0
  68. package/effects.js.map +1 -0
  69. package/effects.ts +90 -0
  70. package/gmail.js +262 -0
  71. package/gmail.js.map +1 -0
  72. package/gmail.ts +314 -0
  73. package/graph.js +26 -0
  74. package/graph.js.map +1 -0
  75. package/graph.ts +30 -0
  76. package/inbound.js +206 -0
  77. package/inbound.js.map +1 -0
  78. package/inbound.ts +238 -0
  79. package/invite.js +102 -0
  80. package/invite.js.map +1 -0
  81. package/invite.ts +143 -0
  82. package/md.js +188 -0
  83. package/md.js.map +1 -0
  84. package/md.ts +245 -0
  85. package/mod.js +109 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +111 -0
  88. package/options.js +24 -0
  89. package/options.js.map +1 -0
  90. package/options.ts +83 -0
  91. package/package.json +66 -4
  92. package/plugin.js +97 -0
  93. package/plugin.js.map +1 -0
  94. package/plugin.ts +88 -0
  95. package/pull.js +344 -0
  96. package/pull.js.map +1 -0
  97. package/pull.ts +443 -0
  98. package/readings.js +24 -0
  99. package/readings.js.map +1 -0
  100. package/readings.ts +34 -0
  101. package/receipts.js +45 -0
  102. package/receipts.js.map +1 -0
  103. package/receipts.ts +45 -0
  104. package/recipient.js +92 -0
  105. package/recipient.js.map +1 -0
  106. package/recipient.ts +89 -0
  107. package/routes.js +103 -0
  108. package/routes.js.map +1 -0
  109. package/routes.ts +125 -0
  110. package/send.js +284 -0
  111. package/send.js.map +1 -0
  112. package/send.ts +325 -0
  113. package/service.js +64 -0
  114. package/service.js.map +1 -0
  115. package/service.ts +75 -0
  116. package/stash.js +29 -0
  117. package/stash.js.map +1 -0
  118. package/stash.ts +49 -0
  119. package/tools.js +343 -0
  120. package/tools.js.map +1 -0
  121. package/tools.ts +416 -0
  122. package/transport.js +23 -0
  123. package/transport.js.map +1 -0
  124. package/transport.ts +24 -0
  125. package/vocab.js +14 -0
  126. package/vocab.js.map +1 -0
  127. package/vocab.json +415 -0
  128. package/vocab.ts +16 -0
  129. package/work.js +121 -0
  130. package/work.js.map +1 -0
  131. package/work.ts +134 -0
package/gmail.ts ADDED
@@ -0,0 +1,314 @@
1
+ import PostalMime from 'postal-mime'
2
+ import { fromBase64url, toBase64, toBase64url } from '@yaks/fp'
3
+ import {
4
+ type Incoming,
5
+ type Message,
6
+ type Sender,
7
+ Undeliverable,
8
+ Unsent,
9
+ } from '@yaks/host/senders'
10
+
11
+ export let GMAIL_MAILBOX = 'gmail-mailbox'
12
+
13
+ let API = 'https://gmail.googleapis.com/gmail/v1/users/me'
14
+ let utf8 = (text: string) => new TextEncoder().encode(text)
15
+ let encoded = (text: string) => toBase64(utf8(text))
16
+ let body = (text: string) => encoded(text).replace(/.{76}/g, '$&\r\n')
17
+ let line = (text: string) => text.replace(/[\r\n]+/g, ' ').trim()
18
+ let word = (text: string) =>
19
+ /^[\x20-\x7e]*$/.test(text) ? text : `=?UTF-8?B?${encoded(text)}?=`
20
+ let address = (text: string) => text.trim().toLowerCase()
21
+
22
+ /** The raw MIME Gmail sends, including the headers used to thread replies. */
23
+ export let gmailLetter = (m: Message, id?: string): string => {
24
+ let boundary = 'yak-' + crypto.randomUUID()
25
+ let who = m.name ? `${word(line(m.name))} <${line(m.from)}>` : line(m.from)
26
+ if (m.name && /^[\x20-\x7e]*$/.test(line(m.name))) {
27
+ who = `"${line(m.name).replace(/["\\]/g, '\\$&')}" <${line(m.from)}>`
28
+ }
29
+ let headers = [
30
+ `From: ${who}`,
31
+ `To: ${[m.to].flat().map(line).join(', ')}`,
32
+ ...(m.cc ? [`Cc: ${line(m.cc)}`] : []),
33
+ `Subject: ${word(line(m.subject))}`,
34
+ ...(id ? [`Message-ID: <${id}>`] : []),
35
+ ...(m.replyAddress ? [`Reply-To: ${line(m.replyAddress)}`] : []),
36
+ ...(m.replyTo
37
+ ? [
38
+ `In-Reply-To: <${line(m.replyTo)}>`,
39
+ `References: <${line(m.replyTo)}>`,
40
+ ]
41
+ : []),
42
+ 'MIME-Version: 1.0',
43
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
44
+ ]
45
+ let part = (type: string, text: string) => [
46
+ `--${boundary}`,
47
+ `Content-Type: text/${type}; charset=UTF-8`,
48
+ 'Content-Transfer-Encoding: base64',
49
+ '',
50
+ body(text),
51
+ ]
52
+ return toBase64url(utf8([
53
+ ...headers,
54
+ '',
55
+ ...part('plain', m.text),
56
+ ...part('html', m.html),
57
+ `--${boundary}--`,
58
+ '',
59
+ ].join('\r\n')))
60
+ }
61
+
62
+ type Call = (req: Request) => Promise<Response>
63
+
64
+ class GmailError extends Error {
65
+ constructor(readonly operation: string, readonly status: number) {
66
+ super(`Gmail ${operation} returned ${status}`)
67
+ }
68
+ }
69
+
70
+ let ask = async <T>(
71
+ call: Call,
72
+ path: string,
73
+ query: Record<string, string> = {},
74
+ data?: object,
75
+ ): Promise<T> => {
76
+ let at = new URL(API + path)
77
+ at.search = new URLSearchParams(query).toString()
78
+ let res = await call(
79
+ new Request(
80
+ at,
81
+ data
82
+ ? {
83
+ method: 'POST',
84
+ headers: { 'content-type': 'application/json' },
85
+ body: JSON.stringify(data),
86
+ }
87
+ : undefined,
88
+ ),
89
+ )
90
+ if (!res.ok) {
91
+ await res.body?.cancel()
92
+ throw new GmailError(
93
+ path.replace(/\/messages\/[^/]+$/, '/messages/:id'),
94
+ res.status,
95
+ )
96
+ }
97
+ return await res.json() as T
98
+ }
99
+
100
+ let gone = (error: unknown) =>
101
+ error instanceof GmailError && error.status == 404
102
+
103
+ /** The mailbox identity and the Gmail history position from which new mail starts. */
104
+ export let gmailProfile = async (
105
+ call: Call,
106
+ expected: string,
107
+ ): Promise<string> => {
108
+ let { emailAddress, historyId } = await ask<{
109
+ emailAddress?: string
110
+ historyId?: string
111
+ }>(call, '/profile')
112
+ if (address(emailAddress ?? '') != address(expected) || !historyId) {
113
+ throw new Error('Gmail returned a different mailbox or no history position')
114
+ }
115
+ return historyId
116
+ }
117
+
118
+ type SendAs = {
119
+ sendAsEmail: string
120
+ isPrimary?: boolean
121
+ verificationStatus?: string
122
+ }
123
+
124
+ /** Gmail's accepted addresses, after checking that this is the selected account. */
125
+ export let gmailAddresses = async (
126
+ call: Call,
127
+ expected: string,
128
+ ): Promise<Set<string>> => {
129
+ let { sendAs = [] } = await ask<{ sendAs?: SendAs[] }>(
130
+ call,
131
+ '/settings/sendAs',
132
+ )
133
+ let primary = sendAs.find((one) => one.isPrimary)
134
+ if (address(primary?.sendAsEmail ?? '') != address(expected)) {
135
+ throw new Error('Gmail returned a different sending account')
136
+ }
137
+ return new Set(
138
+ sendAs
139
+ .filter((one) => one.isPrimary || one.verificationStatus == 'accepted')
140
+ .map((one) => address(one.sendAsEmail)),
141
+ )
142
+ }
143
+
144
+ export let gmailSender = (call: Call, expected: string): Sender => ({
145
+ send: async (message) => {
146
+ let from = address(message.from)
147
+ let allowed = await gmailAddresses(call, expected).catch((error) => {
148
+ throw new Unsent(
149
+ error instanceof Error
150
+ ? error.message
151
+ : 'Could not check Gmail aliases',
152
+ 60_000,
153
+ )
154
+ })
155
+ if (!allowed.has(from)) {
156
+ throw new Undeliverable(
157
+ `${from} is not a verified Gmail Send mail as address`,
158
+ )
159
+ }
160
+ let id = `${message.id ?? crypto.randomUUID()}@${expected.split('@')[1]}`
161
+ try {
162
+ await ask(call, '/messages/send', {}, { raw: gmailLetter(message, id) })
163
+ } catch (error) {
164
+ if (error instanceof GmailError && error.status == 429) {
165
+ throw new Unsent('Gmail is limiting sends', 60_000)
166
+ }
167
+ throw error
168
+ }
169
+ return { id }
170
+ },
171
+ })
172
+
173
+ type MessageKey = { id: string }
174
+ type History = {
175
+ historyId: string
176
+ history?: { messagesAdded?: { message: MessageKey }[] }[]
177
+ nextPageToken?: string
178
+ }
179
+ type Listing = { messages?: MessageKey[]; nextPageToken?: string }
180
+ type Unread = { internalDate?: string; labelIds?: string[]; raw?: string }
181
+ let excluded = new Set(['SENT', 'DRAFT', 'SPAM', 'TRASH', 'CHAT'])
182
+
183
+ let incoming = async (
184
+ encoded: string,
185
+ addresses: Set<string>,
186
+ primary: string,
187
+ ): Promise<Incoming | undefined> => {
188
+ let raw = fromBase64url(encoded)
189
+ let mail = await PostalMime.parse(raw)
190
+ if (!mail.from?.address) return
191
+ let headers = new Map(mail.headers.map(({ key, value }) => [key, value]))
192
+ let recipients = [...mail.to ?? [], ...mail.cc ?? []].flatMap((one) =>
193
+ 'group' in one ? one.group ?? [] : [one]
194
+ )
195
+ let to = [
196
+ ...recipients.map((one) => one.address ?? ''),
197
+ headers.get('x-original-to') ?? '',
198
+ headers.get('delivered-to') ?? '',
199
+ ].map(address).find((one) => one != primary && addresses.has(one)) ?? primary
200
+ if (mail.subject != null) headers.set('subject', mail.subject)
201
+ if (mail.messageId) headers.set('message-id', mail.messageId)
202
+ return {
203
+ from: mail.from.address,
204
+ name: mail.from.name,
205
+ to,
206
+ headers: {
207
+ get: (name) => headers.get(name.toLowerCase()) ?? null,
208
+ entries: () => headers.entries(),
209
+ },
210
+ text: mail.text ?? '',
211
+ html: mail.html,
212
+ attachments: mail.attachments.map((file) => ({
213
+ name: file.filename ?? '',
214
+ type: file.mimeType || 'application/octet-stream',
215
+ bytes: typeof file.content == 'string'
216
+ ? utf8(file.content)
217
+ : new Uint8Array(file.content),
218
+ })),
219
+ sources: [{
220
+ name: 'message.eml',
221
+ type: 'message/rfc822',
222
+ bytes: new Uint8Array(raw),
223
+ }],
224
+ }
225
+ }
226
+
227
+ /** The activation time is the lower bound even if Gmail expires a history ID. */
228
+ export type GmailCursor = { history: string; since: string; through: string }
229
+ export let gmailStart = async (
230
+ call: Call,
231
+ primary: string,
232
+ started: string,
233
+ ): Promise<GmailCursor> => ({
234
+ history: await gmailProfile(call, primary),
235
+ since: started,
236
+ through: started,
237
+ })
238
+
239
+ /** A poll reads message content only after Gmail's delivery time and labels
240
+ * have been checked. Advance the cursor only once every arrival is filed. */
241
+ export let gmailPoll = async (
242
+ call: Call,
243
+ primary: string,
244
+ cursor: GmailCursor,
245
+ started: string,
246
+ file: (id: string, mail: Incoming) => Promise<unknown>,
247
+ ): Promise<GmailCursor> => {
248
+ let seen = new Set<string>()
249
+ let since = Date.parse(cursor.since)
250
+ let addresses: Promise<Set<string>> | undefined
251
+ let receive = async ({ id }: MessageKey) => {
252
+ if (seen.has(id)) return
253
+ seen.add(id)
254
+ let path = '/messages/' + encodeURIComponent(id)
255
+ let get = (query: Record<string, string>) =>
256
+ ask<Unread>(call, path, query)
257
+ .catch((error) => gone(error) ? undefined : Promise.reject(error))
258
+ let meta = await get({ format: 'full', fields: 'internalDate,labelIds' })
259
+ if (!meta || meta.labelIds?.some((label) => excluded.has(label))) return
260
+ let at = Number(meta.internalDate)
261
+ if (!meta.internalDate || !Number.isFinite(at)) {
262
+ throw new Error('Gmail returned no message delivery time')
263
+ }
264
+ if (at < since) return
265
+ addresses ??= gmailAddresses(call, primary)
266
+ let verified = await addresses
267
+ let full = await get({ format: 'raw', fields: 'raw' })
268
+ if (full && !full.raw) throw new Error('Gmail returned no message content')
269
+ let mail = full?.raw && await incoming(full.raw, verified, primary)
270
+ if (mail) await file(id, mail)
271
+ }
272
+ let page = ''
273
+ try {
274
+ do {
275
+ let history = await ask<History>(call, '/history', {
276
+ startHistoryId: cursor.history,
277
+ historyTypes: 'messageAdded',
278
+ maxResults: '100',
279
+ ...(page ? { pageToken: page } : {}),
280
+ })
281
+ for (let event of history.history ?? []) {
282
+ for (let { message } of event.messagesAdded ?? []) {
283
+ await receive(message)
284
+ }
285
+ }
286
+ page = history.nextPageToken ?? ''
287
+ if (!page) {
288
+ if (!history.historyId) {
289
+ throw new Error('Gmail returned no history position')
290
+ }
291
+ return { ...cursor, history: history.historyId, through: started }
292
+ }
293
+ } while (page)
294
+ } catch (error) {
295
+ if (!(gone(error) && (error as GmailError).operation == '/history')) {
296
+ throw error
297
+ }
298
+ }
299
+ // Capture the replacement position before the search, so a delivery during
300
+ // the search is considered by the next history poll.
301
+ let history = await gmailProfile(call, primary)
302
+ let after = Math.floor(Date.parse(cursor.through) / 1000) - 1
303
+ page = ''
304
+ do {
305
+ let listing = await ask<Listing>(call, '/messages', {
306
+ q: `after:${after}`,
307
+ maxResults: '100',
308
+ ...(page ? { pageToken: page } : {}),
309
+ })
310
+ for (let message of listing.messages ?? []) await receive(message)
311
+ page = listing.nextPageToken ?? ''
312
+ } while (page)
313
+ return { ...cursor, history, through: started }
314
+ }
package/graph.js ADDED
@@ -0,0 +1,26 @@
1
+ // The write-time half: the `@yaks/mail/graph` entry point — the components
2
+ // and, where the config names a domain, the canonicalizer that normalizes an
3
+ // address on the way in.
4
+ //
5
+ // The domain is this plugin's option rather than a server-wide setting: which
6
+ // domain an address belongs to is a fact about this plugin, and a server that
7
+ // composes two mailboxes would otherwise have one domain between them.
8
+ //
9
+ // The outbound half is `./effects`, which needs the sender the config names.
10
+ import { mailbox } from "./plugin.js";
11
+ import { recipients } from "./recipient.js";
12
+ /** The letter components, the address canonicalizer the domain implies, and
13
+ * the mark that keeps an address only a letter names with the letters, where
14
+ * the store speaks the words it is written in. */ export let plugins = ({ vocab }, options = {})=>[
15
+ mailbox({
16
+ domain: options.domain
17
+ }),
18
+ ...[
19
+ 'email',
20
+ 'deliver',
21
+ 'recipient'
22
+ ].every((n)=>vocab.comp(n)?.namespace?.label == '@yaks/mail') ? [
23
+ recipients()
24
+ ] : []
25
+ ];
26
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,yBAAyB;AACzB,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,uEAAuE;AACvE,EAAE;AACF,6EAA6E;AAI7E,SAAS,OAAO,sBAAqB;AACrC,SAAS,UAAU,yBAAwB;AAG3C;;gDAEgD,GAChD,OAAO,IAAI,UAAU,CACnB,EAAE,KAAK,EAAoB,EAC3B,UAAmB,CAAC,CAAC,GACR;IACb,QAAQ;MAAE,QAAQ,QAAQ,MAAM;IAAC;OAC9B;MAAC;MAAS;MAAW;KAAY,CAAC,KAAK,CAAC,CAAC,IACxC,MAAM,IAAI,CAAC,IAAI,WAAW,SAAS,gBAEnC;MAAC;KAAa,GACd,EAAE;GACP,CAAA"}
package/graph.ts ADDED
@@ -0,0 +1,30 @@
1
+ // The write-time half: the `@yaks/mail/graph` entry point — the components
2
+ // and, where the config names a domain, the canonicalizer that normalizes an
3
+ // address on the way in.
4
+ //
5
+ // The domain is this plugin's option rather than a server-wide setting: which
6
+ // domain an address belongs to is a fact about this plugin, and a server that
7
+ // composes two mailboxes would otherwise have one domain between them.
8
+ //
9
+ // The outbound half is `./effects`, which needs the sender the config names.
10
+
11
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
12
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
13
+ import { mailbox } from './plugin.js'
14
+ import { recipients } from './recipient.js'
15
+ import type { Options } from './options.ts'
16
+
17
+ /** The letter components, the address canonicalizer the domain implies, and
18
+ * the mark that keeps an address only a letter names with the letters, where
19
+ * the store speaks the words it is written in. */
20
+ export let plugins = (
21
+ { vocab }: { vocab: Vocab },
22
+ options: Options = {},
23
+ ): Plugin[] => [
24
+ mailbox({ domain: options.domain }),
25
+ ...['email', 'deliver', 'recipient'].every((n) =>
26
+ vocab.comp(n)?.namespace?.label == '@yaks/mail'
27
+ )
28
+ ? [recipients()]
29
+ : [],
30
+ ]
package/inbound.js ADDED
@@ -0,0 +1,206 @@
1
+ // The other direction: a letter that arrived, as bundles to write.
2
+ //
3
+ // The shape it takes is the one Cloudflare's Email Workers hand a worker (a
4
+ // `ForwardableEmailMessage`), named structurally so nothing here imports a
5
+ // Cloudflare type — ./conform.ts is where that claim is checked against the
6
+ // runtime's own types. Any other source that can say from, to and headers
7
+ // works the same way.
8
+ //
9
+ // Two things this deliberately does not do:
10
+ //
11
+ // It does not parse MIME. The body arrives as a stream of RFC 5322 and
12
+ // turning that into text is a parser's job, not this package's — so pass the
13
+ // text in (`postal-mime` is the usual choice in a Worker) and this composes
14
+ // the entity around it.
15
+ //
16
+ // It does not query the graph. It is pure: a message in, bundles out. Whom
17
+ // the letter is for, and which earlier letter it answers, are lookups — see
18
+ // below — and a pure function is what makes this testable without a storage
19
+ // adapter anywhere.
20
+ //
21
+ // An arrival carries no `deliver`, which is exactly why it can never echo back
22
+ // out: ./send.ts sends the letters that ask to be sent, and an arrival never
23
+ // asks to be sent.
24
+ import { DOC } from "@yaks/doc";
25
+ import { MAIL } from "./comp.js";
26
+ /**
27
+ * The DKIM verdict off an `Authentication-Results` header, as every receiving
28
+ * MTA writes one: `true` only where the header says `dkim=pass`, `null` where
29
+ * there is no header to read at all — nobody checked, which is not the same as
30
+ * a check that failed.
31
+ *
32
+ * ```ts
33
+ * import { verdict } from '@yaks/mail'
34
+ * let head = (v: string | null) => ({ get: () => v })
35
+ * verdict(head('mx.example; dkim=pass header.i=@books.example; spf=pass')) // true
36
+ * verdict(head('mx.example; dkim=fail; spf=pass')) // false
37
+ * verdict(head(null)) // null
38
+ * ```
39
+ */ export let verdict = (m)=>{
40
+ let said = m.get('authentication-results');
41
+ return said == null ? null : /\bdkim\s*=\s*pass\b/i.test(said);
42
+ };
43
+ /**
44
+ * Who wrote the letter, from the `From:` header.
45
+ *
46
+ * The envelope `from` is not the author: a relay stamps its own bounce address
47
+ * there, so a reply aimed at it reaches a bounce sink rather than a person.
48
+ * The header is the author, in either of its two shapes — `Ana <ana@x.example>`
49
+ * or a bare address — and the envelope is the fallback when there is no header
50
+ * at all.
51
+ */ export let author = (m)=>addressIn(m.headers.get('from')) || m.from;
52
+ /**
53
+ * Whom an answer goes to, from the `Reply-To:` header: the first address it
54
+ * names, or `''` when it names none. A relay (a feedback form, a list) writes
55
+ * for somebody else, so its `From:` is the relay and this is the person. A
56
+ * list's first reader is enough, the way a mail client's Reply answers one.
57
+ *
58
+ * ```ts
59
+ * import { answerer } from '@yaks/mail'
60
+ * let said = (v: string | null) => ({ from: '', to: '', headers: { get: () => v } })
61
+ * answerer(said('Ana <ana@x.example>, bo@x.example')) // 'ana@x.example'
62
+ * answerer(said('ana@x.example')) // 'ana@x.example'
63
+ * answerer(said(null)) // ''
64
+ * ```
65
+ */ export let answerer = (m)=>addressIn(m.headers.get('reply-to')?.split(',')[0]);
66
+ // One address out of a header's either shape, `Ana <ana@x.example>` or bare.
67
+ let addressIn = (said)=>{
68
+ let head = (said ?? '').trim();
69
+ let angled = /<([^<>\s]+@[^<>\s]+)>/.exec(head);
70
+ return angled?.[1] ?? (/^\S+@\S+$/.test(head) ? head : '');
71
+ };
72
+ /**
73
+ * The words a letter's author wrote: its text without the quote of somebody
74
+ * else's letter, which a mail client sets below a reply (or between its
75
+ * lines). A person's letter then never carries another's words as theirs; the
76
+ * letter it quotes is the one its `in-reply-to` names, kept where it was.
77
+ *
78
+ * A quote is known by the line a client introduces it with: `On <date>,
79
+ * <name> <address> wrote:` (which some clients wrap over two lines), or an
80
+ * Outlook header block, `From:` then `Sent:` or `Date:`, or `-----Original
81
+ * Message-----`. Where that line names the author, the quote is their own
82
+ * earlier letter and stays. Otherwise the quote goes: its `>` lines, wherever
83
+ * they fall after it, or everything after it where its lines carry no `>` (an
84
+ * html letter read as text, an Outlook reply). A letter with no such line is
85
+ * its author's, `>` lines and all.
86
+ *
87
+ * ```ts
88
+ * import { own } from '@yaks/mail'
89
+ * own('ok\n\nOn Fri, Bo <bo@x.example> wrote:\n> Send the keys.', 'ana@x.example')
90
+ * // 'ok'
91
+ * own('ok\n\nOn Fri, Ana <ana@x.example> wrote:\n> My list.', 'ana@x.example')
92
+ * // 'ok\n\nOn Fri, Ana <ana@x.example> wrote:\n> My list.'
93
+ * ```
94
+ */ export let own = (text, author)=>{
95
+ let lines = text.split(/\r?\n/);
96
+ let me = author.trim().toLowerCase();
97
+ for(let i = 0; i < lines.length; i++){
98
+ let span = introduces(lines, i);
99
+ if (!span) continue;
100
+ let said = lines.slice(i, i + span.lines).join(' ');
101
+ if (said.match(ADDRESS)?.[0].toLowerCase() == me) {
102
+ i += span.lines - 1;
103
+ continue;
104
+ }
105
+ let rest = lines.slice(i + span.lines);
106
+ let first = rest.find((l)=>l.trim());
107
+ let kept = span.whole || !first?.startsWith('>') ? [] : rest.filter((l)=>!l.startsWith('>'));
108
+ return [
109
+ ...lines.slice(0, i),
110
+ ...kept
111
+ ].join('\n').replace(/\n{3,}/g, '\n\n').trim();
112
+ }
113
+ return text;
114
+ };
115
+ // An address as a quote's introduction writes it: bare, in angles, or
116
+ // after `mailto:`.
117
+ let ADDRESS = /[^\s<>[\]"'(),;:]+@[^\s<>[\]"'(),;:]+/;
118
+ // Whether line `i` introduces a quote, and over how many lines, the last of
119
+ // them naming who wrote it; `whole` where what follows is the quoted letter
120
+ // to its end, `>` or not.
121
+ let introduces = (lines, i)=>{
122
+ let at = (n)=>lines[i + n]?.trim() ?? '';
123
+ if (/^-{2,}\s*original message\s*-{2,}$/i.test(at(0))) {
124
+ let from = [
125
+ 1,
126
+ 2,
127
+ 3
128
+ ].find((n)=>/^from:\s/i.test(at(n)));
129
+ return {
130
+ lines: (from ?? 0) + 1,
131
+ whole: true
132
+ };
133
+ }
134
+ if (/^from:\s/i.test(at(0)) && /^(sent|date):\s/i.test(at(1))) {
135
+ return {
136
+ lines: 1,
137
+ whole: true
138
+ };
139
+ }
140
+ if (!/^on\s/i.test(at(0))) return null;
141
+ if (/\swrote:$/i.test(at(0))) return {
142
+ lines: 1
143
+ };
144
+ if (/\swrote:$/i.test(at(1))) return {
145
+ lines: 2
146
+ };
147
+ return null;
148
+ };
149
+ /** The unbracketed Message-ID of a received letter, or `''`. */ export let messageId = (m)=>(m.headers.get('message-id') ?? '').replace(/[<>]/g, '').trim();
150
+ /**
151
+ * A received message → the bundles that record it: one entity carrying the
152
+ * envelope it arrived in (`mail`) and the words it carried
153
+ * ({@link https://jsr.io/@yaks/doc | @yaks/doc}'s `doc{title, body}`).
154
+ *
155
+ * ```ts
156
+ * import { inbound } from '@yaks/mail'
157
+ * // in a Worker's email() handler:
158
+ * // let text = await parse(message.raw)
159
+ * // await graph.apply(inbound(message, { text, target: club }))
160
+ * ```
161
+ *
162
+ * Threading is a lookup, so the caller passes in the answer rather than the
163
+ * question: read the `in-reply-to` header, find the letter whose `message_id`
164
+ * matches, and pass it as `reply`. Same for `target` when the recipient
165
+ * address names an entity — query `email.address`, and pass what you find.
166
+ * Both lookups live in ./arrive.ts, which has a graph to query.
167
+ */ export let inbound = (m, arrival = {})=>{
168
+ let at = arrival.at ?? m.headers.get('date') ?? new Date().toISOString();
169
+ let answers = m.headers.get('in-reply-to');
170
+ let answer = answerer(m);
171
+ return [
172
+ {
173
+ entity: {
174
+ eid: arrival.eid ?? crypto.randomUUID()
175
+ },
176
+ [DOC]: {
177
+ title: m.headers.get('subject') || '(no subject)',
178
+ body: arrival.text ?? ''
179
+ },
180
+ [MAIL]: {
181
+ from: author(m),
182
+ to: m.to,
183
+ at,
184
+ message_id: messageId(m),
185
+ ...arrival.target ? {
186
+ target: arrival.target
187
+ } : {},
188
+ ...arrival.reply ? {
189
+ reply_to: arrival.reply
190
+ } : {},
191
+ // The header as written, beside `reply_to`: a reply to a letter this
192
+ // graph never kept still says what it answers.
193
+ ...answers ? {
194
+ in_reply_to: answers
195
+ } : {},
196
+ ...answer ? {
197
+ reply_address: answer
198
+ } : {},
199
+ ...arrival.verified == null ? {} : {
200
+ verified: arrival.verified
201
+ }
202
+ }
203
+ }
204
+ ];
205
+ };
206
+ //# sourceMappingURL=inbound.js.map
package/inbound.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inbound.js","sources":["./inbound.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,4EAA4E;AAC5E,0EAA0E;AAC1E,sBAAsB;AACtB,EAAE;AACF,4CAA4C;AAC5C,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,8EAA8E;AAC9E,0BAA0B;AAC1B,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,sBAAsB;AACtB,EAAE;AACF,+EAA+E;AAC/E,6EAA6E;AAC7E,mBAAmB;AAGnB,SAAS,GAAG,yBAA8B;AAC1C,SAAS,IAAI,oBAAmB;AAwChC;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,OAAO,EAAE,GAAG,CAAC;EACjB,OAAO,QAAQ,OAAO,OAAO,uBAAuB,IAAI,CAAC;AAC3D,EAAC;AAED;;;;;;;;CAQC,GACD,OAAO,IAAI,SAAS,CAAC,IACnB,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,YAAY,EAAE,IAAI,CAAA;AAE5C;;;;;;;;;;;;;CAaC,GACD,OAAO,IAAI,WAAW,CAAC,IACrB,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,aAAa,MAAM,IAAI,CAAC,EAAE,EAAC;AAErD,6EAA6E;AAC7E,IAAI,YAAY,CAAC;EACf,IAAI,OAAO,CAAC,QAAQ,EAAE,EAAE,IAAI;EAC5B,IAAI,SAAS,wBAAwB,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