Repository navigation
feat(node): send Nodemailer mail through PostHog #5575
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Silthus
wants to merge
12
commits into
emails-v2/node-integration-option
from
emails-v2/node-nodemailer-transport
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d1d5353
feat(node): send Nodemailer mail through PostHog
Silthus 7ba8074
fix(node): refuse what Nodemailer's normalize() hides, and type the tβ¦
Silthus 84935ad
Merge branch 'emails-v2/node-integration-option' into emails-v2/node-β¦
Silthus bdca8bb
docs(node): say what capture_engagement does in the Nodemailer options
Silthus 5498549
Merge commit '03d1aba76' into map41/nodemailer-transport
Silthus 1b3e597
fix(node): refuse what the Nodemailer transport can't carry, and passβ¦
Silthus b3771bb
Merge commit '7229be4c9' into map41/nodemailer-transport
Silthus 1e4a3d7
Merge remote-tracking branch 'origin/emails-v2/node-integration-optioβ¦
Silthus 5eef616
fix(node): refuse what Nodemailer changes after compile, and keep retβ¦
Silthus c9a28bd
fix(node): never call a keyless Nodemailer send retryable, and keep dβ¦
Silthus 38baa70
fix(node): renumber only whole data URL content ID references
Silthus 4cf1529
fix(node): end a data URL content ID reference at any non-ID character
Silthus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| 'posthog-node': minor | ||
| --- | ||
|
|
||
| Send Nodemailer mail through PostHog with the new `posthog-node/nodemailer` entry point: `nodemailer.createTransport(createPostHogTransport({ client }))`. Every `sendMail` call stays as it is, and `sendMail({ posthog: { ... } })` takes PostHog's options. A message PostHog can't carry fails with `code: 'EPOSTHOGUNSUPPORTED'` and sends nothing. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /** @vitest-environment node */ | ||
|
|
||
| import { execFileSync } from 'node:child_process' | ||
| import { fileURLToPath } from 'node:url' | ||
|
|
||
| const packageRoot = fileURLToPath(new URL('../../', import.meta.url)) | ||
|
|
||
| const HIDE_NODEMAILER = ` | ||
| import { registerHooks } from 'node:module' | ||
| registerHooks({ | ||
| resolve(specifier, context, nextResolve) { | ||
| if (specifier === 'nodemailer' || specifier.startsWith('nodemailer/')) { | ||
| throw Object.assign(new Error('Cannot find module ' + specifier), { code: 'ERR_MODULE_NOT_FOUND' }) | ||
| } | ||
| return nextResolve(specifier, context) | ||
| }, | ||
| }) | ||
| ` | ||
|
|
||
| describe('the built posthog-node without Nodemailer installed', () => { | ||
| it.each(['import', 'require'])('loads both entry points with %s and sends a message', (loader) => { | ||
| const load = (specifier: string): string => | ||
| loader === 'import' ? `await import('${specifier}')` : `createRequire(import.meta.url)('${specifier}')` | ||
| const output = execFileSync( | ||
| process.execPath, | ||
| [ | ||
| '--import', | ||
| `data:text/javascript,${encodeURIComponent(HIDE_NODEMAILER)}`, | ||
| '--input-type=module', | ||
| '-e', | ||
| ` | ||
| import { createRequire } from 'node:module' | ||
| const { PostHog } = ${load('posthog-node')} | ||
| const { createPostHogTransport } = ${load('posthog-node/nodemailer')} | ||
| await import('nodemailer').then(() => { throw new Error('Nodemailer is still installed') }, () => {}) | ||
| const client = new PostHog('phc_test', { | ||
| secretKey: 'phs_test', | ||
| enableLocalEvaluation: false, | ||
| fetch: async () => ({ status: 202, text: async () => '{"message_id":"msg_1"}', headers: { get: () => null } }), | ||
| }) | ||
| const data = { | ||
| from: { name: '', address: 'shop@example.com' }, | ||
| to: [{ name: '', address: 'ana@example.com' }], | ||
| subject: 'Hi', | ||
| text: 'Hi', | ||
| envelope: { from: 'shop@example.com', to: ['ana@example.com'] }, | ||
| } | ||
| const info = await new Promise((resolve, reject) => | ||
| createPostHogTransport({ client }).send({ normalize: (done) => done(null, data) }, (error, sent) => | ||
| error ? reject(error) : resolve(sent) | ||
| ) | ||
| ) | ||
| await client.shutdown() | ||
| console.log(JSON.stringify(info)) | ||
| `, | ||
| ], | ||
| { cwd: packageRoot, encoding: 'utf8', timeout: 10_000 } | ||
| ) | ||
|
|
||
| expect(JSON.parse(output)).toEqual({ messageId: 'msg_1' }) | ||
| }) | ||
| }) |
76 changes: 76 additions & 0 deletions
76
packages/node/src/__tests__/nodemailer-declarations.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /** @vitest-environment node */ | ||
|
|
||
| import { spawnSync } from 'node:child_process' | ||
| import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
| import { fileURLToPath } from 'node:url' | ||
|
|
||
| const packageRoot = fileURLToPath(new URL('../../', import.meta.url)) | ||
|
|
||
| const CONSUMER = ` | ||
| import nodemailer from 'nodemailer' | ||
| import { PostHog } from 'posthog-node' | ||
| import { createPostHogTransport } from 'posthog-node/nodemailer' | ||
|
|
||
| const client = new PostHog('phc_test', { secretKey: 'phs_test' }) | ||
| const transporter = nodemailer.createTransport(createPostHogTransport({ client })) | ||
|
|
||
| export const messageId: Promise<string> = transporter | ||
| .sendMail({ | ||
| to: 'ana@example.com', | ||
| subject: 'Hi', | ||
| text: 'Hi', | ||
| posthog: { distinct_id: 'user_42', tracking: { opens: true, clicks: false }, sensitive: true }, | ||
| }) | ||
| .then((info) => info.messageId) | ||
|
|
||
| // @ts-expect-error a PostHog send has no SMTP fields | ||
| export const accepted = transporter.sendMail({ to: 'ana@example.com', text: 'Hi' }).then((info) => info.accepted) | ||
|
|
||
| // @ts-expect-error the PostHog options keep the API's names | ||
| export const misnamed = transporter.sendMail({ to: 'ana@example.com', text: 'Hi', posthog: { distinctId: 'user_42' } }) | ||
| ` | ||
|
|
||
| describe('the built posthog-node/nodemailer declarations', () => { | ||
| let consumer: string | ||
|
|
||
| beforeAll(() => { | ||
| consumer = mkdtempSync(join(tmpdir(), 'posthog-nodemailer-consumer-')) | ||
| mkdirSync(join(consumer, 'node_modules/@types'), { recursive: true }) | ||
| symlinkSync(packageRoot, join(consumer, 'node_modules/posthog-node')) | ||
| symlinkSync(join(packageRoot, 'node_modules/nodemailer'), join(consumer, 'node_modules/nodemailer')) | ||
| symlinkSync(join(packageRoot, 'node_modules/@types/node'), join(consumer, 'node_modules/@types/node')) | ||
| writeFileSync(join(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' })) | ||
| }) | ||
|
|
||
| afterAll(() => rmSync(consumer, { recursive: true, force: true })) | ||
|
|
||
| it.each(['mts', 'cts'])('type-check sendMail with PostHog options in a NodeNext .%s consumer', (extension) => { | ||
| writeFileSync(join(consumer, `consumer.${extension}`), CONSUMER) | ||
| writeFileSync( | ||
| join(consumer, `tsconfig.${extension}.json`), | ||
| JSON.stringify({ | ||
| compilerOptions: { | ||
| strict: true, | ||
| noEmit: true, | ||
| target: 'ES2022', | ||
| module: 'NodeNext', | ||
| moduleResolution: 'NodeNext', | ||
| types: ['node'], | ||
| esModuleInterop: true, | ||
| }, | ||
| files: [`consumer.${extension}`], | ||
| }) | ||
| ) | ||
|
|
||
| const result = spawnSync( | ||
| process.execPath, | ||
| [join(packageRoot, 'node_modules/typescript/bin/tsc'), '-p', `tsconfig.${extension}.json`, '--pretty', 'false'], | ||
| { cwd: consumer, encoding: 'utf8', timeout: 60_000 } | ||
| ) | ||
|
|
||
| expect(result.stdout + result.stderr).toBe('') | ||
| expect(result.status).toBe(0) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| /** @vitest-environment node */ | ||
|
|
||
| import { spawn } from 'node:child_process' | ||
| import { fileURLToPath } from 'node:url' | ||
|
|
||
| const packageRoot = fileURLToPath(new URL('../../', import.meta.url)) | ||
|
|
||
| const SCRIPT_WITH_A_STALLED_ATTACHMENT = ` | ||
| import { PassThrough } from 'node:stream' | ||
| import nodemailer from 'nodemailer' | ||
| import { PostHog } from 'posthog-node' | ||
| import { createPostHogTransport } from 'posthog-node/nodemailer' | ||
|
|
||
| const client = new PostHog('phc_test', { secretKey: 'phs_test', enableLocalEvaluation: false }) | ||
| const transporter = nodemailer.createTransport(createPostHogTransport({ client })) | ||
| const sent = transporter.sendMail({ | ||
| from: 'shop@example.com', | ||
| to: 'ana@example.com', | ||
| subject: 'Report', | ||
| text: 'Attached.', | ||
| attachments: [{ filename: 'report.csv', content: new PassThrough() }], | ||
| }) | ||
| console.log('sending') | ||
| await sent | ||
| ` | ||
|
|
||
| describe('the built posthog-node/nodemailer in a script', () => { | ||
| it('keeps the script running while it waits for an attachment, so the send can still fail', async () => { | ||
| vi.useRealTimers() | ||
| const script = spawn(process.execPath, ['--input-type=module', '-e', SCRIPT_WITH_A_STALLED_ATTACHMENT], { | ||
| cwd: packageRoot, | ||
| stdio: ['ignore', 'pipe', 'ignore'], | ||
| }) | ||
| const exited = new Promise<number | null>((resolve) => script.once('exit', resolve)) | ||
| const sending = new Promise<void>((resolve) => | ||
| script.stdout.on('data', (chunk) => chunk.includes('sending') && resolve()) | ||
| ) | ||
|
|
||
| await Promise.race([sending, exited]) | ||
| const outcome = await Promise.race([exited, new Promise((resolve) => setTimeout(() => resolve('running'), 2_000))]) | ||
| script.kill() | ||
| await exited | ||
|
|
||
| expect(outcome).toBe('running') | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.