-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmicrosite-dev.ts
282 lines (253 loc) · 9.18 KB
/
microsite-dev.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import { startDevServer } from "snowpack";
import arg from "arg";
import { join, resolve, extname } from "path";
import type { IncomingMessage, ServerResponse } from "http";
import { green, dim } from "kleur/colors";
import polka from "polka";
import { openInBrowser } from "../utils/open.js";
import { readDir } from "../utils/fs.js";
import { promises as fsp } from "fs";
import { ErrorProps } from "error.js";
import { loadConfiguration } from "../utils/command.js";
const pageScript = (
page: string,
props?: any
) => `import { csr } from '/web_modules/microsite/client/csr.js';
import Page from '${page}';
csr("${page.replace(/\/src\/pages/, "").replace(/\.js$/, "")}", ${
props ? `Page, ${JSON.stringify(props)}` : `Page`
});`;
const errorScript = (
props: any
) => `import { h, render } from '/web_modules/preact.js';
import Page from '/web_modules/microsite/error.js';
const root = document.querySelector('#__microsite');
render(h(Page, ${JSON.stringify(props)}, null), root);`;
const globalScript = () => `(async () => {
try { await import('/src/global/index.css.proxy.js'); } catch (e) {}
try {
const global = await import('/src/global/index.js').then(mod => mod.default);
if (global) global();
} catch (e) {}
document.documentElement.style.removeProperty('visibility');
})()`;
const doc = (
page: string,
props?: any
) => `<!DOCTYPE html>\n<!-- Generated by microsite -->\n<html lang="en" dir="ltr" style="visibility:hidden">\n\t<head></head>\n\t<body>
\t\t<div id="__microsite"></div>
\t\t<script data-csr="true">window.HMR_WEBSOCKET_URL = 'ws://localhost:3333';</script>
\t\t<script type="module" src="/__snowpack__/hmr-client.js"></script>
\t\t<script type="module" data-microsite="page">${pageScript(
page,
props
)}</script>
\t\t<script type="module" data-microsite="global">${globalScript()}</script>
</body>\n</html>`;
const errorPage = (
props: any
) => `<!doctype html>\n<!-- Generated by microsite -->\n<html lang="en" dir="ltr">\n\t<head></head>\n\t<body>
\t\t<div id="__microsite"></div>
\t\t<script data-csr="true">window.HMR_WEBSOCKET_URL = 'ws://localhost:3333';</script>
\t\t<script type="module" src="/__snowpack__/hmr-client.js"></script>
\t\t<script type="module" data-microsite="page">${errorScript(props)}</script>
\t\t<script type="module" data-microsite="global">${globalScript()}</script>`;
const EXTS = [".js", ".jsx", ".ts", ".tsx", ".mjs"];
function parseArgs(argv: string[]) {
return arg(
{
"--port": Number,
"--no-open": Boolean,
// Aliases
"-p": "--port",
},
{ permissive: true, argv }
);
}
export default async function dev(argvOrParsedArgs: string[]|ReturnType<typeof parseArgs>) {
const cwd = process.cwd();
const args = Array.isArray(argvOrParsedArgs) ? parseArgs(argvOrParsedArgs) : argvOrParsedArgs;
let PORT = args["--port"] ?? 8888;
const [errs, config] = await loadConfiguration('dev');
if (errs) {
errs.forEach((err) => console.error(err));
return;
}
const snowpack = await startDevServer({
cwd: process.cwd(),
config,
lockfile: null,
});
const loadErrorPage = async (contentType: string, props?: ErrorProps) => {
try {
const url = `/src/pages/_error.js`;
const result = await snowpack.loadUrl(url);
if (!result) throw new Error();
if (contentType === "text/html")
return doc("/src/pages/_error.js", props);
if (contentType === "application/javascript")
return result.contents.toString();
} catch (e) {}
try {
const url = `/web_modules/microsite/error.js`;
const result = await snowpack.loadUrl(url);
if (!result) throw new Error();
if (contentType === "text/html") return errorPage(props);
if (contentType === "application/javascript")
return result.contents.toString();
} catch (e) {}
return null;
};
const sendErr = async (res: ServerResponse, props?: ErrorProps) => {
const contents = await loadErrorPage("text/html", props);
res.writeHead(props.statusCode ?? 500, {
"Content-Type": "text/html",
});
res.end(contents);
};
const server = polka()
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (req.url?.endsWith(".js")) {
res.setHeader("Content-Type", "application/javascript");
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (req.url === "/") return next();
const clean = /(\.html|index\.html|index|\/)$/;
if (clean.test(req.url ?? "")) {
res.writeHead(302, {
Location: req.url?.replace(clean, ""),
});
res.end();
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (req.url?.indexOf("microsite") > -1) {
if (req.url.endsWith("_error.js")) {
const contents = await loadErrorPage("application/javascript");
res.setHeader("Content-Type", "application/javascript");
res.end(contents);
} else {
req.url.replace("_microsite", "microsite");
}
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
if (!(req.url.endsWith(".html") || req.url.indexOf(".") === -1))
return next();
let base = req.url.slice(1);
if (base.endsWith(".html")) base = base.slice(0, ".html".length * -1);
if (base === "") base = "index";
const loadAndSSR = async (base: string) => {
try {
const url = `/src/pages/${base}.js`;
const result = await snowpack.loadUrl(url, { isSSR: true });
if (!result) throw new Error();
res.setHeader("Content-Type", "text/html");
res.end(doc(url));
return true;
} catch (err) {
// console.error(err);
}
return false;
};
const findPotentialMatch = async (base: string) => {
const baseParts = [...base.split("/"), "index"];
const pages = join(cwd, "src", "pages");
let files = await readDir(pages);
files = files
.filter((file: string) => EXTS.includes(extname(file)))
.map((file: string) =>
file.slice(pages.length, extname(file).length * -1)
)
.filter((file: string) => {
if (file.indexOf("[") === -1) return false;
const parts = file.slice(1).split("/");
if (parts.length === baseParts.length - 1)
return parts.every((part, i) =>
part.indexOf("[") > -1 ? true : part === baseParts[i]
);
if (parts.length === baseParts.length)
return parts.every((part, i) =>
part.indexOf("[") > -1 ? true : part === baseParts[i]
);
if (file.indexOf("[[") > -1)
return parts.every((part, i) => {
if (part.indexOf("[[")) return i === parts.length - 1;
if (part.indexOf("[")) return true;
return part === baseParts[i];
});
});
if (files.length === 0) return null;
if (files.length === 1) return files[0].slice(1);
if (files.length > 1) {
// TODO: rank direct matches above catch-all routes
// console.log(files);
return files[0];
}
};
const direct = await loadAndSSR(base);
if (direct) {
return next();
}
const index = await loadAndSSR(`${base}/index`);
if (index) {
return next();
}
const dynamic = await findPotentialMatch(base);
if (dynamic) {
await loadAndSSR(dynamic);
}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
try {
// Respond directly if asset is found
const result = await snowpack.loadUrl(req.url);
if (result.contentType)
res.setHeader("Content-Type", result.contentType);
if (req.url.indexOf("/web_modules/microsite") === -1) {
result.contents = result.contents
.toString()
.replace(/preact\/hooks/, "microsite/client/hooks");
}
return res.end(result.contents);
} catch (err) {}
next();
})
.use(async (req: IncomingMessage, res: ServerResponse, next: any) => {
try {
let localPath = resolve(cwd, `.${req.url}`);
const stats = await fsp.stat(localPath);
if (stats.isDirectory()) {
let contents = await readDir(localPath);
contents = contents.map((path) => path.slice(localPath.length));
res.setHeader("Content-Type", "application/json");
return res.end(JSON.stringify(contents));
}
} catch (err) {}
next();
})
.get("*", (_req: IncomingMessage, res: ServerResponse) =>
sendErr(res, { statusCode: 404 })
);
await new Promise<void>((resolve) =>
server.listen(PORT, (err) => {
if (err) throw err;
resolve();
})
);
let protocol = "http:";
let hostname = "localhost";
if (!args["--no-open"]) {
await openInBrowser(protocol, hostname, PORT, '/', "chrome");
}
console.log(
`${dim("[microsite]")} ${green("✔")} Microsite started on ${green(
`${protocol}//${hostname}:${PORT}`
)}\n`
);
}