react-email 4.1.0 → 4.1.1

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 (100) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.js +2 -2
  3. package/package.json +1 -1
  4. package/src/utils/get-preview-server-location.ts +1 -2
  5. package/dist/cli/index.mjs +0 -1391
  6. package/dist/preview/.next/BUILD_ID +0 -1
  7. package/dist/preview/.next/app-build-manifest.json +0 -44
  8. package/dist/preview/.next/app-path-routes-manifest.json +0 -6
  9. package/dist/preview/.next/build-manifest.json +0 -33
  10. package/dist/preview/.next/diagnostics/build-diagnostics.json +0 -6
  11. package/dist/preview/.next/diagnostics/framework.json +0 -1
  12. package/dist/preview/.next/export-marker.json +0 -6
  13. package/dist/preview/.next/images-manifest.json +0 -57
  14. package/dist/preview/.next/next-minimal-server.js.nft.json +0 -1
  15. package/dist/preview/.next/next-server.js.nft.json +0 -1
  16. package/dist/preview/.next/package.json +0 -1
  17. package/dist/preview/.next/prerender-manifest.json +0 -41
  18. package/dist/preview/.next/react-loadable-manifest.json +0 -1
  19. package/dist/preview/.next/required-server-files.json +0 -311
  20. package/dist/preview/.next/routes-manifest.json +0 -64
  21. package/dist/preview/.next/server/app/_not-found/page.js +0 -1
  22. package/dist/preview/.next/server/app/_not-found/page.js.nft.json +0 -1
  23. package/dist/preview/.next/server/app/_not-found/page_client-reference-manifest.js +0 -1
  24. package/dist/preview/.next/server/app/favicon.ico/route.js +0 -1
  25. package/dist/preview/.next/server/app/favicon.ico/route.js.nft.json +0 -1
  26. package/dist/preview/.next/server/app/favicon.ico.body +0 -0
  27. package/dist/preview/.next/server/app/favicon.ico.meta +0 -1
  28. package/dist/preview/.next/server/app/page.js +0 -1
  29. package/dist/preview/.next/server/app/page.js.nft.json +0 -1
  30. package/dist/preview/.next/server/app/page_client-reference-manifest.js +0 -1
  31. package/dist/preview/.next/server/app/preview/[...slug]/page.js +0 -321
  32. package/dist/preview/.next/server/app/preview/[...slug]/page.js.nft.json +0 -1
  33. package/dist/preview/.next/server/app/preview/[...slug]/page_client-reference-manifest.js +0 -1
  34. package/dist/preview/.next/server/app-paths-manifest.json +0 -6
  35. package/dist/preview/.next/server/chunks/134.js +0 -6
  36. package/dist/preview/.next/server/chunks/235.js +0 -15
  37. package/dist/preview/.next/server/chunks/343.js +0 -20
  38. package/dist/preview/.next/server/chunks/428.js +0 -14
  39. package/dist/preview/.next/server/chunks/934.js +0 -1
  40. package/dist/preview/.next/server/chunks/963.js +0 -1
  41. package/dist/preview/.next/server/functions-config-manifest.json +0 -4
  42. package/dist/preview/.next/server/interception-route-rewrite-manifest.js +0 -1
  43. package/dist/preview/.next/server/middleware-build-manifest.js +0 -1
  44. package/dist/preview/.next/server/middleware-manifest.json +0 -6
  45. package/dist/preview/.next/server/middleware-react-loadable-manifest.js +0 -1
  46. package/dist/preview/.next/server/next-font-manifest.js +0 -1
  47. package/dist/preview/.next/server/next-font-manifest.json +0 -1
  48. package/dist/preview/.next/server/pages/500.html +0 -1
  49. package/dist/preview/.next/server/pages/_app.js +0 -1
  50. package/dist/preview/.next/server/pages/_app.js.nft.json +0 -1
  51. package/dist/preview/.next/server/pages/_document.js +0 -1
  52. package/dist/preview/.next/server/pages/_document.js.nft.json +0 -1
  53. package/dist/preview/.next/server/pages/_error.js +0 -1
  54. package/dist/preview/.next/server/pages/_error.js.nft.json +0 -1
  55. package/dist/preview/.next/server/pages-manifest.json +0 -5
  56. package/dist/preview/.next/server/server-reference-manifest.js +0 -1
  57. package/dist/preview/.next/server/server-reference-manifest.json +0 -1
  58. package/dist/preview/.next/server/webpack-runtime.js +0 -1
  59. package/dist/preview/.next/static/FZEE-q531kq1Juxsda2po/_buildManifest.js +0 -1
  60. package/dist/preview/.next/static/FZEE-q531kq1Juxsda2po/_ssgManifest.js +0 -1
  61. package/dist/preview/.next/static/chunks/107-3043079e7cb8bcae.js +0 -1
  62. package/dist/preview/.next/static/chunks/293-297b1eb2241f9a70.js +0 -1
  63. package/dist/preview/.next/static/chunks/3bd82e28-cda2c00a924937c5.js +0 -1
  64. package/dist/preview/.next/static/chunks/45-1021fac82f766268.js +0 -1
  65. package/dist/preview/.next/static/chunks/484-f5954e7b4b93f109.js +0 -1
  66. package/dist/preview/.next/static/chunks/589-817d8691661d370e.js +0 -1
  67. package/dist/preview/.next/static/chunks/902-c34acb56733e0ce1.js +0 -1
  68. package/dist/preview/.next/static/chunks/app/_not-found/page-4cbc7dce3ad33336.js +0 -1
  69. package/dist/preview/.next/static/chunks/app/layout-89c12abbc616c3a1.js +0 -1
  70. package/dist/preview/.next/static/chunks/app/page-0492cd9ce15b7980.js +0 -1
  71. package/dist/preview/.next/static/chunks/app/preview/[...slug]/page-c670410568d530db.js +0 -1
  72. package/dist/preview/.next/static/chunks/f33a14d2-ec7c5f0b91818561.js +0 -6
  73. package/dist/preview/.next/static/chunks/framework-b887e9fc751a9906.js +0 -1
  74. package/dist/preview/.next/static/chunks/main-9a03e7ba8acb1900.js +0 -1
  75. package/dist/preview/.next/static/chunks/main-app-951f948d1c44189f.js +0 -1
  76. package/dist/preview/.next/static/chunks/pages/_app-542a93a5a214e1c0.js +0 -1
  77. package/dist/preview/.next/static/chunks/pages/_error-d5fe1b1612642f76.js +0 -1
  78. package/dist/preview/.next/static/chunks/polyfills-42372ed130431b0a.js +0 -1
  79. package/dist/preview/.next/static/chunks/webpack-31c45daa2bd82a7b.js +0 -1
  80. package/dist/preview/.next/static/css/78c81281aa95270f.css +0 -3
  81. package/dist/preview/.next/static/media/05613964ce6c782e-s.p.otf +0 -0
  82. package/dist/preview/.next/static/media/11c6126b9369e85e-s.p.otf +0 -0
  83. package/dist/preview/.next/static/media/26a46d62cd723877-s.woff2 +0 -0
  84. package/dist/preview/.next/static/media/26cb97734d8cb717-s.p.otf +0 -0
  85. package/dist/preview/.next/static/media/55c55f0601d81cf3-s.woff2 +0 -0
  86. package/dist/preview/.next/static/media/581909926a08bbc8-s.woff2 +0 -0
  87. package/dist/preview/.next/static/media/8e9860b6e62d6359-s.woff2 +0 -0
  88. package/dist/preview/.next/static/media/97e0cb1ae144a2a9-s.woff2 +0 -0
  89. package/dist/preview/.next/static/media/bb6462617151f6b7-s.p.otf +0 -0
  90. package/dist/preview/.next/static/media/cf6daef822ab0142-s.p.otf +0 -0
  91. package/dist/preview/.next/static/media/df0a9ae256c0569c-s.woff2 +0 -0
  92. package/dist/preview/.next/static/media/e4051546b3043204-s.p.otf +0 -0
  93. package/dist/preview/.next/static/media/e4af272ccee01ff0-s.p.woff2 +0 -0
  94. package/dist/preview/.next/static/media/logo.2ce2a759.png +0 -0
  95. package/dist/preview/.next/trace +0 -27
  96. package/dist/preview/.next/types/app/layout.ts +0 -84
  97. package/dist/preview/.next/types/app/page.ts +0 -84
  98. package/dist/preview/.next/types/app/preview/[...slug]/page.ts +0 -84
  99. package/dist/preview/.next/types/cache-life.d.ts +0 -141
  100. package/dist/preview/.next/types/package.json +0 -1
