-
Notifications
You must be signed in to change notification settings - Fork 1
/
prerun.mjs
85 lines (72 loc) · 2.31 KB
/
prerun.mjs
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
import fs from 'fs';
import { findUp } from 'find-up';
import * as Dotenv from 'dotenv';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
const requiredEnvKeys = ['DOGU_RUN_TYPE', 'NEXT_PUBLIC_ENV'];
async function parseDotenv() {
const envFilePath = await findUp(`.env`);
if (envFilePath === undefined) {
const message = `.env file not found`;
console.error(`[prerun] ${message}`);
throw new Error(message);
}
const parsedEnv = Dotenv.config({ path: envFilePath }).parsed || {};
// compare env keys
const existKeys = Object.keys(parsedEnv);
const difference = requiredEnvKeys.filter((x) => !existKeys.includes(x));
if (difference.length > 0) {
throw new Error(
`[prerun] Env validation failed. ${difference.join()} should exist.`,
);
}
return parsedEnv;
}
function writeEnv(parsedEnv) {
const scriptFilePath = `${fs.realpathSync(process.cwd())}/public/__ENV.js`;
const content = `window.__ENV = ${JSON.stringify(parsedEnv)}`;
fs.writeFileSync(scriptFilePath, content);
console.info(
`[prerun] Write environment to ${scriptFilePath} content: ${content}`,
);
}
async function copyEnv(appEnv) {
const envFilePath = await findUp(`.env`);
const dotenvFilePath = `${fs.realpathSync(process.cwd())}/.env`;
fs.copyFileSync(envFilePath, dotenvFilePath);
}
async function writeRobotsText(runType) {
const robotsTxtFilePath = `${fs.realpathSync(
process.cwd(),
)}/public/robots.txt`;
const content =
runType === 'production'
? `User-agent: *\nAllow: /`
: `User-agent: *\nDisallow: /`;
fs.writeFileSync(robotsTxtFilePath, content);
console.info(
`[prerun] Write robots.txt to ${robotsTxtFilePath} content: ${content}`,
);
}
yargs(hideBin(process.argv))
.command(
'start',
'Create Next.js runtime environment js and write robots.txt',
function builder(y) {
return y.option('env', {
alias: 'e',
type: 'string',
description: 'Environment name(ex: production, development)',
});
},
async function handler(args) {
const appEnv = '';
console.info(`[env] App environment: ${appEnv}`);
const parsedEnv = await parseDotenv();
writeEnv(parsedEnv);
await copyEnv(appEnv);
writeRobotsText(parsedEnv.DOGU_RUN_TYPE);
return parsedEnv;
},
)
.parse();