-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvite.config.js
184 lines (155 loc) · 4.53 KB
/
vite.config.js
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
import { defineConfig, loadEnv } from 'vite';
import {
CloudFormationClient,
DescribeStacksCommand,
} from '@aws-sdk/client-cloudformation';
import { fromIni } from '@aws-sdk/credential-providers';
import react from '@vitejs/plugin-react-swc';
import generouted from '@generouted/react-router/plugin';
import environment from 'vite-plugin-environment';
import readline from 'readline';
import process from 'process';
import { writeFileSync } from 'fs';
const awsProfile = process.env.AWS_PROFILE;
const cloudFormationClient = new CloudFormationClient(clientConfig);
let clientConfig = {};
if (awsProfile) {
const credentialsProvider = fromIni({ profile: awsProfile });
clientConfig = { credentials: credentialsProvider };
}
// Chunk deps to reduce module size
const manualChunks = (path) =>
path.split('/').reverse()[
path.split('/').reverse().indexOf('node_modules') - 1
]; // just a hack to get the next path segment of the last node_modules in path
const fetchApiUrl = async () => {
try {
const { Stacks } = await cloudFormationClient.send(
new DescribeStacksCommand({ StackName: `AmazonIVSRTWebDemoStack` })
);
const [backendStack] = Stacks;
const outputs = backendStack.Outputs;
for (const output of outputs) {
const value = findValueBySubstring(
output,
'AmazonIVSRTWebDemoApiEndpoint'
);
if (value) return value;
}
} catch (err) {
throw new Error(err);
}
};
const validateApiUrl = async () => {
const validator = (response) => {
const startsWithHttps = response.startsWith('https://');
const endsWithSlash = response.at(-1) === '/';
return startsWithHttps && endsWithSlash;
};
const validationMessage =
'\nInvalid API URL provided. API URL must begin with `https://` and end with a `/`';
return await readUserInput(`Enter your backend API URL: `, {
validator,
validationMessage,
});
};
const initApiUrl = async () => {
let apiUrl = undefined;
try {
apiUrl = await fetchApiUrl();
} catch (err) {
const shouldContinue = await confirmAction(
`${err.message}.
\nCould not find a deployed backend.
\nDo you wish to manually set a backend API URL? [Y/n]`
);
if (!shouldContinue) {
throw new Error('Operation aborted by user.');
}
apiUrl = await validateApiUrl();
}
const shouldSave = await confirmAction(
`API URL: ${apiUrl}
\nDo you wish to save this API URL for future use? [Y/n]`
);
if (shouldSave) {
try {
const content = `API_URL=${apiUrl}`;
writeFileSync('./.env', content);
} catch (err) {
console.error('Failed to write file:', err);
}
}
};
// https://vitejs.dev/config/
export default defineConfig(async ({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
let apiUrl = env.API_URL || undefined;
if (apiUrl === undefined) {
await initApiUrl();
}
const plugins = [
react(),
generouted(),
environment({
API_URL: apiUrl,
}),
];
return {
build: {
sourcemap: false,
rollupOptions: {
output: { manualChunks },
},
},
plugins,
};
});
function findValueBySubstring(obj, substring) {
const values = Object.values(obj);
const matchingValues = values.filter((value) => value.includes(substring));
if (matchingValues.length === 0) return null;
return obj.OutputValue;
}
async function confirmAction(query) {
const readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
readlineInterface.on('SIGINT', () => process.exit(-1));
const answer = await new Promise((resolve) => {
readlineInterface.question(`\n${query} `, (ans) => {
readlineInterface.close();
resolve(ans);
});
});
if (answer.toLowerCase() === 'y' || answer.toLowerCase() === '') {
return true;
}
if (answer.toLowerCase() === 'n') {
return false;
}
console.info('Invalid answer provided.');
return confirmAction(query);
}
async function readUserInput(
query,
{ validator = () => true, validationMessage = 'Invalid answer provided.' }
) {
const readlineInterface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
readlineInterface.on('SIGINT', () => process.exit(-1));
const answer = await new Promise((resolve) => {
readlineInterface.question(`\n${query} `, (ans) => {
readlineInterface.close();
resolve(ans);
});
});
if (validator(answer)) {
return answer;
}
console.info(validationMessage);
return readUserInput(query, validator);
}