-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathsetup.ts
231 lines (195 loc) · 6.64 KB
/
setup.ts
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
import { resolve, posix } from "path";
import { execSync } from "child_process";
import {
copy,
mkdir,
readdir,
remove,
rm,
writeFile,
readFile,
appendFile,
readJSONSync,
} from "fs-extra";
import { debug, log } from "../../../util/log";
import { build, BuildOptions } from "esbuild";
import { template } from "lodash";
import { getNodeModulesDirsFrom } from "../../util/getNodeModulesDirsFrom";
export const COMPONENT_FILE_REGEXP = /^[^\s-]+\.[tj]sx$/; // no spaces, .jsx or .tsx
export type PreviewServerOptions = {
emailsDir: string;
port: number;
quiet: boolean;
};
export async function linkEmailsDirectory(emailsDir: string) {
const dotMailingSrcPath = ".mailing/src";
const dynManifestPath = dotMailingSrcPath + "/moduleManifest.ts";
const dynFeManifestPath = dotMailingSrcPath + "/feManifest.ts";
const previewsPath = emailsDir + "/previews";
const previewCollections = (await readdir(previewsPath)).filter((path) =>
COMPONENT_FILE_REGEXP.test(path)
);
debug("scanning for previews at", previewsPath, previewCollections);
const uniquePreviewCollections = Array.from(new Set(previewCollections));
const previewImports: string[] = [];
const previewConsts: string[] = [];
// calculate the relative path the user's emailsDir
// so we can import templates and previews from there
// when in the context of the build output
const relativePathToEmailsDir = posix.relative(dotMailingSrcPath, emailsDir);
uniquePreviewCollections.forEach((p) => {
const moduleName = p.replace(/\.[jt]sx/g, "");
previewImports.push(
`import * as ${moduleName}Preview from "${
relativePathToEmailsDir + "/previews/" + moduleName
}";`
);
previewConsts.push(`${moduleName}: ${moduleName}Preview`);
});
let indexFound = false;
const emailsDirContents = await readdir(emailsDir);
const templates = emailsDirContents.filter((path) => {
if (/^index\.[jt]sx?$/.test(path)) {
indexFound = true; // index.ts, index.js
return false;
}
return COMPONENT_FILE_REGEXP.test(path);
});
if (!indexFound)
throw new Error("index.ts or index.js not found in emails directory");
const uniqueTemplates = Array.from(new Set(templates));
const templateImports: string[] = [];
const templateModuleNames: string[] = [];
uniqueTemplates.forEach((p) => {
const moduleName = p.replace(/\.[jt]sx/g, "");
templateModuleNames.push(moduleName);
templateImports.push(
`import ${moduleName} from "${
relativePathToEmailsDir + "/" + moduleName
}";`
);
});
const moduleManifestTemplate = template(
(
await readFile(
".mailing/src/commands/preview/server/templates/moduleManifest.template.ejs"
)
).toString()
);
const moduleManifestContents = moduleManifestTemplate({
relativePathToEmailsDir,
templateImports,
previewImports,
previewConsts,
templateModuleNames,
});
await writeFile(dynManifestPath, moduleManifestContents);
const feManifestContents = (
await readFile(
".mailing/src/commands/preview/server/templates/feModuleManifest.template.ejs"
)
).toString();
await writeFile(dynFeManifestPath, feManifestContents);
debug("writing module manifest to", dynManifestPath);
// build the module manifests
await buildManifest("node", dynManifestPath);
await buildManifest("browser", dynFeManifestPath);
}
export async function packageJsonVersionsMatch(): Promise<boolean> {
const mailingPackageJsonPath = "./.mailing/package.json";
let mailingPackageJsonVersion: string;
// read .mailing package.json
try {
const pkgJSON = readJSONSync(mailingPackageJsonPath);
mailingPackageJsonVersion = pkgJSON.version;
debug(".mailing version:\t", mailingPackageJsonVersion);
} catch (err: any) {
if ("ENOENT" === err?.code) {
// .mailing package.json doesn't exist
return false;
} else {
throw err;
}
}
const cliPackageJsonVersion = execSync("npx mailing --version")
.toString()
.trim();
debug("cli version:\t\t", cliPackageJsonVersion);
// compare versions and return early if the same
return cliPackageJsonVersion === mailingPackageJsonVersion;
}
export async function bootstrapMailingDir() {
const mailingPath = "./.mailing";
// return early if .mailing exists and version matches packages.json
if (await packageJsonVersionsMatch()) {
debug("versions match, returning");
return;
}
// copy node_modules mailing into .mailing
const nodeMailingPath = resolve(
process.env.MM_DEV ? __dirname + "/../../../.." : __dirname + "/.."
);
debug("versions do not match, copying .mailing from", nodeMailingPath);
await rm(mailingPath, { recursive: true, force: true });
await mkdir(mailingPath, { recursive: true });
await copy(nodeMailingPath, mailingPath, {
recursive: true,
dereference: true,
overwrite: true,
filter: (path) => {
return !/__test__|generator_templates|src\/index\.ts$|src\/dev\.js$|\.mailing$|\.next$|node_modules$|\/cypress$/.test(
path
);
},
});
// delete .mailing/src/emails after copying because we should be using the user's
// emailsDir, not the copied version (mostly for sanity)
await rm(mailingPath + "/src/emails", {
recursive: true,
force: true,
});
// add .mailing to .gitignore if it does not exist
try {
const ignored = (await readFile(".gitignore")).toString().split("\n");
if (ignored.includes(".mailing")) return;
log("adding .mailing to .gitignore");
await appendFile(".gitignore", "\n.mailing\n");
} catch (err: any) {
if ("ENOENT" === err?.code) {
log("adding .gitignore");
await writeFile(".gitignore", ".mailing\nnode_modules\n", { flag: "wx" });
} else {
throw err;
}
}
}
async function buildManifest(
buildType: "node" | "browser",
manifestPath: string
) {
const buildOutdir = ".mailing/src";
const buildOpts: BuildOptions = {
entryPoints: [manifestPath],
outdir: buildOutdir,
write: true,
bundle: true,
format: "esm",
jsx: "preserve",
external: getNodeModulesDirsFrom("."),
};
if ("node" === buildType) {
buildOpts.platform = "node";
buildOpts.target = "node12";
} else {
buildOpts.platform = "browser";
buildOpts.target = "esnext";
}
debug("invoking esbuild with buildOpts: ", JSON.stringify(buildOpts));
// build the manifest
debug(`bundling ${buildType} manifest for ${manifestPath}...`);
await build(buildOpts);
// delete the original .ts file so there is no confusion loading the bundled .js files
await remove(manifestPath);
delete require.cache[manifestPath];
debug(`bundled ${buildType} manifest for ${manifestPath} to ${buildOutdir}`);
}