-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
init.ts
396 lines (342 loc) · 9.42 KB
/
init.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import {
brightBlue,
green,
underline,
white,
yellow,
} from "https://deno.land/std@0.153.0/fmt/colors.ts";
import { dirname, join } from "https://deno.land/std@0.153.0/path/mod.ts";
import outdent from "https://deno.land/x/outdent@v0.8.0/mod.ts";
import { ensureDir } from "https://deno.land/std@0.153.0/fs/ensure_dir.ts";
type Dialect = "ts" | "js";
type TaskContext = {
cwd: string;
output: string;
overwrite?: boolean;
dialect: Dialect;
};
type TaskUtils = {
dialectFilename: (filename: string, isJsk?: boolean) => string;
};
async function execute(context: TaskContext, utils: TaskUtils) {
const tasks = taskQueue([
createFileTask("deno.json", denoConfigContent(utils)),
createFileTask("importMap.json", importMapContent()),
createFileTask(
utils.dialectFilename("build"),
buildContent(utils),
),
createFileTask(
utils.dialectFilename("server", true),
serverContent(utils),
),
createFileTask(
utils.dialectFilename("client", true),
clientContent(utils),
),
createFileTask(
utils.dialectFilename("src/app", true),
helloUltraContent(),
),
fetchFileTask(
"public/favicon.ico",
import.meta.resolve("./examples/basic/public/favicon.ico"),
),
fetchFileTask(
"public/robots.txt",
import.meta.resolve("./examples/basic/public/robots.txt"),
),
createFileTask(
"public/style.css",
styleContent(),
),
]);
for (const task of tasks) {
await task(context);
}
}
function createFileTask(path: string, content: string | Uint8Array) {
return async (context: TaskContext) => {
let overwritten = false;
path = join(context.cwd, context.output, path);
if (!context.overwrite && await exists(path)) {
const confirmed = await confirm(
yellow(
`DANG: A file at "${path}" already exists, do you want to overwrite it?`,
),
);
if (!confirmed) {
return Promise.resolve();
}
overwritten = true;
}
await ensureDir(dirname(path));
await Deno.writeFile(
path,
typeof content === "string" ? new TextEncoder().encode(content) : content,
);
if (!overwritten && !context.overwrite) {
console.log(`${green("✔️ Created:")} ${path}`);
} else {
console.log(`${yellow("✔️ Modifed:")} ${path}`);
}
};
}
function fetchFileTask(path: string, url: string) {
return async (context: TaskContext) => {
const response = await fetch(url);
const content = await response.arrayBuffer();
console.log(`${green("✔️ Fetched:")} ${url}`);
const createFile = createFileTask(
path,
new Uint8Array(content),
);
return createFile(context);
};
}
function* taskQueue(tasks: ((context: TaskContext) => Promise<void>)[]) {
let iterationCount = 0;
for (let i = 0; i < tasks.length; i++) {
iterationCount++;
yield tasks[i];
}
return iterationCount;
}
async function exists(filePath: string): Promise<boolean> {
try {
await Deno.lstat(filePath);
return true;
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return false;
}
throw err;
}
}
async function ask(question = ":", stdin = Deno.stdin, stdout = Deno.stdout) {
await stdout.write(new TextEncoder().encode(question + " "));
const buf = new Uint8Array(1024);
const n = <number> await stdin.read(buf);
const answer = new TextDecoder().decode(buf.subarray(0, n));
return answer.trim();
}
async function confirm(question = "Are you sure?") {
let a: string;
while (
!/^(y|n)$/i.test(a = (await ask(question + white(" [y/n]"))).trim())
// deno-lint-ignore no-empty
) {
}
return a.toLowerCase() === "y";
}
function resolveDialect(typescript: boolean) {
return typescript ? "ts" : "js";
}
function denoConfigContent(utils: TaskUtils) {
const serverEntrypoint = utils.dialectFilename("./server", true);
// deno-fmt-ignore
return outdent`
{
"tasks": {
"dev": "deno run -A --no-check --watch ${serverEntrypoint}",
"build": "deno run -A ./build.ts",
"start": "ULTRA_MODE=production deno run -A --no-remote ${serverEntrypoint}"
},
"compilerOptions": {
"jsx": "react-jsxdev",
"jsxImportSource": "react"
},
"importMap": "./importMap.json"
}
`;
}
function importMapContent() {
return outdent`
{
"imports": {
"react": "https://esm.sh/react@18.2.0",
"react/": "https://esm.sh/react@18.2.0/",
"react-dom": "https://esm.sh/react-dom@18.2.0",
"react-dom/": "https://esm.sh/react-dom@18.2.0/",
"ultra/": "${import.meta.url.replace("init.ts", "")}"
}
}
`;
}
function buildContent(utils: TaskUtils) {
const browserEntrypoint = utils.dialectFilename("./client", true);
const serverEntrypoint = utils.dialectFilename("./server", true);
// deno-fmt-ignore
return outdent`
import build from "ultra/build.ts";
await build({
browserEntrypoint: import.meta.resolve("${browserEntrypoint}"),
serverEntrypoint: import.meta.resolve("${serverEntrypoint}"),
});
`;
}
function serverContent(utils: TaskUtils) {
const browserEntrypoint = utils.dialectFilename("client", true);
const app = utils.dialectFilename("app", true);
// deno-fmt-ignore
return outdent`
import { serve } from "https://deno.land/std@0.153.0/http/server.ts";
import { createServer } from "ultra/server.ts";
import App from "./src/${app}";
const server = await createServer({
importMapPath: import.meta.resolve("./importMap.json"),
browserEntrypoint: import.meta.resolve("./${browserEntrypoint}"),
});
server.get("*", async (context) => {
/**
* Render the request
*/
const result = await server.render(<App />);
return context.body(result, 200, {
"content-type": "text/html",
});
});
serve(server.fetch);
`;
}
function clientContent(utils: TaskUtils) {
const app = utils.dialectFilename("app", true);
// deno-fmt-ignore
return outdent`
import { hydrateRoot } from "react-dom/client";
import App from "./src/${app}";
hydrateRoot(document, <App />);
`;
}
function styleContent() {
// deno-fmt-ignore
return outdent`
html,
body {
margin: 0;
padding: 1rem;
font-family: monospace;
background: #ddd;
text-align: center;
}
h1 {
text-align: center;
margin: 1rem auto 3rem;
font-size: clamp(2em, 10vw, 8em);
font-weight: 400;
}
h1 span::before {
content: '@';
animation: blink 3s infinite;
}
@keyframes blink {
0%,
50%,
70%,
95% {
content: '@';
}
65%,
90% {
content: '—';
}
}
p {
max-width: 600px;
margin: 0 auto 1em;
}
`;
}
function helloUltraContent() {
// deno-fmt-ignore
return outdent`
export default function App() {
console.log("Hello world!");
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<title>Ultra</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<main>
<h1>
<span></span>__<span></span>
</h1>
<p>
Welcome to{" "}
<strong>Ultra</strong>. This is a barebones starter for your web
app.
</p>
<p>
Take{" "}
<a
href="https://ultrajs.dev/docs"
target="_blank"
>
this
</a>, you may need it where you are going. It will show you how to
customise your routing, data fetching, and styling with popular
libraries.
</p>
</main>
</body>
</html>
);
}
`;
}
function dialectExtension(dialect: Dialect, isJsx?: boolean) {
switch (dialect) {
case "js":
return isJsx ? "jsx" : "js";
case "ts":
return isJsx ? "tsx" : "ts";
}
}
if (import.meta.main) {
// deno-fmt-ignore
console.log(outdent`
=== Welcome to Ultra ===\n
Let's get you setup with your new Ultra project.\n
But first, we need to ask just a few questions.\n
`);
let output = "";
while (output === "") {
output = await ask(
brightBlue("Where do you want to initialise your new project?"),
);
}
const typescript = await confirm(
brightBlue("Do you want to use TypeScript?"),
);
const dialect: Dialect = resolveDialect(typescript);
const context: TaskContext = {
cwd: Deno.cwd(),
output: output,
overwrite: false,
dialect,
};
const utils: TaskUtils = {
dialectFilename(filename: string, isJsx?: boolean) {
const extension = dialectExtension(dialect, isJsx);
return `${filename}.${extension}`;
},
};
const confirmed = await confirm(
brightBlue("Ready to go?"),
);
if (confirmed) {
console.log("\n");
await execute(context, utils);
// deno-fmt-ignore
console.log(outdent`
\n 🎉 BONZA! Your new Ultra project is ready, you can now cd into "${brightBlue(output)}" and run ${underline("deno task dev")} to get started!
`);
} else {
Deno.exit(0);
}
}