-
Notifications
You must be signed in to change notification settings - Fork 950
Expand file tree
/
Copy pathrender-email-by-path.tsx
More file actions
245 lines (219 loc) Β· 7.35 KB
/
render-email-by-path.tsx
File metadata and controls
245 lines (219 loc) Β· 7.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
'use server';
import fs from 'node:fs';
import path from 'node:path';
import logSymbols from 'log-symbols';
import ora, { type Ora } from 'ora';
import {
isBuilding,
isPreviewDevelopment,
previewServerLocation,
userProjectLocation,
} from '../app/env';
import { convertStackWithSourceMap } from '../utils/convert-stack-with-sourcemap';
import { createJsxRuntime } from '../utils/create-jsx-runtime';
import { getEmailComponent } from '../utils/get-email-component';
import { registerSpinnerAutostopping } from '../utils/register-spinner-autostopping';
import { styleText } from '../utils/style-text';
import type { ErrorObject } from '../utils/types/error-object';
export interface RenderedEmailMetadata {
prettyMarkup: string;
markup: string;
/**
* HTML markup with `data-source-file` and `data-source-line` attributes pointing to the original
* .jsx/.tsx files corresponding to the rendered tag
*/
markupWithReferences?: string;
plainText: string;
reactMarkup: string;
basename: string;
extname: string;
}
export type EmailRenderingResult =
| RenderedEmailMetadata
| {
error: ErrorObject;
};
const cache = new Map<string, EmailRenderingResult>();
export const renderEmailByPath = async (
emailPath: string,
invalidatingCache = false,
): Promise<EmailRenderingResult> => {
if (invalidatingCache) {
cache.delete(emailPath);
}
if (cache.has(emailPath)) {
return cache.get(emailPath)!;
}
const emailFilename = path.basename(emailPath);
let spinner: Ora | undefined;
if (!isBuilding && !isPreviewDevelopment) {
spinner = ora({
text: `Rendering email template ${emailFilename}\n`,
prefixText: ' ',
}).start();
registerSpinnerAutostopping(spinner);
}
const timeBeforeEmailBundled = performance.now();
const originalJsxRuntimePath = path.resolve(
previewServerLocation,
'jsx-runtime',
);
const jsxRuntimePath = await createJsxRuntime(
userProjectLocation,
originalJsxRuntimePath,
);
const componentResult = await getEmailComponent(emailPath, jsxRuntimePath);
const millisecondsToBundled = performance.now() - timeBeforeEmailBundled;
if ('error' in componentResult) {
spinner?.stopAndPersist({
symbol: logSymbols.error,
text: `Failed while rendering ${emailFilename}`,
});
return { error: componentResult.error };
}
const {
emailComponent: Email,
createElement,
render,
renderWithReferences,
sourceMapToOriginalFile,
} = componentResult;
const previewProps = Email.PreviewProps || {};
const EmailComponent = Email as React.FC;
try {
const timeBeforeEmailRendered = performance.now();
const element = createElement(EmailComponent, previewProps);
const markupWithReferences = await renderWithReferences(element, {
pretty: true,
});
const prettyMarkup = await render(element, {
pretty: true,
});
const markup = await render(element, {
pretty: false,
});
const plainText = await render(element, {
plainText: true,
});
const reactMarkup = await fs.promises.readFile(emailPath, 'utf-8');
const millisecondsToRendered = performance.now() - timeBeforeEmailRendered;
let timeForConsole = `${millisecondsToRendered.toFixed(0)}ms`;
if (millisecondsToRendered <= 450) {
timeForConsole = styleText('green', timeForConsole);
} else if (millisecondsToRendered <= 1000) {
timeForConsole = styleText('yellow', timeForConsole);
} else {
timeForConsole = styleText('red', timeForConsole);
}
spinner?.stopAndPersist({
symbol: logSymbols.success,
text: `Successfully rendered ${emailFilename} in ${timeForConsole} (bundled in ${millisecondsToBundled.toFixed(0)}ms)`,
});
const renderingResult: RenderedEmailMetadata = {
prettyMarkup,
// This ensures that no null byte character ends up in the rendered
// markup making users suspect of any issues. These null byte characters
// only seem to happen with React 18, as it has no similar incident with React 19.
markup: markup.replaceAll('\0', ''),
markupWithReferences: markupWithReferences.replaceAll('\0', ''),
plainText,
reactMarkup,
basename: path.basename(emailPath, path.extname(emailPath)),
extname: path.extname(emailPath).slice(1),
};
cache.set(emailPath, renderingResult);
return renderingResult;
} catch (exception) {
const error = exception as Error;
spinner?.stopAndPersist({
symbol: logSymbols.error,
text: `Failed while rendering ${emailFilename}`,
});
if (exception instanceof SyntaxError) {
interface SpanPosition {
file: {
content: string;
};
offset: number;
line: number;
col: number;
}
// means the email's HTML was invalid and prettier threw this error
// TODO: always throw when the HTML is invalid during `render`
const cause = exception.cause as {
msg: string;
span: {
start: SpanPosition;
end: SpanPosition;
};
};
const sourceFileAttributeMatches = cause.span.start.file.content.matchAll(
/data-source-file="(?<file>[^"]*)"/g,
);
let closestSourceFileAttribute: RegExpExecArray | undefined;
for (const sourceFileAttributeMatch of sourceFileAttributeMatches) {
if (closestSourceFileAttribute === undefined) {
closestSourceFileAttribute = sourceFileAttributeMatch;
}
if (
Math.abs(sourceFileAttributeMatch.index - cause.span.start.offset) <
Math.abs(closestSourceFileAttribute.index - cause.span.start.offset)
) {
closestSourceFileAttribute = sourceFileAttributeMatch;
}
}
const findClosestAttributeValue = (
attributeName: string,
): string | undefined => {
const attributeMatches = cause.span.start.file.content.matchAll(
new RegExp(`${attributeName}="(?<value>[^"]*)"`, 'g'),
);
let closestAttribute: RegExpExecArray | undefined;
for (const attributeMatch of attributeMatches) {
if (closestAttribute === undefined) {
closestAttribute = attributeMatch;
}
if (
Math.abs(attributeMatch.index - cause.span.start.offset) <
Math.abs(closestAttribute.index - cause.span.start.offset)
) {
closestAttribute = attributeMatch;
}
}
return closestAttribute?.groups?.value;
};
let stack = convertStackWithSourceMap(
error.stack,
emailPath,
sourceMapToOriginalFile,
);
const sourceFile = findClosestAttributeValue('data-source-file');
const sourceLine = findClosestAttributeValue('data-source-line');
if (sourceFile && sourceLine) {
stack = ` at ${sourceFile}:${sourceLine}\n${stack}`;
}
return {
error: {
name: exception.name,
message: cause.msg,
stack,
cause: error.cause ? JSON.parse(JSON.stringify(cause)) : undefined,
},
};
}
return {
error: {
name: error.name,
message: error.message,
stack: convertStackWithSourceMap(
error.stack,
emailPath,
sourceMapToOriginalFile,
),
cause: error.cause
? JSON.parse(JSON.stringify(error.cause))
: undefined,
},
};
}
};