@@ -1,1391 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/cli/index.ts
4
- import { program } from "commander";
5
-
6
- // package.json
7
- var package_default = {
8
- name: "react-email",
9
- version: "4.0.17",
10
- description: "A live preview of your emails right in your browser.",
11
- bin: {
12
- email: "./dist/cli/index.mjs"
13
- },
14
- scripts: {
15
- build: "tsup-node && node ./scripts/build-preview-server.mjs && pnpm install --frozen-lockfile",
16
- "caniemail:fetch": "node ./scripts/fill-caniemail-data.mjs",
17
- clean: "rm -rf dist",
18
- dev: "tsup-node --watch",
19
- "dev:preview": "cd ../../apps/demo && tsx ../../packages/react-email/src/cli/index.ts dev",
20
- test: "vitest run",
21
- "test:watch": "vitest"
22
- },
23
- license: "MIT",
24
- repository: {
25
- type: "git",
26
- url: "https://github.com/resend/react-email.git",
27
- directory: "packages/react-email"
28
- },
29
- keywords: [
30
- "react",
31
- "email"
32
- ],
33
- engines: {
34
- node: ">=18.0.0"
35
- },
36
- dependencies: {
37
- "@babel/parser": "^7.27.0",
38
- "@babel/traverse": "^7.27.0",
39
- chalk: "^5.0.0",
40
- chokidar: "^4.0.3",
41
- commander: "^13.0.0",
42
- debounce: "^2.0.0",
43
- esbuild: "^0.25.0",
44
- glob: "^11.0.0",
45
- "log-symbols": "^7.0.0",
46
- "mime-types": "^3.0.0",
47
- next: "^15.3.1",
48
- "normalize-path": "^3.0.0",
49
- ora: "^8.0.0",
50
- "socket.io": "^4.8.1",
51
- "tsconfig-paths": "4.2.0"
52
- },
53
- devDependencies: {
54
- "@babel/core": "7.26.10",
55
- "@lottiefiles/dotlottie-react": "0.13.3",
56
- "@radix-ui/colors": "3.0.0",
57
- "@radix-ui/react-collapsible": "1.1.7",
58
- "@radix-ui/react-dropdown-menu": "2.1.10",
59
- "@radix-ui/react-popover": "1.1.10",
60
- "@radix-ui/react-slot": "1.2.0",
61
- "@radix-ui/react-tabs": "1.1.7",
62
- "@radix-ui/react-toggle-group": "1.1.6",
63
- "@radix-ui/react-tooltip": "1.2.3",
64
- "@react-email/components": "workspace:*",
65
- "@swc/core": "1.11.21",
66
- "@types/babel__core": "7.20.5",
67
- "@types/babel__traverse": "7.20.7",
68
- "@types/fs-extra": "11.0.1",
69
- "@types/mime-types": "2.1.4",
70
- "@types/node": "22.14.1",
71
- "@types/normalize-path": "3.0.2",
72
- "@types/react": "19.0.10",
73
- "@types/react-dom": "19.0.4",
74
- "@types/webpack": "5.28.5",
75
- autoprefixer: "10.4.21",
76
- clsx: "2.1.1",
77
- "framer-motion": "12.7.5",
78
- jiti: "2.4.2",
79
- json5: "2.2.3",
80
- "module-punycode": "npm:punycode@2.3.1",
81
- "node-html-parser": "7.0.1",
82
- postcss: "8.5.3",
83
- "pretty-bytes": "6.1.1",
84
- "prism-react-renderer": "2.4.1",
85
- react: "19.0.0",
86
- "react-dom": "19.0.0",
87
- sharp: "0.34.1",
88
- "socket.io-client": "4.8.1",
89
- sonner: "2.0.3",
90
- "source-map-js": "1.2.1",
91
- spamc: "0.0.5",
92
- "stacktrace-parser": "0.1.11",
93
- "tailwind-merge": "3.2.0",
94
- tailwindcss: "3.4.0",
95
- tsup: "8.4.0",
96
- tsx: "4.19.3",
97
- typescript: "5.8.3",
98
- "use-debounce": "10.0.4",
99
- zod: "3.24.3"
100
- }
101
- };
102
-
103
- // src/cli/commands/build.ts
104
- import { spawn } from "node:child_process";
105
- import fs5 from "node:fs";
106
- import path9 from "node:path";
107
- import logSymbols3 from "log-symbols";
108
- import ora2 from "ora";
109
-
110
- // src/utils/get-emails-directory-metadata.ts
111
- import fs from "node:fs";
112
- import path from "node:path";
113
- var isFileAnEmail = async (fullPath) => {
114
- let fileHandle;
115
- try {
116
- fileHandle = await fs.promises.open(fullPath, "r");
117
- } catch (exception) {
118
- console.warn(exception);
119
- return false;
120
- }
121
- const stat = await fileHandle.stat();
122
- if (stat.isDirectory()) {
123
- await fileHandle.close();
124
- return false;
125
- }
126
- const { ext } = path.parse(fullPath);
127
- if (![".js", ".tsx", ".jsx"].includes(ext)) {
128
- await fileHandle.close();
129
- return false;
130
- }
131
- const fileContents = await fileHandle.readFile("utf8");
132
- await fileHandle.close();
133
- const hasES6DefaultExport = /\bexport\s+default\b/gm.test(fileContents);
134
- const hasCommonJSExport = /\bmodule\.exports\s*=/gm.test(fileContents);
135
- const hasNamedExport = /\bexport\s+\{[^}]*\bdefault\b[^}]*\}/gm.test(
136
- fileContents
137
- );
138
- return hasES6DefaultExport || hasCommonJSExport || hasNamedExport;
139
- };
140
- var mergeDirectoriesWithSubDirectories = (emailsDirectoryMetadata) => {
141
- let currentResultingMergedDirectory = emailsDirectoryMetadata;
142
- while (currentResultingMergedDirectory.emailFilenames.length === 0 && currentResultingMergedDirectory.subDirectories.length === 1) {
143
- const onlySubDirectory = currentResultingMergedDirectory.subDirectories[0];
144
- currentResultingMergedDirectory = {
145
- ...onlySubDirectory,
146
- directoryName: path.join(
147
- currentResultingMergedDirectory.directoryName,
148
- onlySubDirectory.directoryName
149
- )
150
- };
151
- }
152
- return currentResultingMergedDirectory;
153
- };
154
- var getEmailsDirectoryMetadata = async (absolutePathToEmailsDirectory, keepFileExtensions = false, isSubDirectory = false, baseDirectoryPath = absolutePathToEmailsDirectory) => {
155
- if (!fs.existsSync(absolutePathToEmailsDirectory)) return;
156
- const dirents = await fs.promises.readdir(absolutePathToEmailsDirectory, {
157
- withFileTypes: true
158
- });
159
- const isEmailPredicates = await Promise.all(
160
- dirents.map(
161
- (dirent) => isFileAnEmail(path.join(absolutePathToEmailsDirectory, dirent.name))
162
- )
163
- );
164
- const emailFilenames = dirents.filter((_, i) => isEmailPredicates[i]).map(
165
- (dirent) => keepFileExtensions ? dirent.name : dirent.name.replace(path.extname(dirent.name), "")
166
- );
167
- const subDirectories = await Promise.all(
168
- dirents.filter(
169
- (dirent) => dirent.isDirectory() && !dirent.name.startsWith("_") && dirent.name !== "static"
170
- ).map((dirent) => {
171
- const direntAbsolutePath = path.join(
172
- absolutePathToEmailsDirectory,
173
- dirent.name
174
- );
175
- return getEmailsDirectoryMetadata(
176
- direntAbsolutePath,
177
- keepFileExtensions,
178
- true,
179
- baseDirectoryPath
180
- );
181
- })
182
- );
183
- const emailsMetadata = {
184
- absolutePath: absolutePathToEmailsDirectory,
185
- relativePath: path.relative(
186
- baseDirectoryPath,
187
- absolutePathToEmailsDirectory
188
- ),
189
- directoryName: absolutePathToEmailsDirectory.split(path.sep).pop(),
190
- emailFilenames,
191
- subDirectories
192
- };
193
- return isSubDirectory ? mergeDirectoriesWithSubDirectories(emailsMetadata) : emailsMetadata;
194
- };
195
-
196
- // src/utils/register-spinner-autostopping.ts
197
- import logSymbols from "log-symbols";
198
- var spinners = /* @__PURE__ */ new Set();
199
- process.on("SIGINT", () => {
200
- spinners.forEach((spinner) => {
201
- if (spinner.isSpinning) {
202
- spinner.stop();
203
- }
204
- });
205
- });
206
- process.on("exit", (code) => {
207
- if (code !== 0) {
208
- spinners.forEach((spinner) => {
209
- if (spinner.isSpinning) {
210
- spinner.stopAndPersist({
211
- symbol: logSymbols.error
212
- });
213
- }
214
- });
215
- }
216
- });
217
- var registerSpinnerAutostopping = (spinner) => {
218
- spinners.add(spinner);
219
- };
220
-
221
- // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
222
- import path7 from "node:path";
223
- import { watch } from "chokidar";
224
- import debounce from "debounce";
225
- import { Server as SocketServer } from "socket.io";
226
-
227
- // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
228
- import { existsSync as existsSync2, promises as fs3, statSync } from "node:fs";
229
- import path6 from "node:path";
230
-
231
- // src/cli/utils/preview/start-dev-server.ts
232
- import http from "node:http";
233
- import path4 from "node:path";
234
- import url from "node:url";
235
- import chalk from "chalk";
236
- import logSymbols2 from "log-symbols";
237
- import next from "next";
238
- import ora from "ora";
239
-
240
- // src/cli/utils/preview/get-env-variables-for-preview-app.ts
241
- import path2 from "node:path";
242
- var getEnvVariablesForPreviewApp = (relativePathToEmailsDirectory, cwd) => {
243
- return {
244
- EMAILS_DIR_RELATIVE_PATH: relativePathToEmailsDirectory,
245
- EMAILS_DIR_ABSOLUTE_PATH: path2.resolve(cwd, relativePathToEmailsDirectory),
246
- USER_PROJECT_LOCATION: cwd,
247
- NEXT_PUBLIC_IS_PREVIEW_DEVELOPMENT: isDev ? "true" : "false"
248
- };
249
- };
250
-
251
- // src/cli/utils/preview/serve-static-file.ts
252
- import { existsSync, promises as fs2 } from "node:fs";
253
- import path3 from "node:path";
254
- import { lookup } from "mime-types";
255
- var serveStaticFile = async (res, parsedUrl, staticDirRelativePath) => {
256
- const pathname = parsedUrl.pathname.replace("/static", "./static");
257
- const ext = path3.parse(pathname).ext;
258
- const staticBaseDir = path3.resolve(process.cwd(), staticDirRelativePath);
259
- const fileAbsolutePath = path3.resolve(staticBaseDir, pathname);
260
- if (!fileAbsolutePath.startsWith(staticBaseDir)) {
261
- res.statusCode = 403;
262
- res.end();
263
- return;
264
- }
265
- try {
266
- const fileHandle = await fs2.open(fileAbsolutePath, "r");
267
- const fileData = await fs2.readFile(fileHandle);
268
- res.setHeader("Content-type", lookup(ext) || "text/plain");
269
- res.end(fileData);
270
- fileHandle.close();
271
- } catch (exception) {
272
- if (!existsSync(fileAbsolutePath)) {
273
- res.statusCode = 404;
274
- res.end();
275
- } else {
276
- const sanitizedFilePath = fileAbsolutePath.replace(/\n|\r/g, "");
277
- console.error(
278
- `Could not read file at %s to be served, here's the exception:`,
279
- sanitizedFilePath,
280
- exception
281
- );
282
- res.statusCode = 500;
283
- res.end(
284
- "Could not read file to be served! Check your terminal for more information."
285
- );
286
- }
287
- }
288
- };
289
-
290
- // src/cli/utils/preview/start-dev-server.ts
291
- var devServer;
292
- var safeAsyncServerListen = (server, port) => {
293
- return new Promise((resolve) => {
294
- server.listen(port, () => {
295
- resolve({ portAlreadyInUse: false });
296
- });
297
- server.on("error", (e) => {
298
- if (e.code === "EADDRINUSE") {
299
- resolve({ portAlreadyInUse: true });
300
- }
301
- });
302
- });
303
- };
304
- var filename = url.fileURLToPath(import.meta.url);
305
- var dirname = path4.dirname(filename);
306
- var isDev = !filename.endsWith(path4.join("cli", "index.mjs"));
307
- var cliPackageLocation = isDev ? path4.resolve(dirname, "../../../..") : path4.resolve(dirname, "../..");
308
- var previewServerLocation = isDev ? path4.resolve(dirname, "../../../..") : path4.resolve(dirname, "../preview");
309
- var startDevServer = async (emailsDirRelativePath, staticBaseDirRelativePath, port) => {
310
- const [majorNodeVersion] = process.versions.node.split(".");
311
- if (majorNodeVersion && Number.parseInt(majorNodeVersion) < 18) {
312
- console.error(
313
- ` ${logSymbols2.error} Node ${majorNodeVersion} is not supported. Please upgrade to Node 18 or higher.`
314
- );
315
- process.exit(1);
316
- }
317
- devServer = http.createServer((req, res) => {
318
- if (!req.url) {
319
- res.end(404);
320
- return;
321
- }
322
- const parsedUrl = url.parse(req.url, true);
323
- res.setHeader(
324
- "Cache-Control",
325
- "no-cache, max-age=0, must-revalidate, no-store"
326
- );
327
- res.setHeader("Pragma", "no-cache");
328
- res.setHeader("Expires", "-1");
329
- try {
330
- if (parsedUrl.path?.includes("static/") && !parsedUrl.path.includes("_next/static/")) {
331
- void serveStaticFile(res, parsedUrl, staticBaseDirRelativePath);
332
- } else if (!isNextReady) {
333
- void nextReadyPromise.then(
334
- () => nextHandleRequest?.(req, res, parsedUrl)
335
- );
336
- } else {
337
- void nextHandleRequest?.(req, res, parsedUrl);
338
- }
339
- } catch (e) {
340
- console.error("caught error", e);
341
- res.writeHead(500);
342
- res.end();
343
- }
344
- });
345
- const { portAlreadyInUse } = await safeAsyncServerListen(devServer, port);
346
- if (!portAlreadyInUse) {
347
- console.log(chalk.greenBright(` React Email ${package_default.version}`));
348
- console.log(` Running preview at: http://localhost:${port}
349
- `);
350
- } else {
351
- const nextPortToTry = port + 1;
352
- console.warn(
353
- ` ${logSymbols2.warning} Port ${port} is already in use, trying ${nextPortToTry}`
354
- );
355
- return startDevServer(
356
- emailsDirRelativePath,
357
- staticBaseDirRelativePath,
358
- nextPortToTry
359
- );
360
- }
361
- devServer.on("close", async () => {
362
- await app.close();
363
- });
364
- devServer.on("error", (e) => {
365
- spinner.stopAndPersist({
366
- symbol: logSymbols2.error,
367
- text: `Preview Server had an error: ${e}`
368
- });
369
- process.exit(1);
370
- });
371
- const spinner = ora({
372
- text: "Getting react-email preview server ready...\n",
373
- prefixText: " "
374
- }).start();
375
- registerSpinnerAutostopping(spinner);
376
- const timeBeforeNextReady = performance.now();
377
- process.env = {
378
- NODE_ENV: "development",
379
- ...process.env,
380
- ...getEnvVariablesForPreviewApp(
381
- // If we don't do normalization here, stuff like https://github.com/resend/react-email/issues/1354 happens.
382
- path4.normalize(emailsDirRelativePath),
383
- process.cwd()
384
- )
385
- };
386
- const app = next({
387
- // passing in env here does not get the environment variables there
388
- dev: isDev,
389
- conf: {
390
- images: {
391
- // This is to avoid the warning with sharp
392
- unoptimized: true
393
- }
394
- },
395
- hostname: "localhost",
396
- port,
397
- dir: previewServerLocation
398
- });
399
- let isNextReady = false;
400
- const nextReadyPromise = app.prepare();
401
- try {
402
- await nextReadyPromise;
403
- } catch (exception) {
404
- spinner.stopAndPersist({
405
- symbol: logSymbols2.error,
406
- text: ` Preview Server had an error: ${exception}`
407
- });
408
- process.exit(1);
409
- }
410
- isNextReady = true;
411
- const nextHandleRequest = app.getRequestHandler();
412
- const secondsToNextReady = ((performance.now() - timeBeforeNextReady) / 1e3).toFixed(1);
413
- spinner.stopAndPersist({
414
- text: `Ready in ${secondsToNextReady}s
415
- `,
416
- symbol: logSymbols2.success
417
- });
418
- return devServer;
419
- };
420
- var makeExitHandler = (options) => (_codeOrSignal) => {
421
- if (typeof devServer !== "undefined") {
422
- console.log("\n shutting down dev server");
423
- devServer.close();
424
- devServer = void 0;
425
- }
426
- if (options?.shouldKillProcess) {
427
- process.exit(options.killWithErrorCode ? 1 : 0);
428
- }
429
- };
430
- process.on("exit", makeExitHandler());
431
- process.on(
432
- "SIGINT",
433
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
434
- );
435
- process.on(
436
- "SIGUSR1",
437
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
438
- );
439
- process.on(
440
- "SIGUSR2",
441
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: false })
442
- );
443
- process.on(
444
- "uncaughtException",
445
- makeExitHandler({ shouldKillProcess: true, killWithErrorCode: true })
446
- );
447
-
448
- // src/cli/utils/preview/hot-reloading/get-imported-modules.ts
449
- import { parse } from "@babel/parser";
450
- import traverseModule from "@babel/traverse";
451
- var traverse = (
452
- // we keep this check here so that this still works with the dev:preview
453
- // script's use of tsx
454
- typeof traverseModule === "function" ? traverseModule : (
455
- // @ts-expect-error This is fine since the default export is wrapped in a
456
- // default function. The problem is that babel/traverse is not ESM.
457
- traverseModule.default
458
- )
459
- );
460
- var getImportedModules = (contents) => {
461
- const importedPaths = [];
462
- const parsedContents = parse(contents, {
463
- sourceType: "unambiguous",
464
- strictMode: false,
465
- errorRecovery: true,
466
- plugins: ["jsx", "typescript", "decorators"]
467
- });
468
- traverse(parsedContents, {
469
- ImportDeclaration({ node }) {
470
- importedPaths.push(node.source.value);
471
- },
472
- ExportAllDeclaration({ node }) {
473
- importedPaths.push(node.source.value);
474
- },
475
- ExportNamedDeclaration({ node }) {
476
- if (node.source) {
477
- importedPaths.push(node.source.value);
478
- }
479
- },
480
- TSExternalModuleReference({ node }) {
481
- importedPaths.push(node.expression.value);
482
- },
483
- CallExpression({ node }) {
484
- if ("name" in node.callee && node.callee.name === "require") {
485
- if (node.arguments.length === 1) {
486
- const importPathNode = node.arguments[0];
487
- if (importPathNode.type === "StringLiteral") {
488
- importedPaths.push(importPathNode.value);
489
- }
490
- }
491
- }
492
- }
493
- });
494
- return importedPaths;
495
- };
496
-
497
- // src/cli/utils/preview/hot-reloading/resolve-path-aliases.ts
498
- import path5 from "node:path";
499
- import { createMatchPath, loadConfig } from "tsconfig-paths";
500
- var resolvePathAliases = (importPaths, projectPath) => {
501
- const configLoadResult = loadConfig(projectPath);
502
- if (configLoadResult.resultType === "success") {
503
- const matchPath = createMatchPath(
504
- configLoadResult.absoluteBaseUrl,
505
- configLoadResult.paths
506
- );
507
- return importPaths.map((importedPath) => {
508
- const unaliasedPath = matchPath(importedPath, void 0, void 0, [
509
- ".tsx",
510
- ".ts",
511
- ".js",
512
- ".jsx",
513
- ".cjs",
514
- ".mjs"
515
- ]);
516
- if (unaliasedPath) {
517
- return `./${path5.relative(projectPath, unaliasedPath)}`;
518
- }
519
- return importedPath;
520
- });
521
- }
522
- return importPaths;
523
- };
524
-
525
- // src/cli/utils/preview/hot-reloading/create-dependency-graph.ts
526
- var readAllFilesInsideDirectory = async (directory) => {
527
- let allFilePaths = [];
528
- const topLevelDirents = await fs3.readdir(directory, { withFileTypes: true });
529
- for await (const dirent of topLevelDirents) {
530
- const pathToDirent = path6.join(directory, dirent.name);
531
- if (dirent.isDirectory()) {
532
- allFilePaths = allFilePaths.concat(
533
- await readAllFilesInsideDirectory(pathToDirent)
534
- );
535
- } else {
536
- allFilePaths.push(pathToDirent);
537
- }
538
- }
539
- return allFilePaths;
540
- };
541
- var isJavascriptModule = (filePath) => {
542
- const extensionName = path6.extname(filePath);
543
- return [".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"].includes(extensionName);
544
- };
545
- var checkFileExtensionsUntilItExists = (pathWithoutExtension) => {
546
- if (existsSync2(`${pathWithoutExtension}.ts`)) {
547
- return `${pathWithoutExtension}.ts`;
548
- }
549
- if (existsSync2(`${pathWithoutExtension}.tsx`)) {
550
- return `${pathWithoutExtension}.tsx`;
551
- }
552
- if (existsSync2(`${pathWithoutExtension}.js`)) {
553
- return `${pathWithoutExtension}.js`;
554
- }
555
- if (existsSync2(`${pathWithoutExtension}.jsx`)) {
556
- return `${pathWithoutExtension}.jsx`;
557
- }
558
- if (existsSync2(`${pathWithoutExtension}.mjs`)) {
559
- return `${pathWithoutExtension}.mjs`;
560
- }
561
- if (existsSync2(`${pathWithoutExtension}.cjs`)) {
562
- return `${pathWithoutExtension}.cjs`;
563
- }
564
- };
565
- var createDependencyGraph = async (directory) => {
566
- const filePaths = await readAllFilesInsideDirectory(directory);
567
- const modulePaths = filePaths.filter(isJavascriptModule);
568
- const graph = Object.fromEntries(
569
- modulePaths.map((path13) => [
570
- path13,
571
- {
572
- path: path13,
573
- dependencyPaths: [],
574
- dependentPaths: [],
575
- moduleDependencies: []
576
- }
577
- ])
578
- );
579
- const getDependencyPaths = async (filePath) => {
580
- const contents = await fs3.readFile(filePath, "utf8");
581
- const importedPaths = isJavascriptModule(filePath) ? resolvePathAliases(getImportedModules(contents), path6.dirname(filePath)) : [];
582
- const importedPathsRelativeToDirectory = importedPaths.map(
583
- (dependencyPath) => {
584
- const isModulePath = !dependencyPath.startsWith(".");
585
- if (isModulePath || path6.isAbsolute(dependencyPath)) {
586
- return dependencyPath;
587
- }
588
- let pathToDependencyFromDirectory = path6.resolve(
589
- /*
590
- path.resolve resolves paths differently from what imports on javascript do.
591
-
592
- So if we wouldn't do this, for an email at "/path/to/email.tsx" with a dependency path of "./other-email"
593
- would end up going into /path/to/email.tsx/other-email instead of /path/to/other-email which is the
594
- one the import is meant to go to
595
- */
596
- path6.dirname(filePath),
597
- dependencyPath
598
- );
599
- let isDirectory = false;
600
- try {
601
- isDirectory = statSync(pathToDependencyFromDirectory).isDirectory();
602
- } catch (_) {
603
- }
604
- if (isDirectory) {
605
- const pathToSubDirectory = pathToDependencyFromDirectory;
606
- const pathWithExtension = checkFileExtensionsUntilItExists(
607
- `${pathToSubDirectory}/index`
608
- );
609
- if (pathWithExtension) {
610
- pathToDependencyFromDirectory = pathWithExtension;
611
- } else if (isDev) {
612
- console.warn(
613
- `Could not find index file for directory at ${pathToDependencyFromDirectory}. This is probably going to cause issues with both hot reloading and your code.`
614
- );
615
- }
616
- }
617
- const extension = path6.extname(pathToDependencyFromDirectory);
618
- const pathWithEnsuredExtension = (() => {
619
- if (extension.length > 0 && existsSync2(pathToDependencyFromDirectory)) {
620
- return pathToDependencyFromDirectory;
621
- }
622
- return checkFileExtensionsUntilItExists(
623
- pathToDependencyFromDirectory.replace(extension, "")
624
- );
625
- })();
626
- if (pathWithEnsuredExtension) {
627
- pathToDependencyFromDirectory = pathWithEnsuredExtension;
628
- } else if (isDev) {
629
- console.warn(
630
- `Could not find file at ${pathToDependencyFromDirectory}`
631
- );
632
- }
633
- return pathToDependencyFromDirectory;
634
- }
635
- );
636
- const moduleDependencies = importedPathsRelativeToDirectory.filter(
637
- (dependencyPath) => !dependencyPath.startsWith(".") && !path6.isAbsolute(dependencyPath)
638
- );
639
- const nonNodeModuleImportPathsRelativeToDirectory = importedPathsRelativeToDirectory.filter(
640
- (dependencyPath) => dependencyPath.startsWith(".") || path6.isAbsolute(dependencyPath)
641
- );
642
- return {
643
- dependencyPaths: nonNodeModuleImportPathsRelativeToDirectory,
644
- moduleDependencies
645
- };
646
- };
647
- const updateModuleDependenciesInGraph = async (moduleFilePath) => {
648
- if (graph[moduleFilePath] === void 0) {
649
- graph[moduleFilePath] = {
650
- path: moduleFilePath,
651
- dependencyPaths: [],
652
- dependentPaths: [],
653
- moduleDependencies: []
654
- };
655
- }
656
- const { moduleDependencies, dependencyPaths: newDependencyPaths } = await getDependencyPaths(moduleFilePath);
657
- graph[moduleFilePath].moduleDependencies = moduleDependencies;
658
- for (const dependencyPath of graph[moduleFilePath].dependencyPaths) {
659
- if (newDependencyPaths.includes(dependencyPath)) continue;
660
- const dependencyModule = graph[dependencyPath];
661
- if (dependencyModule !== void 0) {
662
- dependencyModule.dependentPaths = dependencyModule.dependentPaths.filter(
663
- (dependentPath) => dependentPath !== moduleFilePath
664
- );
665
- }
666
- }
667
- graph[moduleFilePath].dependencyPaths = newDependencyPaths;
668
- for await (const dependencyPath of newDependencyPaths) {
669
- if (graph[dependencyPath] === void 0) {
670
- await updateModuleDependenciesInGraph(dependencyPath);
671
- }
672
- const dependencyModule = graph[dependencyPath];
673
- if (dependencyModule === void 0) {
674
- throw new Error(
675
- `Loading the dependency path ${dependencyPath} did not initialize it at all. This is a bug in React Email.`
676
- );
677
- }
678
- if (!dependencyModule.dependentPaths.includes(moduleFilePath)) {
679
- dependencyModule.dependentPaths.push(moduleFilePath);
680
- }
681
- }
682
- };
683
- for (const filePath of modulePaths) {
684
- await updateModuleDependenciesInGraph(filePath);
685
- }
686
- const removeModuleFromGraph = (filePath) => {
687
- const module = graph[filePath];
688
- if (module) {
689
- for (const dependencyPath of module.dependencyPaths) {
690
- if (graph[dependencyPath]) {
691
- graph[dependencyPath].dependentPaths = graph[dependencyPath].dependentPaths.filter(
692
- (dependentPath) => dependentPath !== filePath
693
- );
694
- }
695
- }
696
- delete graph[filePath];
697
- }
698
- };
699
- return [
700
- graph,
701
- async (event, pathToModified) => {
702
- switch (event) {
703
- case "change":
704
- if (isJavascriptModule(pathToModified)) {
705
- await updateModuleDependenciesInGraph(pathToModified);
706
- }
707
- break;
708
- case "add":
709
- if (isJavascriptModule(pathToModified)) {
710
- await updateModuleDependenciesInGraph(pathToModified);
711
- }
712
- break;
713
- case "addDir": {
714
- const filesInsideAddedDirectory = await readAllFilesInsideDirectory(pathToModified);
715
- const modulesInsideAddedDirectory = filesInsideAddedDirectory.filter(isJavascriptModule);
716
- for await (const filePath of modulesInsideAddedDirectory) {
717
- await updateModuleDependenciesInGraph(filePath);
718
- }
719
- break;
720
- }
721
- case "unlink":
722
- if (isJavascriptModule(pathToModified)) {
723
- removeModuleFromGraph(pathToModified);
724
- }
725
- break;
726
- case "unlinkDir": {
727
- const filesInsideDeletedDirectory = await readAllFilesInsideDirectory(pathToModified);
728
- const modulesInsideDeletedDirectory = filesInsideDeletedDirectory.filter(isJavascriptModule);
729
- for await (const filePath of modulesInsideDeletedDirectory) {
730
- removeModuleFromGraph(filePath);
731
- }
732
- break;
733
- }
734
- }
735
- },
736
- {
737
- resolveDependentsOf: function resolveDependentsOf(pathToModule) {
738
- const moduleEntry = graph[pathToModule];
739
- const dependentPaths = [];
740
- if (moduleEntry) {
741
- for (const dependentPath of moduleEntry.dependentPaths) {
742
- const dependentsOfDependent = resolveDependentsOf(dependentPath);
743
- dependentPaths.push(...dependentsOfDependent);
744
- dependentPaths.push(dependentPath);
745
- }
746
- }
747
- return dependentPaths;
748
- }
749
- }
750
- ];
751
- };
752
-
753
- // src/cli/utils/preview/hot-reloading/setup-hot-reloading.ts
754
- var setupHotreloading = async (devServer2, emailDirRelativePath) => {
755
- let clients = [];
756
- const io = new SocketServer(devServer2);
757
- io.on("connection", (client) => {
758
- clients.push(client);
759
- client.on("disconnect", () => {
760
- clients = clients.filter((item) => item !== client);
761
- });
762
- });
763
- let changes = [];
764
- const reload = debounce(() => {
765
- clients.forEach((client) => {
766
- client.emit(
767
- "reload",
768
- changes.filter(
769
- (change) => (
770
- // Ensures only changes inside the emails directory are emitted
771
- path7.resolve(absolutePathToEmailsDirectory, change.filename).startsWith(absolutePathToEmailsDirectory)
772
- )
773
- )
774
- );
775
- });
776
- changes = [];
777
- }, 150);
778
- const absolutePathToEmailsDirectory = path7.resolve(
779
- process.cwd(),
780
- emailDirRelativePath
781
- );
782
- const [dependencyGraph, updateDependencyGraph, { resolveDependentsOf }] = await createDependencyGraph(absolutePathToEmailsDirectory);
783
- const watcher = watch("", {
784
- ignoreInitial: true,
785
- cwd: absolutePathToEmailsDirectory
786
- });
787
- const getFilesOutsideEmailsDirectory = () => Object.keys(dependencyGraph).filter(
788
- (p) => path7.relative(absolutePathToEmailsDirectory, p).startsWith("..")
789
- );
790
- let filesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
791
- for (const p of filesOutsideEmailsDirectory) {
792
- watcher.add(p);
793
- }
794
- const exit = async () => {
795
- await watcher.close();
796
- };
797
- process.on("SIGINT", exit);
798
- process.on("uncaughtException", exit);
799
- watcher.on("all", async (event, relativePathToChangeTarget) => {
800
- const file = relativePathToChangeTarget.split(path7.sep);
801
- if (file.length === 0) {
802
- return;
803
- }
804
- const pathToChangeTarget = path7.resolve(
805
- absolutePathToEmailsDirectory,
806
- relativePathToChangeTarget
807
- );
808
- await updateDependencyGraph(event, pathToChangeTarget);
809
- const newFilesOutsideEmailsDirectory = getFilesOutsideEmailsDirectory();
810
- for (const p of filesOutsideEmailsDirectory) {
811
- if (!newFilesOutsideEmailsDirectory.includes(p)) {
812
- watcher.unwatch(p);
813
- }
814
- }
815
- for (const p of newFilesOutsideEmailsDirectory) {
816
- if (!filesOutsideEmailsDirectory.includes(p)) {
817
- watcher.add(p);
818
- }
819
- }
820
- filesOutsideEmailsDirectory = newFilesOutsideEmailsDirectory;
821
- changes.push({
822
- event,
823
- filename: relativePathToChangeTarget
824
- });
825
- for (const dependentPath of resolveDependentsOf(pathToChangeTarget)) {
826
- changes.push({
827
- event: "change",
828
- filename: path7.relative(absolutePathToEmailsDirectory, dependentPath)
829
- });
830
- }
831
- reload();
832
- });
833
- return watcher;
834
- };
835
-
836
- // src/cli/utils/tree.ts
837
- import { promises as fs4 } from "node:fs";
838
- import os from "node:os";
839
- import path8 from "node:path";
840
- var SYMBOLS = {
841
- BRANCH: "\u251C\u2500\u2500 ",
842
- EMPTY: "",
843
- INDENT: " ",
844
- LAST_BRANCH: "\u2514\u2500\u2500 ",
845
- VERTICAL: "\u2502 "
846
- };
847
- var getTreeLines = async (dirPath, depth, currentDepth = 0) => {
848
- const base = process.cwd();
849
- const dirFullpath = path8.resolve(base, dirPath);
850
- const dirname2 = path8.basename(dirFullpath);
851
- let lines = [dirname2];
852
- const dirStat = await fs4.stat(dirFullpath);
853
- if (dirStat.isDirectory() && currentDepth < depth) {
854
- const childDirents = await fs4.readdir(dirFullpath, { withFileTypes: true });
855
- childDirents.sort((a, b) => {
856
- if (a.isDirectory() && b.isFile()) {
857
- return -1;
858
- }
859
- if (a.isFile() && b.isDirectory()) {
860
- return 1;
861
- }
862
- return b.name > a.name ? -1 : 1;
863
- });
864
- for (let i = 0; i < childDirents.length; i++) {
865
- const dirent = childDirents[i];
866
- const isLast = i === childDirents.length - 1;
867
- const branchingSymbol = isLast ? SYMBOLS.LAST_BRANCH : SYMBOLS.BRANCH;
868
- const verticalSymbol = isLast ? SYMBOLS.INDENT : SYMBOLS.VERTICAL;
869
- if (dirent.isFile()) {
870
- lines.push(`${branchingSymbol}${dirent.name}`);
871
- } else {
872
- const pathToDirectory = path8.join(dirFullpath, dirent.name);
873
- const treeLinesForSubDirectory = await getTreeLines(
874
- pathToDirectory,
875
- depth,
876
- currentDepth + 1
877
- );
878
- lines = lines.concat(
879
- treeLinesForSubDirectory.map(
880
- (line, index) => index === 0 ? `${branchingSymbol}${line}` : `${verticalSymbol}${line}`
881
- )
882
- );
883
- }
884
- }
885
- }
886
- return lines;
887
- };
888
- var tree = async (dirPath, depth) => {
889
- const lines = await getTreeLines(dirPath, depth);
890
- return lines.join(os.EOL);
891
- };
892
-
893
- // src/cli/commands/build.ts
894
- var buildPreviewApp = (absoluteDirectory) => {
895
- return new Promise((resolve, reject) => {
896
- const nextBuild = spawn("npm", ["run", "build"], {
897
- cwd: absoluteDirectory,
898
- shell: true
899
- });
900
- nextBuild.stdout.pipe(process.stdout);
901
- nextBuild.stderr.pipe(process.stderr);
902
- nextBuild.on("close", (code) => {
903
- if (code === 0) {
904
- resolve();
905
- } else {
906
- reject(
907
- new Error(
908
- `Unable to build the Next app and it exited with code: ${code}`
909
- )
910
- );
911
- }
912
- });
913
- });
914
- };
915
- var setNextEnvironmentVariablesForBuild = async (emailsDirRelativePath, builtPreviewAppPath) => {
916
- const nextConfigContents = `
917
- const path = require('path');
918
- const emailsDirRelativePath = path.normalize('${emailsDirRelativePath}');
919
- const userProjectLocation = path.resolve(process.cwd(), '../');
920
- /** @type {import('next').NextConfig} */
921
- module.exports = {
922
- env: {
923
- NEXT_PUBLIC_IS_BUILDING: 'true',
924
- EMAILS_DIR_RELATIVE_PATH: emailsDirRelativePath,
925
- EMAILS_DIR_ABSOLUTE_PATH: path.resolve(userProjectLocation, emailsDirRelativePath),
926
- USER_PROJECT_LOCATION: userProjectLocation
927
- },
928
- // this is needed so that the code for building emails works properly
929
- webpack: (
930
- /** @type {import('webpack').Configuration & { externals: string[] }} */
931
- config,
932
- { isServer }
933
- ) => {
934
- if (isServer) {
935
- config.externals.push('esbuild');
936
- }
937
-
938
- return config;
939
- },
940
- typescript: {
941
- ignoreBuildErrors: true
942
- },
943
- eslint: {
944
- ignoreDuringBuilds: true
945
- },
946
- experimental: {
947
- webpackBuildWorker: true
948
- },
949
- }`;
950
- await fs5.promises.writeFile(
951
- path9.resolve(builtPreviewAppPath, "./next.config.js"),
952
- nextConfigContents,
953
- "utf8"
954
- );
955
- };
956
- var getEmailSlugsFromEmailDirectory = (emailDirectory, emailsDirectoryAbsolutePath) => {
957
- const directoryPathRelativeToEmailsDirectory = emailDirectory.absolutePath.replace(emailsDirectoryAbsolutePath, "").trim();
958
- const slugs = [];
959
- emailDirectory.emailFilenames.forEach(
960
- (filename3) => slugs.push(
961
- path9.join(directoryPathRelativeToEmailsDirectory, filename3).split(path9.sep).filter((segment) => segment.length > 0)
962
- )
963
- );
964
- emailDirectory.subDirectories.forEach((directory) => {
965
- slugs.push(
966
- ...getEmailSlugsFromEmailDirectory(
967
- directory,
968
- emailsDirectoryAbsolutePath
969
- )
970
- );
971
- });
972
- return slugs;
973
- };
974
- var forceSSGForEmailPreviews = async (emailsDirPath, builtPreviewAppPath) => {
975
- const emailDirectoryMetadata = (
976
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
977
- await getEmailsDirectoryMetadata(emailsDirPath)
978
- );
979
- const parameters = getEmailSlugsFromEmailDirectory(
980
- emailDirectoryMetadata,
981
- emailsDirPath
982
- ).map((slug) => ({ slug }));
983
- const removeForceDynamic = async (filePath) => {
984
- const contents = await fs5.promises.readFile(filePath, "utf8");
985
- await fs5.promises.writeFile(
986
- filePath,
987
- contents.replace("export const dynamic = 'force-dynamic';", ""),
988
- "utf8"
989
- );
990
- };
991
- await removeForceDynamic(
992
- path9.resolve(builtPreviewAppPath, "./src/app/layout.tsx")
993
- );
994
- await removeForceDynamic(
995
- path9.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx")
996
- );
997
- await fs5.promises.appendFile(
998
- path9.resolve(builtPreviewAppPath, "./src/app/preview/[...slug]/page.tsx"),
999
- `
1000
-
1001
- export function generateStaticParams() {
1002
- return Promise.resolve(
1003
- ${JSON.stringify(parameters)}
1004
- );
1005
- }`,
1006
- "utf8"
1007
- );
1008
- };
1009
- var updatePackageJson = async (builtPreviewAppPath) => {
1010
- const packageJsonPath = path9.resolve(builtPreviewAppPath, "./package.json");
1011
- const packageJson = JSON.parse(
1012
- await fs5.promises.readFile(packageJsonPath, "utf8")
1013
- );
1014
- packageJson.scripts.build = "next build";
1015
- packageJson.scripts.start = "next start";
1016
- packageJson.name = "preview-server";
1017
- delete packageJson.devDependencies["@react-email/render"];
1018
- delete packageJson.devDependencies["@react-email/components"];
1019
- delete packageJson.scripts.prepare;
1020
- await fs5.promises.writeFile(
1021
- packageJsonPath,
1022
- JSON.stringify(packageJson),
1023
- "utf8"
1024
- );
1025
- };
1026
- var npmInstall = async (builtPreviewAppPath, packageManager) => {
1027
- return new Promise((resolve, reject) => {
1028
- const childProc = spawn(
1029
- packageManager,
1030
- [
1031
- "install",
1032
- packageManager === "deno" ? "" : "--include=dev",
1033
- packageManager === "deno" ? "--quiet" : "--silent"
1034
- ],
1035
- {
1036
- cwd: builtPreviewAppPath,
1037
- shell: true
1038
- }
1039
- );
1040
- childProc.stdout.pipe(process.stdout);
1041
- childProc.stderr.pipe(process.stderr);
1042
- childProc.on("close", (code) => {
1043
- if (code === 0) {
1044
- resolve();
1045
- } else {
1046
- reject(
1047
- new Error(
1048
- `Unable to install the dependencies and it exited with code: ${code}`
1049
- )
1050
- );
1051
- }
1052
- });
1053
- });
1054
- };
1055
- var build = async ({
1056
- dir: emailsDirRelativePath,
1057
- packageManager
1058
- }) => {
1059
- try {
1060
- const spinner = ora2({
1061
- text: "Starting build process...",
1062
- prefixText: " "
1063
- }).start();
1064
- registerSpinnerAutostopping(spinner);
1065
- spinner.text = `Checking if ${emailsDirRelativePath} folder exists`;
1066
- if (!fs5.existsSync(emailsDirRelativePath)) {
1067
- process.exit(1);
1068
- }
1069
- const emailsDirPath = path9.join(process.cwd(), emailsDirRelativePath);
1070
- const staticPath = path9.join(emailsDirPath, "static");
1071
- const builtPreviewAppPath = path9.join(process.cwd(), ".react-email");
1072
- if (fs5.existsSync(builtPreviewAppPath)) {
1073
- spinner.text = "Deleting pre-existing `.react-email` folder";
1074
- await fs5.promises.rm(builtPreviewAppPath, { recursive: true });
1075
- }
1076
- spinner.text = "Copying preview app from CLI to `.react-email`";
1077
- await fs5.promises.cp(cliPackageLocation, builtPreviewAppPath, {
1078
- recursive: true,
1079
- filter: (source) => {
1080
- return !/(\/|\\)cli(\/|\\)?/.test(source) && !/(\/|\\)\.next(\/|\\)?/.test(source) && !/(\/|\\)\.turbo(\/|\\)?/.test(source) && !/(\/|\\)node_modules(\/|\\)?$/.test(source);
1081
- }
1082
- });
1083
- if (fs5.existsSync(staticPath)) {
1084
- spinner.text = "Copying `static` folder into `.react-email/public/static`";
1085
- const builtStaticDirectory = path9.resolve(
1086
- builtPreviewAppPath,
1087
- "./public/static"
1088
- );
1089
- await fs5.promises.cp(staticPath, builtStaticDirectory, {
1090
- recursive: true
1091
- });
1092
- }
1093
- spinner.text = "Setting Next environment variables for preview app to work properly";
1094
- await setNextEnvironmentVariablesForBuild(
1095
- emailsDirRelativePath,
1096
- builtPreviewAppPath
1097
- );
1098
- spinner.text = "Setting server side generation for the email preview pages";
1099
- await forceSSGForEmailPreviews(emailsDirPath, builtPreviewAppPath);
1100
- spinner.text = "Updating package.json's build and start scripts";
1101
- await updatePackageJson(builtPreviewAppPath);
1102
- spinner.text = "Installing dependencies on `.react-email`";
1103
- await npmInstall(builtPreviewAppPath, packageManager);
1104
- spinner.stopAndPersist({
1105
- text: "Successfully prepared `.react-email` for `next build`",
1106
- symbol: logSymbols3.success
1107
- });
1108
- await buildPreviewApp(builtPreviewAppPath);
1109
- } catch (error) {
1110
- console.log(error);
1111
- process.exit(1);
1112
- }
1113
- };
1114
-
1115
- // src/cli/commands/dev.ts
1116
- import fs6 from "node:fs";
1117
- var dev = async ({ dir: emailsDirRelativePath, port }) => {
1118
- try {
1119
- if (!fs6.existsSync(emailsDirRelativePath)) {
1120
- console.error(`Missing ${emailsDirRelativePath} folder`);
1121
- process.exit(1);
1122
- }
1123
- const devServer2 = await startDevServer(
1124
- emailsDirRelativePath,
1125
- emailsDirRelativePath,
1126
- // defaults to ./emails/static for the static files that are served to the preview
1127
- Number.parseInt(port)
1128
- );
1129
- await setupHotreloading(devServer2, emailsDirRelativePath);
1130
- } catch (error) {
1131
- console.log(error);
1132
- process.exit(1);
1133
- }
1134
- };
1135
-
1136
- // src/cli/commands/export.ts
1137
- import fs8, { unlinkSync, writeFileSync } from "node:fs";
1138
- import { createRequire } from "node:module";
1139
- import path11 from "node:path";
1140
- import url2 from "node:url";
1141
- import { build as build2 } from "esbuild";
1142
- import { glob } from "glob";
1143
- import logSymbols4 from "log-symbols";
1144
- import normalize from "normalize-path";
1145
- import ora3 from "ora";
1146
-
1147
- // src/utils/esbuild/renderring-utilities-exporter.ts
1148
- import { promises as fs7 } from "node:fs";
1149
- import path10 from "node:path";
1150
-
1151
- // src/utils/esbuild/escape-string-for-regex.ts
1152
- function escapeStringForRegex(string) {
1153
- return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
1154
- }
1155
-
1156
- // src/utils/esbuild/renderring-utilities-exporter.ts
1157
- var renderingUtilitiesExporter = (emailTemplates) => ({
1158
- name: "rendering-utilities-exporter",
1159
- setup: (b) => {
1160
- b.onLoad(
1161
- {
1162
- filter: new RegExp(
1163
- emailTemplates.map((emailPath) => escapeStringForRegex(emailPath)).join("|")
1164
- )
1165
- },
1166
- async ({ path: pathToFile }) => {
1167
- return {
1168
- contents: `${await fs7.readFile(pathToFile, "utf8")};
1169
- export { render } from 'react-email-module-that-will-export-render'
1170
- export { createElement as reactEmailCreateReactElement } from 'react';
1171
- `,
1172
- loader: path10.extname(pathToFile).slice(1)
1173
- };
1174
- }
1175
- );
1176
- b.onResolve(
1177
- { filter: /^react-email-module-that-will-export-render$/ },
1178
- async (args) => {
1179
- const options = {
1180
- kind: "import-statement",
1181
- importer: args.importer,
1182
- resolveDir: args.resolveDir,
1183
- namespace: args.namespace
1184
- };
1185
- let result = await b.resolve("@react-email/render", options);
1186
- if (result.errors.length === 0) {
1187
- return result;
1188
- }
1189
- result = await b.resolve("@react-email/components", options);
1190
- if (result.errors.length > 0 && result.errors[0]) {
1191
- result.errors[0].text = "Failed trying to import `render` from either `@react-email/render` or `@react-email/components` to be able to render your email template.\n Maybe you don't have either of them installed?";
1192
- }
1193
- return result;
1194
- }
1195
- );
1196
- }
1197
- });
1198
-
1199
- // src/cli/commands/export.ts
1200
- var getEmailTemplatesFromDirectory = (emailDirectory) => {
1201
- const templatePaths = [];
1202
- emailDirectory.emailFilenames.forEach(
1203
- (filename3) => templatePaths.push(path11.join(emailDirectory.absolutePath, filename3))
1204
- );
1205
- emailDirectory.subDirectories.forEach((directory) => {
1206
- templatePaths.push(...getEmailTemplatesFromDirectory(directory));
1207
- });
1208
- return templatePaths;
1209
- };
1210
- var filename2 = url2.fileURLToPath(import.meta.url);
1211
- var require2 = createRequire(filename2);
1212
- var exportTemplates = async (pathToWhereEmailMarkupShouldBeDumped, emailsDirectoryPath, options) => {
1213
- if (fs8.existsSync(pathToWhereEmailMarkupShouldBeDumped)) {
1214
- fs8.rmSync(pathToWhereEmailMarkupShouldBeDumped, { recursive: true });
1215
- }
1216
- let spinner;
1217
- if (!options.silent) {
1218
- spinner = ora3("Preparing files...\n").start();
1219
- registerSpinnerAutostopping(spinner);
1220
- }
1221
- const emailsDirectoryMetadata = await getEmailsDirectoryMetadata(
1222
- path11.resolve(process.cwd(), emailsDirectoryPath),
1223
- true
1224
- );
1225
- if (typeof emailsDirectoryMetadata === "undefined") {
1226
- if (spinner) {
1227
- spinner.stopAndPersist({
1228
- symbol: logSymbols4.error,
1229
- text: `Could not find the directory at ${emailsDirectoryPath}`
1230
- });
1231
- }
1232
- return;
1233
- }
1234
- const allTemplates = getEmailTemplatesFromDirectory(emailsDirectoryMetadata);
1235
- try {
1236
- await build2({
1237
- bundle: true,
1238
- entryPoints: allTemplates,
1239
- format: "cjs",
1240
- jsx: "transform",
1241
- loader: { ".js": "jsx" },
1242
- logLevel: "silent",
1243
- outExtension: { ".js": ".cjs" },
1244
- outdir: pathToWhereEmailMarkupShouldBeDumped,
1245
- platform: "node",
1246
- plugins: [renderingUtilitiesExporter(allTemplates)],
1247
- write: true
1248
- });
1249
- } catch (exception) {
1250
- if (spinner) {
1251
- spinner.stopAndPersist({
1252
- symbol: logSymbols4.error,
1253
- text: "Failed to build emails"
1254
- });
1255
- }
1256
- const buildFailure = exception;
1257
- console.error(`
1258
- ${buildFailure.message}`);
1259
- process.exit(1);
1260
- }
1261
- if (spinner) {
1262
- spinner.succeed();
1263
- }
1264
- const allBuiltTemplates = glob.sync(
1265
- normalize(`${pathToWhereEmailMarkupShouldBeDumped}/**/*.cjs`),
1266
- {
1267
- absolute: true
1268
- }
1269
- );
1270
- for await (const template of allBuiltTemplates) {
1271
- try {
1272
- if (spinner) {
1273
- spinner.text = `rendering ${template.split("/").pop()}`;
1274
- spinner.render();
1275
- }
1276
- delete require2.cache[template];
1277
- const emailModule = require2(template);
1278
- const rendered = await emailModule.render(
1279
- emailModule.reactEmailCreateReactElement(emailModule.default, {}),
1280
- options
1281
- );
1282
- const htmlPath = template.replace(
1283
- ".cjs",
1284
- options.plainText ? ".txt" : ".html"
1285
- );
1286
- writeFileSync(htmlPath, rendered);
1287
- unlinkSync(template);
1288
- } catch (exception) {
1289
- if (spinner) {
1290
- spinner.stopAndPersist({
1291
- symbol: logSymbols4.error,
1292
- text: `failed when rendering ${template.split("/").pop()}`
1293
- });
1294
- }
1295
- console.error(exception);
1296
- process.exit(1);
1297
- }
1298
- }
1299
- if (spinner) {
1300
- spinner.succeed("Rendered all files");
1301
- spinner.text = "Copying static files";
1302
- spinner.render();
1303
- }
1304
- const staticDirectoryPath = path11.join(emailsDirectoryPath, "static");
1305
- if (fs8.existsSync(staticDirectoryPath)) {
1306
- const pathToDumpStaticFilesInto = path11.join(
1307
- pathToWhereEmailMarkupShouldBeDumped,
1308
- "static"
1309
- );
1310
- if (fs8.existsSync(pathToDumpStaticFilesInto))
1311
- await fs8.promises.rm(pathToDumpStaticFilesInto, { recursive: true });
1312
- try {
1313
- await fs8.promises.cp(staticDirectoryPath, pathToDumpStaticFilesInto, {
1314
- recursive: true
1315
- });
1316
- } catch (exception) {
1317
- console.error(exception);
1318
- if (spinner) {
1319
- spinner.stopAndPersist({
1320
- symbol: logSymbols4.error,
1321
- text: "Failed to copy static files"
1322
- });
1323
- }
1324
- console.error(
1325
- `Something went wrong while copying the file to ${pathToWhereEmailMarkupShouldBeDumped}/static, ${exception}`
1326
- );
1327
- process.exit(1);
1328
- }
1329
- }
1330
- if (spinner && !options.silent) {
1331
- spinner.succeed();
1332
- const fileTree = await tree(pathToWhereEmailMarkupShouldBeDumped, 4);
1333
- console.log(fileTree);
1334
- spinner.stopAndPersist({
1335
- symbol: logSymbols4.success,
1336
- text: "Successfully exported emails"
1337
- });
1338
- }
1339
- };
1340
-
1341
- // src/cli/commands/start.ts
1342
- import { spawn as spawn2 } from "node:child_process";
1343
- import fs9 from "node:fs";
1344
- import path12 from "node:path";
1345
- var start = async () => {
1346
- try {
1347
- const usersProjectLocation = process.cwd();
1348
- const builtPreviewPath = path12.resolve(
1349
- usersProjectLocation,
1350
- "./.react-email"
1351
- );
1352
- if (!fs9.existsSync(builtPreviewPath)) {
1353
- console.error(
1354
- "Could not find .react-email, maybe you haven't ran email build?"
1355
- );
1356
- process.exit(1);
1357
- }
1358
- const nextStart = spawn2("npm", ["start"], {
1359
- cwd: builtPreviewPath,
1360
- stdio: "inherit"
1361
- });
1362
- process.on("SIGINT", () => {
1363
- nextStart.kill("SIGINT");
1364
- });
1365
- nextStart.on("exit", (code) => {
1366
- process.exit(code ?? 0);
1367
- });
1368
- } catch (error) {
1369
- console.log(error);
1370
- process.exit(1);
1371
- }
1372
- };
1373
-
1374
- // src/cli/index.ts
1375
- var PACKAGE_NAME = "react-email";
1376
- program.name(PACKAGE_NAME).description("A live preview of your emails right in your browser").version(package_default.version);
1377
- program.command("dev").description("Starts the preview email development app").option("-d, --dir <path>", "Directory with your email templates", "./emails").option("-p --port <port>", "Port to run dev server on", "3000").action(dev);
1378
- program.command("build").description("Copies the preview app for onto .react-email and builds it").option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
1379
- "-p --packageManager <name>",
1380
- "Package name to use on installation on `.react-email`",
1381
- "npm"
1382
- ).action(build);
1383
- program.command("start").description('Runs the built preview app that is inside of ".react-email"').action(start);
1384
- program.command("export").description("Build the templates to the `out` directory").option("--outDir <path>", "Output directory", "out").option("-p, --pretty", "Pretty print the output", false).option("-t, --plainText", "Set output format as plain text", false).option("-d, --dir <path>", "Directory with your email templates", "./emails").option(
1385
- "-s, --silent",
1386
- "To, or not to show a spinner with process information",
1387
- false
1388
- ).action(
1389
- ({ outDir, pretty, plainText, silent, dir: srcDir }) => exportTemplates(outDir, srcDir, { silent, plainText, pretty })
1390
- );
1391
- program.parse();