react-email 1.9.0 → 1.9.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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-email",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "A live preview of your emails right in your browser.",
5
5
  "bin": {
6
6
  "email": "./dist/source/index.js"
@@ -14,7 +14,7 @@ const downloadClient = async () => {
14
14
  const downloadRes = await octokit.repos.downloadTarballArchive({
15
15
  owner: 'resendlabs',
16
16
  repo: 'react-email',
17
- ref: 'v0.0.11',
17
+ ref: 'v0.0.12',
18
18
  });
19
19
  fs_1.default.mkdirSync('.react-email-temp');
20
20
  const TAR_PATH = path_1.default.join('.react-email-temp', 'react-email.tar.gz');
@@ -5,19 +5,47 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.buildProdServer = exports.startProdServer = exports.startDevServer = void 0;
7
7
  const shelljs_1 = __importDefault(require("shelljs"));
8
+ let processesToKill = [];
9
+ function execAsync(command) {
10
+ const process = shelljs_1.default.exec(command, { async: true });
11
+ processesToKill.push(process);
12
+ process.on('close', () => {
13
+ processesToKill = processesToKill.filter((p) => p !== process);
14
+ });
15
+ }
8
16
  const startDevServer = (packageManager, port) => {
9
- shelljs_1.default.exec(`${packageManager} run dev -- -p ${port}`, { async: true });
17
+ execAsync(`${packageManager} run dev -- -p ${port}`);
10
18
  };
11
19
  exports.startDevServer = startDevServer;
12
20
  const startProdServer = (packageManager, port) => {
13
- shelljs_1.default.exec(`${packageManager} run start -- -p ${port}`, { async: true });
21
+ execAsync(`${packageManager} run start -- -p ${port}`);
14
22
  };
15
23
  exports.startProdServer = startProdServer;
16
24
  const buildProdServer = (packageManager) => {
17
- const process = shelljs_1.default.exec(`${packageManager} run build`, { async: true });
25
+ execAsync(`${packageManager} run build`);
18
26
  // if build fails for whatever reason, make sure the shell actually exits
19
27
  process.on('close', (code) => {
20
28
  shelljs_1.default.exit(code ?? undefined);
21
29
  });
22
30
  };
23
31
  exports.buildProdServer = buildProdServer;
32
+ // based on https://stackoverflow.com/a/14032965
33
+ function exitHandler() {
34
+ if (processesToKill.length > 0) {
35
+ console.log('shutting down %d subprocesses', processesToKill.length);
36
+ }
37
+ processesToKill.forEach((p) => {
38
+ if (p.connected) {
39
+ p.kill();
40
+ }
41
+ });
42
+ }
43
+ // do something when app is closing
44
+ process.on('exit', exitHandler);
45
+ // catches ctrl+c event
46
+ process.on('SIGINT', exitHandler);
47
+ // catches "kill pid" (for example: nodemon restart)
48
+ process.on('SIGUSR1', exitHandler);
49
+ process.on('SIGUSR2', exitHandler);
50
+ // catches uncaught exceptions
51
+ process.on('uncaughtException', exitHandler);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-email",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "A live preview of your emails right in your browser.",
5
5
  "bin": {
6
6
  "email": "./dist/source/index.js"
@@ -0,0 +1,29 @@
1
+ import { downloadClient, REACT_EMAIL_ROOT } from '../utils';
2
+ import fs from 'fs';
3
+ import shell from 'shelljs';
4
+ import { setupServer } from '../utils/run-server';
5
+
6
+ interface Args {
7
+ dir: string;
8
+ port: string;
9
+ }
10
+
11
+ export const dev = async ({ dir, port }: Args) => {
12
+ try {
13
+ if (!fs.existsSync(dir)) {
14
+ throw new Error(`Missing ${dir} folder`);
15
+ }
16
+
17
+ if (fs.existsSync(REACT_EMAIL_ROOT)) {
18
+ await setupServer('dev', dir, port);
19
+ return;
20
+ }
21
+
22
+ await downloadClient();
23
+
24
+ await setupServer('dev', dir, port);
25
+ } catch (error) {
26
+ console.log(error);
27
+ shell.exit(1);
28
+ }
29
+ };
@@ -0,0 +1,73 @@
1
+ import { glob } from 'glob';
2
+ import esbuild from 'esbuild';
3
+ import tree from 'tree-node-cli';
4
+ import ora from 'ora';
5
+ import logSymbols from 'log-symbols';
6
+ import { render, Options } from '@react-email/render';
7
+ import { unlinkSync, writeFileSync } from 'fs';
8
+ import normalize from 'normalize-path';
9
+ import path from 'path';
10
+ import shell from 'shelljs';
11
+ import fs from 'fs';
12
+ /*
13
+ This first builds all the templates using esbuild and then puts the output in the `.js`
14
+ files. Then these `.js` files are imported dynamically and rendered to `.html` files
15
+ using the `render` function.
16
+ */
17
+ export const exportTemplates = async (
18
+ outDir: string,
19
+ srcDir: string,
20
+ options: Options,
21
+ ) => {
22
+ const spinner = ora('Preparing files...\n').start();
23
+ const allTemplates = glob.sync(normalize(path.join(srcDir, '*.{tsx,jsx}')));
24
+
25
+ esbuild.buildSync({
26
+ bundle: true,
27
+ entryPoints: allTemplates,
28
+ platform: 'node',
29
+ write: true,
30
+ outdir: outDir,
31
+ });
32
+
33
+ const allBuiltTemplates = glob.sync(normalize(`${outDir}/*.js`), {
34
+ absolute: true,
35
+ });
36
+
37
+ for (const template of allBuiltTemplates) {
38
+ const component = await import(template);
39
+ const rendered = render(component.default({}), options);
40
+ const htmlPath = template.replace(
41
+ '.js',
42
+ options.plainText ? '.txt' : '.html',
43
+ );
44
+ writeFileSync(htmlPath, rendered);
45
+ unlinkSync(template);
46
+ }
47
+
48
+ const staticDir = path.join(srcDir, 'static');
49
+ const hasStaticDirectory = fs.existsSync(staticDir);
50
+
51
+ if (hasStaticDirectory) {
52
+ const result = shell.cp('-r', staticDir, path.join(outDir, 'static'));
53
+ if (result.code > 0) {
54
+ throw new Error(
55
+ `Something went wrong while copying the file to ${outDir}/static, ${result.cat()}`,
56
+ );
57
+ }
58
+ }
59
+
60
+ const fileTree = tree(outDir, {
61
+ allFiles: true,
62
+ maxDepth: 4,
63
+ });
64
+
65
+ console.log(fileTree);
66
+
67
+ spinner.stopAndPersist({
68
+ symbol: logSymbols.success,
69
+ text: 'Successfully exported emails',
70
+ });
71
+
72
+ process.exit();
73
+ };
@@ -0,0 +1,44 @@
1
+ import fs from 'fs';
2
+ import shell from 'shelljs';
3
+ import { downloadClient, REACT_EMAIL_ROOT } from '../utils';
4
+ import { setupServer } from '../utils/run-server';
5
+
6
+ interface BuildPreviewArgs {
7
+ dir: string;
8
+ }
9
+
10
+ export const buildPreview = async ({ dir }: BuildPreviewArgs) => {
11
+ try {
12
+ if (fs.existsSync(REACT_EMAIL_ROOT)) {
13
+ await setupServer('build', dir, '');
14
+ return;
15
+ }
16
+
17
+ await downloadClient();
18
+
19
+ await setupServer('build', dir, '');
20
+ } catch (error) {
21
+ console.log(error);
22
+ shell.exit(1);
23
+ }
24
+ };
25
+
26
+ interface StartPreviewArgs {
27
+ port: string;
28
+ }
29
+
30
+ export const startPreview = async ({ port }: StartPreviewArgs) => {
31
+ try {
32
+ if (fs.existsSync(REACT_EMAIL_ROOT)) {
33
+ await setupServer('start', '', port);
34
+ return;
35
+ }
36
+
37
+ await downloadClient();
38
+
39
+ await setupServer('start', '', port);
40
+ } catch (error) {
41
+ console.log(error);
42
+ shell.exit(1);
43
+ }
44
+ };
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ import { program } from '@commander-js/extra-typings';
3
+ import { dev } from './commands/dev';
4
+ import { buildPreview, startPreview } from './commands/preview';
5
+ import { exportTemplates } from './commands/export';
6
+ import { PACKAGE_NAME } from './utils/constants';
7
+ import packageJson from '../package.json';
8
+
9
+ program
10
+ .name(PACKAGE_NAME)
11
+ .description('A live preview of your emails right in your browser')
12
+ .version(packageJson.version);
13
+
14
+ program
15
+ .command('dev')
16
+ .description('Starts the application in development mode')
17
+ .option('-d, --dir <path>', 'Directory with your email templates', './emails')
18
+ .option('-p --port <port>', 'Port to run dev server on', '3000')
19
+ .action(dev);
20
+
21
+ program
22
+ .command('build')
23
+ .description('Builds a production preview app')
24
+ .option('-d, --dir <path>', 'Directory with your email templates', './emails')
25
+ .action(buildPreview);
26
+
27
+ program
28
+ .command('start')
29
+ .description('Starts the production build of the preview app')
30
+ .option('-p --port <port>', 'Port to run production server on', '3000')
31
+ .action(startPreview);
32
+
33
+ program
34
+ .command('export')
35
+ .description('Build the templates to the `out` directory')
36
+ .option('--outDir <path>', 'Output directory', 'out')
37
+ .option('-p, --pretty', 'Pretty print the output', false)
38
+ .option('-t, --plainText', 'Set output format as plain text', false)
39
+ .option('-d, --dir <path>', 'Directory with your email templates', './emails')
40
+ .action(({ outDir, pretty, plainText, dir: srcDir }) =>
41
+ exportTemplates(outDir, srcDir, { pretty, plainText }),
42
+ );
43
+
44
+ program.parse();
@@ -0,0 +1,25 @@
1
+ import path from 'path';
2
+
3
+ // Package variables
4
+ export const DEFAULT_EMAILS_DIRECTORY = 'emails';
5
+ export const PACKAGE_NAME = 'react-email';
6
+
7
+ // Default paths
8
+ export const CURRENT_PATH = process.cwd();
9
+
10
+ // User paths
11
+ export const USER_PACKAGE_JSON = path.join(CURRENT_PATH, 'package.json');
12
+ export const USER_STATIC_FILES = path.join(CURRENT_PATH, 'emails', 'static');
13
+
14
+ // React Email paths
15
+ export const REACT_EMAIL_ROOT = path.join(CURRENT_PATH, '.react-email');
16
+
17
+ // Events
18
+ export const EVENT_FILE_DELETED = 'unlink';
19
+
20
+ export const PACKAGE_EMAILS_PATH = path.join(
21
+ REACT_EMAIL_ROOT,
22
+ DEFAULT_EMAILS_DIRECTORY,
23
+ );
24
+
25
+ export const PACKAGE_PUBLIC_PATH = path.join(REACT_EMAIL_ROOT, 'public');
@@ -0,0 +1,4 @@
1
+ import path from 'path';
2
+
3
+ export const convertToAbsolutePath = (dir: string): string =>
4
+ path.isAbsolute(dir) ? dir : path.join(process.cwd(), dir);
@@ -0,0 +1,28 @@
1
+ import { Octokit } from '@octokit/rest';
2
+ import fse from 'fs-extra';
3
+ import fs from 'fs';
4
+ import shell from 'shelljs';
5
+ import path from 'path';
6
+
7
+ export const downloadClient = async () => {
8
+ const octokit = new Octokit();
9
+ const downloadRes = await octokit.repos.downloadTarballArchive({
10
+ owner: 'resendlabs',
11
+ repo: 'react-email',
12
+ ref: 'v0.0.12',
13
+ });
14
+ fs.mkdirSync('.react-email-temp');
15
+ const TAR_PATH = path.join('.react-email-temp', 'react-email.tar.gz');
16
+ fs.writeFileSync(TAR_PATH, Buffer.from(downloadRes.data as any));
17
+ shell.exec(
18
+ `tar -xzvf .react-email-temp/react-email.tar.gz -C .react-email-temp --strip-components 1`,
19
+ { silent: true },
20
+ );
21
+
22
+ fse.moveSync(
23
+ path.join('.react-email-temp', 'client'),
24
+ path.join('.react-email'),
25
+ );
26
+
27
+ fse.removeSync('.react-email-temp');
28
+ };
@@ -0,0 +1,63 @@
1
+ import logSymbols from 'log-symbols';
2
+ import { PACKAGE_EMAILS_PATH, PACKAGE_PUBLIC_PATH } from './constants';
3
+ import fs from 'fs';
4
+ import ora from 'ora';
5
+ import shell from 'shelljs';
6
+ import path from 'path';
7
+ import fse from 'fs-extra';
8
+
9
+ export const generateEmailsPreview = async (emailDir: string) => {
10
+ try {
11
+ const spinner = ora('Generating emails preview').start();
12
+
13
+ await createEmailPreviews(emailDir);
14
+ await createStaticFiles(emailDir);
15
+
16
+ spinner.stopAndPersist({
17
+ symbol: logSymbols.success,
18
+ text: 'Emails preview generated',
19
+ });
20
+ } catch (error) {
21
+ console.log({ error });
22
+ }
23
+ };
24
+
25
+ const createEmailPreviews = async (emailDir: string) => {
26
+ const hasEmailsDirectory = fs.existsSync(PACKAGE_EMAILS_PATH);
27
+
28
+ if (hasEmailsDirectory) {
29
+ await fs.promises.rm(PACKAGE_EMAILS_PATH, { recursive: true });
30
+ }
31
+
32
+ const result = shell.cp('-r', emailDir, PACKAGE_EMAILS_PATH);
33
+
34
+ if (result.code > 0) {
35
+ throw new Error(
36
+ `Something went wrong while copying the file to ${PACKAGE_EMAILS_PATH}, ${result.cat()}`,
37
+ );
38
+ }
39
+ };
40
+
41
+ const createStaticFiles = async (emailDir: string) => {
42
+ const hasPublicDirectory = fs.existsSync(PACKAGE_PUBLIC_PATH);
43
+
44
+ if (hasPublicDirectory) {
45
+ await fs.promises.rm(PACKAGE_PUBLIC_PATH, { recursive: true });
46
+ }
47
+
48
+ await fse.ensureDir(path.join(PACKAGE_PUBLIC_PATH, 'static'));
49
+
50
+ const result = shell.cp(
51
+ '-r',
52
+ path.join('static'),
53
+ path.join(PACKAGE_PUBLIC_PATH),
54
+ );
55
+ if (result.code > 0) {
56
+ throw new Error(
57
+ `Something went wrong while copying the file to ${path.join(
58
+ emailDir,
59
+ 'static',
60
+ )}, ${result.cat()}`,
61
+ );
62
+ }
63
+ };
@@ -0,0 +1,8 @@
1
+ export * from './constants';
2
+ export * from './convert-to-absolute-path';
3
+ export * from './download-client';
4
+ export * from './generate-email-preview';
5
+ export * from './install-dependencies';
6
+ export * from './start-server-command';
7
+ export * from './sync-package';
8
+ export * from './watcher';
@@ -0,0 +1,18 @@
1
+ import shell from 'shelljs';
2
+ import path from 'path';
3
+ import { REACT_EMAIL_ROOT } from './constants';
4
+ import ora from 'ora';
5
+ import logSymbols from 'log-symbols';
6
+
7
+ export type PackageManager = 'yarn' | 'npm' | 'pnpm';
8
+
9
+ export const installDependencies = async (packageManager: PackageManager) => {
10
+ const spinner = ora('Installing dependencies...\n').start();
11
+
12
+ shell.cd(path.join(REACT_EMAIL_ROOT));
13
+ shell.exec(`${packageManager} install`);
14
+ spinner.stopAndPersist({
15
+ symbol: logSymbols.success,
16
+ text: 'Dependencies installed',
17
+ });
18
+ };
@@ -0,0 +1,58 @@
1
+ import { createWatcherInstance, watcher } from './watcher';
2
+ import { detect as detectPackageManager } from 'detect-package-manager';
3
+ import { findRoot } from '@manypkg/find-root';
4
+ import {
5
+ CURRENT_PATH,
6
+ convertToAbsolutePath,
7
+ startDevServer,
8
+ installDependencies,
9
+ PackageManager,
10
+ syncPkg,
11
+ generateEmailsPreview,
12
+ buildProdServer,
13
+ startProdServer,
14
+ REACT_EMAIL_ROOT,
15
+ } from '.';
16
+ import path from 'path';
17
+ import shell from 'shelljs';
18
+
19
+ /**
20
+ * Utility function to run init/sync for the server in dev, build or start mode.
21
+ *
22
+ * @param type dev | build | start
23
+ * @param dir Directory in which the emails are located, only for dev and build, unused for start.
24
+ * @param port The port on which the server will run, only for dev and start, unused for build.
25
+ */
26
+ export const setupServer = async (
27
+ type: 'dev' | 'build' | 'start',
28
+ dir: string,
29
+ port: string,
30
+ ) => {
31
+ const cwd = await findRoot(CURRENT_PATH).catch(() => ({
32
+ rootDir: CURRENT_PATH,
33
+ }));
34
+ const emailDir = convertToAbsolutePath(dir);
35
+ const packageManager: PackageManager = await detectPackageManager({
36
+ cwd: cwd.rootDir,
37
+ }).catch(() => 'npm');
38
+
39
+ // when starting, we dont need to worry about these because it should've already happened during the build stage.
40
+ if (type !== 'start') {
41
+ await generateEmailsPreview(emailDir);
42
+ await syncPkg();
43
+ await installDependencies(packageManager);
44
+ }
45
+
46
+ if (type === 'dev') {
47
+ const watcherInstance = createWatcherInstance(emailDir);
48
+
49
+ startDevServer(packageManager, port);
50
+ watcher(watcherInstance, emailDir);
51
+ } else if (type === 'build') {
52
+ buildProdServer(packageManager);
53
+ } else {
54
+ shell.cd(path.join(REACT_EMAIL_ROOT));
55
+
56
+ startProdServer(packageManager, port);
57
+ }
58
+ };
@@ -0,0 +1,54 @@
1
+ import { ChildProcess } from 'child_process';
2
+ import shell from 'shelljs';
3
+
4
+ let processesToKill: ChildProcess[] = [];
5
+
6
+ function execAsync(command: string) {
7
+ const process = shell.exec(command, { async: true });
8
+ processesToKill.push(process);
9
+ process.on('close', () => {
10
+ processesToKill = processesToKill.filter((p) => p !== process);
11
+ });
12
+ }
13
+
14
+ export const startDevServer = (packageManager: string, port: string) => {
15
+ execAsync(`${packageManager} run dev -- -p ${port}`);
16
+ };
17
+
18
+ export const startProdServer = (packageManager: string, port: string) => {
19
+ execAsync(`${packageManager} run start -- -p ${port}`);
20
+ };
21
+
22
+ export const buildProdServer = (packageManager: string) => {
23
+ execAsync(`${packageManager} run build`);
24
+
25
+ // if build fails for whatever reason, make sure the shell actually exits
26
+ process.on('close', (code) => {
27
+ shell.exit(code ?? undefined);
28
+ });
29
+ };
30
+
31
+ // based on https://stackoverflow.com/a/14032965
32
+ function exitHandler() {
33
+ if (processesToKill.length > 0) {
34
+ console.log('shutting down %d subprocesses', processesToKill.length);
35
+ }
36
+ processesToKill.forEach((p) => {
37
+ if (p.connected) {
38
+ p.kill();
39
+ }
40
+ });
41
+ }
42
+
43
+ // do something when app is closing
44
+ process.on('exit', exitHandler);
45
+
46
+ // catches ctrl+c event
47
+ process.on('SIGINT', exitHandler);
48
+
49
+ // catches "kill pid" (for example: nodemon restart)
50
+ process.on('SIGUSR1', exitHandler);
51
+ process.on('SIGUSR2', exitHandler);
52
+
53
+ // catches uncaught exceptions
54
+ process.on('uncaughtException', exitHandler);
@@ -0,0 +1,20 @@
1
+ import readPackage from 'read-pkg';
2
+ import { REACT_EMAIL_ROOT } from './constants';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+
6
+ export const syncPkg = async () => {
7
+ const clientPkg = await readPackage({ cwd: REACT_EMAIL_ROOT });
8
+ const userPkg = await readPackage();
9
+ const pkg = {
10
+ ...clientPkg,
11
+ dependencies: {
12
+ ...clientPkg.dependencies,
13
+ ...userPkg.dependencies,
14
+ },
15
+ };
16
+ await fs.promises.writeFile(
17
+ path.join(REACT_EMAIL_ROOT, 'package.json'),
18
+ JSON.stringify(pkg),
19
+ );
20
+ };
@@ -0,0 +1,63 @@
1
+ import chokidar, { FSWatcher } from 'chokidar';
2
+ import {
3
+ EVENT_FILE_DELETED,
4
+ PACKAGE_EMAILS_PATH,
5
+ REACT_EMAIL_ROOT,
6
+ } from './constants';
7
+ import fs from 'fs';
8
+ import path from 'path';
9
+ import shell from 'shelljs';
10
+
11
+ export const createWatcherInstance = (watchDir: string) =>
12
+ chokidar.watch(watchDir, {
13
+ ignoreInitial: true,
14
+ cwd: watchDir.split(path.sep).slice(0, -1).join(path.sep),
15
+ ignored: /(^|[\/\\])\../,
16
+ });
17
+
18
+ export const watcher = (watcherInstance: FSWatcher, watchDir: string) => {
19
+ watcherInstance.on('all', async (event, filename) => {
20
+ const file = filename.split(path.sep);
21
+ if (file[1] === undefined) {
22
+ return;
23
+ }
24
+
25
+ if (event === EVENT_FILE_DELETED) {
26
+ if (file[1] === 'static' && file[2]) {
27
+ await fs.promises.rm(
28
+ path.join(REACT_EMAIL_ROOT, 'public', 'static', file[2]),
29
+ );
30
+ return;
31
+ }
32
+
33
+ await fs.promises.rm(path.join(REACT_EMAIL_ROOT, filename));
34
+ return;
35
+ }
36
+
37
+ if (file[1] === 'static' && file[2]) {
38
+ const srcPath = path.join(watchDir, 'static', file[2]);
39
+ const result = shell.cp(
40
+ '-r',
41
+ srcPath,
42
+ path.join(REACT_EMAIL_ROOT, 'public', 'static'),
43
+ );
44
+ if (result.code > 0) {
45
+ throw new Error(
46
+ `Something went wrong while copying the file to ${PACKAGE_EMAILS_PATH}, ${result.cat()}`,
47
+ );
48
+ }
49
+ return;
50
+ }
51
+
52
+ const result = shell.cp(
53
+ '-r',
54
+ path.join(watchDir, ...file.slice(1)),
55
+ path.join(PACKAGE_EMAILS_PATH, ...file.slice(1, -1)),
56
+ );
57
+ if (result.code > 0) {
58
+ throw new Error(
59
+ `Something went wrong while copying the file to ${PACKAGE_EMAILS_PATH}, ${result.cat()}`,
60
+ );
61
+ }
62
+ });
63
+ };